Merge remote-tracking branch 'eugenp/master'
This commit is contained in:
commit
d0f455971e
|
@ -2,7 +2,7 @@
|
|||
The "REST with Spring" Classes
|
||||
==============================
|
||||
|
||||
After 5 months of work, here's the Master Class of REST With Spring: <br/>
|
||||
Here's the Master Class of REST With Spring (price changes permanently next Friday): <br/>
|
||||
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||
|
||||
And here's the Master Class of Learn Spring Security: <br/>
|
||||
|
|
|
@ -87,7 +87,7 @@ public class State {
|
|||
void randomPlay() {
|
||||
List<Position> availablePositions = this.board.getEmptyPositions();
|
||||
int totalPossibilities = availablePositions.size();
|
||||
int selectRandom = (int) (Math.random() * ((totalPossibilities - 1) + 1));
|
||||
int selectRandom = (int) (Math.random() * totalPossibilities);
|
||||
this.board.performMove(this.playerNo, availablePositions.get(selectRandom));
|
||||
}
|
||||
|
||||
|
|
|
@ -65,7 +65,7 @@ public class Node {
|
|||
|
||||
public Node getRandomChildNode() {
|
||||
int noOfPossibleMoves = this.childArray.size();
|
||||
int selectRandom = (int) (Math.random() * ((noOfPossibleMoves - 1) + 1));
|
||||
int selectRandom = (int) (Math.random() * noOfPossibleMoves);
|
||||
return this.childArray.get(selectRandom);
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,35 @@
|
|||
package com.baeldung.algorithms.string;
|
||||
|
||||
public class EnglishAlphabetLetters {
|
||||
|
||||
public static boolean checkStringForAllTheLetters(String input) {
|
||||
boolean[] visited = new boolean[26];
|
||||
|
||||
int index = 0;
|
||||
|
||||
for (int id = 0; id < input.length(); id++) {
|
||||
if ('a' <= input.charAt(id) && input.charAt(id) <= 'z') {
|
||||
index = input.charAt(id) - 'a';
|
||||
} else if ('A' <= input.charAt(id) && input.charAt(id) <= 'Z') {
|
||||
index = input.charAt(id) - 'A';
|
||||
}
|
||||
visited[index] = true;
|
||||
}
|
||||
|
||||
for (int id = 0; id < 26; id++) {
|
||||
if (!visited[id]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean checkStringForAllLetterUsingStream(String input) {
|
||||
long c = input.toLowerCase().chars().filter(ch -> ch >= 'a' && ch <= 'z').distinct().count();
|
||||
return c == 26;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
checkStringForAllLetterUsingStream("intit");
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms;
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms;
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms;
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
import org.junit.Test;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms;
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
import com.baeldung.algorithms.hillclimbing.HillClimbing;
|
||||
import com.baeldung.algorithms.hillclimbing.State;
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms;
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
import com.baeldung.algorithms.middleelementlookup.MiddleElementLookup;
|
||||
import com.baeldung.algorithms.middleelementlookup.Node;
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms;
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
import com.baeldung.algorithms.automata.*;
|
||||
import org.junit.Test;
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms;
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms;
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
|
||||
import org.junit.Assert;
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms.binarysearch;
|
||||
package com.baeldung.algorithms.binarysearch;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms.mcts;
|
||||
package com.baeldung.algorithms.mcts;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms.minimax;
|
||||
package com.baeldung.algorithms.minimax;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.algorithms.string;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class EnglishAlphabetLettersUnitTest {
|
||||
|
||||
@Test
|
||||
void givenString_whenContainsAllCharacter_thenTrue() {
|
||||
String input = "Farmer jack realized that big yellow quilts were expensive";
|
||||
Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllTheLetters(input));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenContainsAllCharacter_thenUsingStreamExpectTrue() {
|
||||
String input = "Farmer jack realized that big yellow quilts were expensive";
|
||||
Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllLetterUsingStream(input));
|
||||
}
|
||||
|
||||
}
|
|
@ -9,33 +9,18 @@
|
|||
- [Java 8 New Features](http://www.baeldung.com/java-8-new-features)
|
||||
- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
|
||||
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
|
||||
- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams)
|
||||
- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction)
|
||||
- [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector)
|
||||
- [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern)
|
||||
- [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams)
|
||||
- [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions)
|
||||
- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany)
|
||||
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
|
||||
- [How to Get the Last Element of a Stream in Java?](http://www.baeldung.com/java-stream-last-element)
|
||||
- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro)
|
||||
- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api)
|
||||
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)
|
||||
- [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java)
|
||||
- [Get the Current Date, Time and Timestamp in Java 8](http://www.baeldung.com/current-date-time-and-timestamp-in-java-8)
|
||||
- [TemporalAdjuster in Java](http://www.baeldung.com/java-temporal-adjuster)
|
||||
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
|
||||
- [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode)
|
||||
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
|
||||
- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)
|
||||
- [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception)
|
||||
- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
|
||||
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
|
||||
- [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods)
|
||||
- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream)
|
||||
- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices)
|
||||
- [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency)
|
||||
- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams)
|
||||
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
|
||||
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
|
||||
- [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator)
|
||||
|
@ -44,15 +29,10 @@
|
|||
- [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max)
|
||||
- [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization)
|
||||
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
|
||||
- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time)
|
||||
- [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get)
|
||||
- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
|
||||
- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection)
|
||||
- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic)
|
||||
- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
|
||||
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
|
||||
- [Calculate Age in Java](http://www.baeldung.com/java-get-age)
|
||||
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
|
||||
- [Increment Date in Java](http://www.baeldung.com/java-increment-date)
|
||||
- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date)
|
||||
- [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time)
|
||||
|
|
|
@ -89,11 +89,6 @@
|
|||
<artifactId>vavr</artifactId>
|
||||
<version>${vavr.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>one.util</groupId>
|
||||
<artifactId>streamex</artifactId>
|
||||
<version>${streamex.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
|
@ -177,7 +172,6 @@
|
|||
<lombok.version>1.16.12</lombok.version>
|
||||
<vavr.version>0.9.0</vavr.version>
|
||||
<protonpack.version>1.13</protonpack.version>
|
||||
<streamex.version>0.6.5</streamex.version>
|
||||
<joda.version>2.10</joda.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.optional;
|
||||
|
||||
public class PersonRepository {
|
||||
|
||||
public String findNameById(String id) {
|
||||
return id == null ? null : "Name";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
public class BenchmarkRunner {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
new IntPrimitiveLookup().run();
|
||||
new IntegerWrapperLookup().run();
|
||||
new FloatPrimitiveLookup().run();
|
||||
new FloatWrapperLookup().run();
|
||||
new DoublePrimitiveLookup().run();
|
||||
new DoubleWrapperLookup().run();
|
||||
new ShortPrimitiveLookup().run();
|
||||
new ShortWrapperLookup().run();
|
||||
new BooleanPrimitiveLookup().run();
|
||||
new BooleanWrapperLookup().run();
|
||||
new CharPrimitiveLookup().run();
|
||||
new CharacterWrapperLookup().run();
|
||||
new BytePrimitiveLookup().run();
|
||||
new ByteWrapperLookup().run();
|
||||
new LongPrimitiveLookup().run();
|
||||
new LongWrapperLookup().run();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class BooleanPrimitiveLookup extends Lookup {
|
||||
|
||||
private boolean[] elements;
|
||||
private final boolean pivot = false;
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
elements = new boolean[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = true;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@TearDown
|
||||
@Override
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
while (pivot != elements[index]) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return BooleanPrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class BooleanWrapperLookup extends Lookup {
|
||||
private Boolean[] elements;
|
||||
private final boolean pivot = false;
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
elements = new Boolean[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = true;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@Override
|
||||
@TearDown
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
Boolean pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return BooleanWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class BytePrimitiveLookup extends Lookup {
|
||||
|
||||
private byte[] elements;
|
||||
private final byte pivot = 2;
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
byte common = 1;
|
||||
elements = new byte[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@TearDown
|
||||
@Override
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
while (pivot != elements[index]) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return BytePrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class ByteWrapperLookup extends Lookup {
|
||||
private Byte[] elements;
|
||||
private final byte pivot = 2;
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
byte common = 1;
|
||||
elements = new Byte[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@Override
|
||||
@TearDown
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
Byte pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return ByteWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class CharPrimitiveLookup extends Lookup {
|
||||
|
||||
private char[] elements;
|
||||
private final char pivot = 'b';
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
char common = 'a';
|
||||
elements = new char[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@TearDown
|
||||
@Override
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
while (pivot != elements[index]) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return CharPrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class CharacterWrapperLookup extends Lookup {
|
||||
private Character[] elements;
|
||||
private final char pivot = 'b';
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
char common = 'a';
|
||||
elements = new Character[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@Override
|
||||
@TearDown
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
Character pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return CharacterWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class DoublePrimitiveLookup extends Lookup {
|
||||
private double[] elements;
|
||||
private final double pivot = 2;
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
double common = 1;
|
||||
elements = new double[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@TearDown
|
||||
@Override
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
while (pivot != elements[index]) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return DoublePrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class DoubleWrapperLookup extends Lookup {
|
||||
private Double[] elements;
|
||||
private final double pivot = 2d;
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
double common = 1;
|
||||
elements = new Double[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@Override
|
||||
@TearDown
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
Double pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return DoubleWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class FloatPrimitiveLookup extends Lookup {
|
||||
private float[] elements;
|
||||
private final float pivot = 2;
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
int common = 1;
|
||||
elements = new float[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@TearDown
|
||||
@Override
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
while (pivot != elements[index]) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return FloatPrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class FloatWrapperLookup extends Lookup {
|
||||
private Float[] elements;
|
||||
private final float pivot = 2;
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
float common = 1;
|
||||
elements = new Float[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@Override
|
||||
@TearDown
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
Float pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return FloatWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class IntPrimitiveLookup extends Lookup {
|
||||
|
||||
private int[] elements;
|
||||
private final int pivot = 2;
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
int common = 1;
|
||||
elements = new int[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@TearDown
|
||||
@Override
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
while (pivot != elements[index]) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return IntPrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class IntegerWrapperLookup extends Lookup {
|
||||
private Integer[] elements;
|
||||
private final int pivot = 2;
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
int common = 1;
|
||||
elements = new Integer[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@Override
|
||||
@TearDown
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
Integer pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return IntegerWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class LongPrimitiveLookup extends Lookup {
|
||||
private long[] elements;
|
||||
private final long pivot = 2;
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
long common = 1;
|
||||
elements = new long[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@TearDown
|
||||
@Override
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
while (pivot != elements[index]) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return LongPrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class LongWrapperLookup extends Lookup{
|
||||
private Long[] elements;
|
||||
private final long pivot = 2;
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
long common = 1;
|
||||
elements = new Long[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@Override
|
||||
@TearDown
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
Long pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return LongWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,56 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.results.RunResult;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.RunnerException;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* An abstract class that is to be extended by the classes that
|
||||
* perform lookup in the arrays either of Java primitive types or their wrappers.
|
||||
*/
|
||||
public abstract class Lookup {
|
||||
/**
|
||||
* the array size
|
||||
*/
|
||||
final protected int s = 50000000;
|
||||
|
||||
/**
|
||||
* Initialize the array: fill in the array with the same
|
||||
* elements except for the last one.
|
||||
*/
|
||||
abstract public void prepare();
|
||||
|
||||
/**
|
||||
* Free the array's reference.
|
||||
*/
|
||||
abstract public void clean();
|
||||
|
||||
/**
|
||||
* Find the position of the element that is different from the others.
|
||||
* By construction, it is the last array element.
|
||||
*
|
||||
* @return array's last element index
|
||||
*/
|
||||
abstract public int findPosition();
|
||||
|
||||
/**
|
||||
* Get the name of the class that extends this one. It is needed in order
|
||||
* to set up the benchmark.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
abstract public String getSimpleClassName();
|
||||
|
||||
Collection<RunResult> run() throws RunnerException {
|
||||
Options opt = new OptionsBuilder()
|
||||
.include(getSimpleClassName())
|
||||
.forks(1)
|
||||
.build();
|
||||
return new Runner(opt).run();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class ShortPrimitiveLookup extends Lookup {
|
||||
|
||||
private short[] elements;
|
||||
private final short pivot = 2;
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
short common = 1;
|
||||
elements = new short[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@TearDown
|
||||
@Override
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
while (pivot != elements[index]) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return ShortPrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class ShortWrapperLookup extends Lookup {
|
||||
private Short[] elements;
|
||||
private final short pivot = 2;
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
short common = 1;
|
||||
elements = new Short[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@Override
|
||||
@TearDown
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
Short pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return ShortWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.optional;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
public class PersonRepositoryUnitTest {
|
||||
|
||||
PersonRepository personRepository = new PersonRepository();
|
||||
|
||||
@Test
|
||||
public void whenIdIsNull_thenExceptionIsThrown() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() ->
|
||||
Optional
|
||||
.ofNullable(personRepository.findNameById(null))
|
||||
.orElseThrow(IllegalArgumentException::new));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIdIsNonNull_thenNoExceptionIsThrown() {
|
||||
assertAll(
|
||||
() ->
|
||||
Optional
|
||||
.ofNullable(personRepository.findNameById("id"))
|
||||
.orElseThrow(RuntimeException::new));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIdNonNull_thenReturnsNameUpperCase() {
|
||||
String name = Optional
|
||||
.ofNullable(personRepository.findNameById("id"))
|
||||
.map(String::toUpperCase)
|
||||
.orElseThrow(RuntimeException::new);
|
||||
|
||||
assertEquals("NAME", name);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,97 @@
|
|||
package com.baeldung.streamordering;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.infra.Blackhole;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
import org.openjdk.jmh.runner.options.TimeValue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
|
||||
public class BenchmarkUnitTest
|
||||
{
|
||||
|
||||
@Test
|
||||
public void
|
||||
launchBenchmark() throws Exception {
|
||||
|
||||
Options opt = new OptionsBuilder()
|
||||
// Specify which benchmarks to run.
|
||||
// You can be more specific if you'd like to run only one benchmark per test.
|
||||
.include(this.getClass().getName() + ".*")
|
||||
// Set the following options as needed
|
||||
.mode (Mode.AverageTime)
|
||||
.timeUnit(TimeUnit.MICROSECONDS)
|
||||
.warmupTime(TimeValue.seconds(1))
|
||||
.warmupIterations(2)
|
||||
.measurementTime(TimeValue.seconds(1))
|
||||
.measurementIterations(2)
|
||||
.threads(2)
|
||||
.forks(1)
|
||||
.shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
//.jvmArgs("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining")
|
||||
//.addProfiler(WinPerfAsmProfiler.class)
|
||||
.build();
|
||||
|
||||
new Runner(opt).run();
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenOrderedStreamInput_whenStreamFiltered_showOpsPerMS(){
|
||||
IntStream.range(1, 100_000_000).parallel().filter(i -> i % 10 == 0).toArray();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenUnorderedStreamInput_whenStreamFiltered_showOpsPerMS(){
|
||||
IntStream.range(1,100_000_000).unordered().parallel().filter(i -> i % 10 == 0).toArray();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenUnorderedStreamInput_whenStreamDistinct_showOpsPerMS(){
|
||||
IntStream.range(1, 1_000_000).unordered().parallel().distinct().toArray();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenOrderedStreamInput_whenStreamDistinct_showOpsPerMS() {
|
||||
//section 5.1.
|
||||
IntStream.range(1, 1_000_000).parallel().distinct().toArray();
|
||||
}
|
||||
|
||||
|
||||
// The JMH samples are the best documentation for how to use it
|
||||
// http://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/
|
||||
@State(Scope.Thread)
|
||||
public static class BenchmarkState
|
||||
{
|
||||
List<Integer> list;
|
||||
|
||||
@Setup(Level.Trial) public void
|
||||
initialize() {
|
||||
|
||||
Random rand = new Random();
|
||||
|
||||
list = new ArrayList<>();
|
||||
for (int i = 0; i < 1000; i++)
|
||||
list.add (rand.nextInt());
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark public void
|
||||
benchmark1 (BenchmarkState state, Blackhole bh) {
|
||||
|
||||
List<Integer> list = state.list;
|
||||
|
||||
for (int i = 0; i < 1000; i++)
|
||||
bh.consume (list.get (i));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,149 @@
|
|||
package com.baeldung.streamordering;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StreamsOrderingUnitTest {
|
||||
|
||||
Logger logger = Logger.getLogger( StreamsOrderingUnitTest.class.getName());
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
logger.setLevel(Level.ALL);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoCollections_whenStreamed_thenCheckOutputDifferent(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
Set<String> set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F"));
|
||||
|
||||
Object[] listOutput = list.stream().toArray();
|
||||
Object[] setOutput = set.stream().toArray();
|
||||
|
||||
assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput));
|
||||
assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoCollections_whenStreamedInParallel_thenCheckOutputDifferent(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
Set<String> set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F"));
|
||||
|
||||
Object[] listOutput = list.stream().parallel().toArray();
|
||||
Object[] setOutput = set.stream().parallel().toArray();
|
||||
|
||||
assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput));
|
||||
assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput));
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void givenOrderedInput_whenUnorderedAndOrderedCompared_thenCheckUnorderedOutputChanges(){
|
||||
Set<Integer> set = new TreeSet<>(
|
||||
Arrays.asList(-9, -5, -4, -2, 1, 2, 4, 5, 7, 9, 12, 13, 16, 29, 23, 34, 57, 68, 90, 102, 230));
|
||||
|
||||
Object[] orderedArray = set.stream()
|
||||
.parallel()
|
||||
.limit(5)
|
||||
.toArray();
|
||||
Object[] unorderedArray = set.stream()
|
||||
.unordered()
|
||||
.parallel()
|
||||
.limit(5)
|
||||
.toArray();
|
||||
|
||||
logger.info(Arrays.toString(orderedArray));
|
||||
logger.info(Arrays.toString(unorderedArray));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenUnsortedStreamInput_whenStreamSorted_thenCheckOrderChanged(){
|
||||
|
||||
List<Integer> list = Arrays.asList(-3,10,-4,1,3);
|
||||
|
||||
Object[] listOutput = list.stream().toArray();
|
||||
Object[] listOutputSorted = list.stream().sorted().toArray();
|
||||
|
||||
assertEquals("[-3, 10, -4, 1, 3]", Arrays.toString(listOutput));
|
||||
assertEquals("[-4, -3, 1, 3, 10]", Arrays.toString(listOutputSorted));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedStreamInput_whenStreamDistinct_thenShowTimeTaken(){
|
||||
long start, end;
|
||||
start = System.currentTimeMillis();
|
||||
IntStream.range(1,1_000_000).unordered().parallel().distinct().toArray();
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println(String.format("Time taken when unordered: %d ms", (end - start)));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenSameCollection_whenStreamTerminated_thenCheckEachVsEachOrdered(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
|
||||
list.stream().parallel().forEach(e -> logger.log(Level.INFO, e));
|
||||
list.stream().parallel().forEachOrdered(e -> logger.log(Level.INFO, e));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSameCollection_whenStreamCollected_thenCheckOutput(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
|
||||
List<String> collectionList = list.stream().parallel().collect(Collectors.toList());
|
||||
Set<String> collectionSet = list.stream().parallel().collect(Collectors.toCollection(TreeSet::new));
|
||||
|
||||
assertEquals("[B, A, C, D, F]", collectionList.toString());
|
||||
assertEquals("[A, B, C, D, F]", collectionSet.toString());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenListIterationOrder_whenStreamCollectedToMap_thenCeckOrderChanged() {
|
||||
List<String> list = Arrays.asList("A", "BB", "CCC");
|
||||
|
||||
Map<String, Integer> hashMap = list.stream().collect(Collectors.toMap(Function.identity(), String::length));
|
||||
|
||||
Object[] keySet = hashMap.keySet().toArray();
|
||||
|
||||
assertEquals("[BB, A, CCC]", Arrays.toString(keySet));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListIteration_whenStreamCollectedtoHashMap_thenCheckOrderMaintained() {
|
||||
List<String> list = Arrays.asList("A", "BB", "CCC", "CCC");
|
||||
|
||||
Map<String, Integer> linkedHashMap = list.stream().collect(Collectors.toMap(
|
||||
Function.identity(),
|
||||
String::length,
|
||||
(u, v) -> u,
|
||||
LinkedHashMap::new
|
||||
));
|
||||
|
||||
Object[] keySet = linkedHashMap.keySet().toArray();
|
||||
|
||||
assertEquals("[A, BB, CCC]", Arrays.toString(keySet));
|
||||
}
|
||||
|
||||
}
|
|
@ -15,9 +15,7 @@
|
|||
- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity)
|
||||
- [Java 9 Optional API Additions](http://www.baeldung.com/java-9-optional)
|
||||
- [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams)
|
||||
- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
|
||||
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)
|
||||
- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime)
|
||||
- [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles)
|
||||
- [Exploring the New HTTP Client in Java 9](http://www.baeldung.com/java-9-http-client)
|
||||
- [Method Handles in Java](http://www.baeldung.com/java-method-handles)
|
||||
|
@ -25,3 +23,4 @@
|
|||
- [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity)
|
||||
- [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional)
|
||||
- [Java 9 java.lang.Module API](http://www.baeldung.com/java-9-module-api)
|
||||
- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
|
||||
|
|
|
@ -2,6 +2,7 @@ package com.baeldung.collection;
|
|||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Assert;
|
||||
|
@ -35,8 +36,9 @@ public class StreamOperateAndRemoveUnitTest {
|
|||
@Test
|
||||
public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveIf_thenListContains5Items() {
|
||||
|
||||
itemList.stream().filter(item -> item.isQualified()).forEach(item -> item.operate());
|
||||
itemList.removeIf(item -> item.isQualified());
|
||||
final Predicate<Item> isQualified = item -> item.isQualified();
|
||||
itemList.stream().filter(isQualified).forEach(item -> item.operate());
|
||||
itemList.removeIf(isQualified);
|
||||
|
||||
Assert.assertEquals(5, itemList.size());
|
||||
}
|
||||
|
|
|
@ -1,10 +1,12 @@
|
|||
package org.baeldung.java.io;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.SequenceInputStream;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
|
@ -74,6 +76,28 @@ public class JavaXToInputStreamUnitTest {
|
|||
IOUtils.closeQuietly(targetStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingPlainJava_whenConvertingFileToDataInputStream_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/test/resources/sample.txt");
|
||||
final InputStream targetStream = new DataInputStream(new FileInputStream(initialFile));
|
||||
|
||||
IOUtils.closeQuietly(targetStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingPlainJava_whenConvertingFileToSequenceInputStream_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/test/resources/sample.txt");
|
||||
final File anotherFile = new File("src/test/resources/anothersample.txt");
|
||||
final InputStream targetStream = new FileInputStream(initialFile);
|
||||
final InputStream anotherTargetStream = new FileInputStream(anotherFile);
|
||||
|
||||
InputStream sequenceTargetStream = new SequenceInputStream(targetStream, anotherTargetStream);
|
||||
|
||||
IOUtils.closeQuietly(targetStream);
|
||||
IOUtils.closeQuietly(anotherTargetStream);
|
||||
IOUtils.closeQuietly(sequenceTargetStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenConvertingFileToInputStream_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/test/resources/sample.txt");
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
...Continues
|
|
@ -47,7 +47,6 @@
|
|||
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)
|
||||
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
|
||||
- [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy)
|
||||
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
|
||||
- [Converting a Stack Trace to a String in Java](http://www.baeldung.com/java-stacktrace-to-string)
|
||||
- [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization)
|
||||
- [The StackOverflowError in Java](http://www.baeldung.com/java-stack-overflow-error)
|
||||
|
@ -75,7 +74,6 @@
|
|||
- [A Guide to Java Initialization](http://www.baeldung.com/java-initialization)
|
||||
- [Implementing a Binary Tree in Java](http://www.baeldung.com/java-binary-tree)
|
||||
- [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
|
||||
- [RegEx for matching Date Pattern in Java](http://www.baeldung.com/java-date-regular-expressions)
|
||||
- [Nested Classes in Java](http://www.baeldung.com/java-nested-classes)
|
||||
- [A Guide to Java Loops](http://www.baeldung.com/java-loops)
|
||||
- [Varargs in Java](http://www.baeldung.com/java-varargs)
|
||||
|
@ -96,7 +94,6 @@
|
|||
- [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat)
|
||||
- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os)
|
||||
- [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
|
||||
- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings)
|
||||
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
|
||||
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
|
||||
- [The "final" Keyword in Java](http://www.baeldung.com/java-final)
|
||||
|
@ -110,7 +107,6 @@
|
|||
- [Find Sum and Average in a Java Array](http://www.baeldung.com/java-array-sum-average)
|
||||
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
|
||||
- [Type Erasure in Java Explained](http://www.baeldung.com/java-type-erasure)
|
||||
- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
|
||||
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
|
||||
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
|
||||
- [Sending Emails with Java](http://www.baeldung.com/java-email)
|
||||
|
@ -135,14 +131,11 @@
|
|||
- [Guide to the this Java Keyword](http://www.baeldung.com/java-this)
|
||||
- [Jagged Arrays In Java](http://www.baeldung.com/java-jagged-arrays)
|
||||
- [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class)
|
||||
- [Extracting Year, Month and Day from Date in Java](http://www.baeldung.com/java-year-month-day)
|
||||
- [Get Date Without Time in Java](http://www.baeldung.com/java-date-without-time)
|
||||
- [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension)
|
||||
- [Immutable Objects in Java](http://www.baeldung.com/java-immutable-object)
|
||||
- [Console I/O in Java](http://www.baeldung.com/java-console-input-output)
|
||||
- [Guide to the java.util.Arrays Class](http://www.baeldung.com/java-util-arrays)
|
||||
- [Create a Custom Exception in Java](http://www.baeldung.com/java-new-custom-exception)
|
||||
- [Guide to java.util.GregorianCalendar](http://www.baeldung.com/java-gregorian-calendar)
|
||||
- [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler)
|
||||
- [Encrypting and Decrypting Files in Java](http://www.baeldung.com/java-cipher-input-output-stream)
|
||||
- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object)
|
||||
|
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.classcastexception;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class ClassCastException {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
String p1 = new String("John");
|
||||
String p2 = new String("Snow");
|
||||
String[] strArray = new String[] { p1, p2 };
|
||||
ArrayList<String> strList = (ArrayList<String>) Arrays.asList(strArray);
|
||||
// To fix the ClassCastException at above line, modify the code as:
|
||||
// List<String> strList = Arrays.asList(strArray);
|
||||
System.out.println("String list: " + strList);
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.linesintersection;
|
||||
|
||||
import java.awt.Point;
|
||||
import java.util.Optional;
|
||||
|
||||
public class LinesIntersectionService {
|
||||
|
||||
public Optional<Point> calculateIntersectionPoint(float m1, float b1, float m2, float b2) {
|
||||
|
||||
if (m1 == m2) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
float x = (b2 - b1) / (m1 - m2);
|
||||
float y = m1 * x + b1;
|
||||
|
||||
Point point = new Point(Math.round(x), Math.round(y));
|
||||
|
||||
return Optional.of(point);
|
||||
}
|
||||
}
|
|
@ -1,16 +1,10 @@
|
|||
package com.baeldung.throwsexception;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
public class PersonRepository {
|
||||
|
||||
@Nullable
|
||||
public String findNameById(String id) {
|
||||
return id == null ? null : "example-name";
|
||||
}
|
||||
|
||||
public List<String> findAll() throws SQLException {
|
||||
throw new SQLException();
|
||||
}
|
||||
|
|
|
@ -0,0 +1,40 @@
|
|||
package com.baeldung.linesintersection;
|
||||
|
||||
import java.awt.Point;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class LinesIntersectionServiceUnitTest {
|
||||
private LinesIntersectionService service = new LinesIntersectionService();
|
||||
|
||||
@Test
|
||||
public void givenNotParallelLines_whenCalculatePoint_thenPresent() {
|
||||
|
||||
float m1 = 0;
|
||||
float b1 = 0;
|
||||
float m2 = 1;
|
||||
float b2 = -1;
|
||||
|
||||
Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2);
|
||||
|
||||
assertTrue(point.isPresent());
|
||||
assertEquals(point.get().x, 1);
|
||||
assertEquals(point.get().y, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParallelLines_whenCalculatePoint_thenEmpty() {
|
||||
float m1 = 1;
|
||||
float b1 = 0;
|
||||
float m2 = 1;
|
||||
float b2 = -1;
|
||||
|
||||
Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2);
|
||||
|
||||
assertFalse(point.isPresent());
|
||||
}
|
||||
}
|
|
@ -1,32 +0,0 @@
|
|||
package com.baeldung.throwsexception;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
public class PersonRepositoryUnitTest {
|
||||
|
||||
PersonRepository personRepository = new PersonRepository();
|
||||
|
||||
@Test
|
||||
public void whenIdIsNull_thenExceptionIsThrown() throws Exception {
|
||||
assertThrows(Exception.class,
|
||||
() ->
|
||||
Optional
|
||||
.ofNullable(personRepository.findNameById(null))
|
||||
.orElseThrow(Exception::new));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIdIsNonNull_thenNoExceptionIsThrown() throws Exception {
|
||||
assertAll(
|
||||
() ->
|
||||
Optional
|
||||
.ofNullable(personRepository.findNameById("id"))
|
||||
.orElseThrow(Exception::new));
|
||||
}
|
||||
|
||||
}
|
|
@ -3,69 +3,24 @@
|
|||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-kotlin</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<artifactId>parent-kotlin</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../parent-kotlin</relativePath>
|
||||
</parent>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>jcenter</id>
|
||||
<url>http://jcenter.bintray.com</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>kotlin-ktor</id>
|
||||
<url>https://dl.bintray.com/kotlin/ktor/</url>
|
||||
<id>exposed</id>
|
||||
<name>exposed</name>
|
||||
<url>https://dl.bintray.com/kotlin/exposed</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-stdlib</artifactId>
|
||||
<version>${kotlin-stdlib.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-stdlib-jdk8</artifactId>
|
||||
<version>${kotlin-stdlib.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>khttp</groupId>
|
||||
<artifactId>khttp</artifactId>
|
||||
<version>${khttp.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-test-junit</artifactId>
|
||||
<version>${kotlin-test-junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-reflect</artifactId>
|
||||
<version>${kotlin-reflect.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlinx</groupId>
|
||||
<artifactId>kotlinx-coroutines-core</artifactId>
|
||||
<version>${kotlinx.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.spek</groupId>
|
||||
<artifactId>spek-api</artifactId>
|
||||
|
@ -84,6 +39,22 @@
|
|||
<version>1.1.5</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>khttp</groupId>
|
||||
<artifactId>khttp</artifactId>
|
||||
<version>${khttp.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.nhaarman</groupId>
|
||||
<artifactId>mockito-kotlin</artifactId>
|
||||
|
@ -107,129 +78,18 @@
|
|||
<version>${klaxon.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.ktor</groupId>
|
||||
<artifactId>ktor-server-netty</artifactId>
|
||||
<version>${ktor.io.version}</version>
|
||||
<groupId>org.jetbrains.exposed</groupId>
|
||||
<artifactId>exposed</artifactId>
|
||||
<version>${exposed.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.ktor</groupId>
|
||||
<artifactId>ktor-gson</artifactId>
|
||||
<version>${ktor.io.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>1.2.1</version>
|
||||
<scope>test</scope>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2database.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-maven-plugin</artifactId>
|
||||
<version>${kotlin-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>compile</id>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sourceDirs>
|
||||
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
|
||||
<sourceDir>${project.basedir}/src/main/java</sourceDir>
|
||||
</sourceDirs>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>test-compile</id>
|
||||
<goals>
|
||||
<goal>test-compile</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sourceDirs>
|
||||
<sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
|
||||
<sourceDir>${project.basedir}/src/test/java</sourceDir>
|
||||
</sourceDirs>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${java.version}</source>
|
||||
<target>${java.version}</target>
|
||||
</configuration>
|
||||
<executions>
|
||||
<!-- Replacing default-compile as it is treated specially
|
||||
by maven -->
|
||||
<execution>
|
||||
<id>default-compile</id>
|
||||
<phase>none</phase>
|
||||
</execution>
|
||||
<!-- Replacing default-testCompile as it is treated specially
|
||||
by maven -->
|
||||
<execution>
|
||||
<id>default-testCompile</id>
|
||||
<phase>none</phase>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>java-compile</id>
|
||||
<phase>compile</phase>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>java-test-compile</id>
|
||||
<phase>test-compile</phase>
|
||||
<goals>
|
||||
<goal>testCompile</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>${maven-failsafe-plugin.version}</version>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>junit5</id>
|
||||
<goals>
|
||||
<goal>integration-test</goal>
|
||||
<goal>verify</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<includes>
|
||||
<include>**/*Test5.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<kotlin-maven-plugin.version>1.2.60</kotlin-maven-plugin.version>
|
||||
<kotlin-test-junit.version>1.2.60</kotlin-test-junit.version>
|
||||
<kotlin-stdlib.version>1.2.60</kotlin-stdlib.version>
|
||||
<kotlin-reflect.version>1.2.60</kotlin-reflect.version>
|
||||
<kotlinx.version>0.22.5</kotlinx.version>
|
||||
<ktor.io.version>0.9.2</ktor.io.version>
|
||||
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
|
||||
<kodein.version>4.1.0</kodein.version>
|
||||
<klaxon.version>3.0.4</klaxon.version>
|
||||
|
@ -238,6 +98,8 @@
|
|||
<junit.platform.version>1.1.1</junit.platform.version>
|
||||
<junit.vintage.version>5.2.0</junit.vintage.version>
|
||||
<assertj.version>3.10.0</assertj.version>
|
||||
<h2database.version>1.4.197</h2database.version>
|
||||
<exposed.version>0.10.4</exposed.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,333 @@
|
|||
package com.baeldung.kotlin.exposed
|
||||
|
||||
import org.jetbrains.exposed.dao.*
|
||||
import org.jetbrains.exposed.sql.*
|
||||
import org.jetbrains.exposed.sql.transactions.TransactionManager
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
import org.junit.Test
|
||||
import java.sql.DriverManager
|
||||
import kotlin.test.*
|
||||
|
||||
class ExposedTest {
|
||||
|
||||
@Test
|
||||
fun whenH2Database_thenConnectionSuccessful() {
|
||||
val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
|
||||
transaction {
|
||||
assertEquals(1.4.toBigDecimal(), database.version)
|
||||
assertEquals("h2", database.vendor)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenH2DatabaseWithCredentials_thenConnectionSuccessful() {
|
||||
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver", user = "myself", password = "secret")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenH2DatabaseWithManualConnection_thenConnectionSuccessful() {
|
||||
var connected = false
|
||||
Database.connect({ connected = true; DriverManager.getConnection("jdbc:h2:mem:test;MODE=MySQL") })
|
||||
assertEquals(false, connected)
|
||||
transaction {
|
||||
addLogger(StdOutSqlLogger)
|
||||
assertEquals(false, connected)
|
||||
SchemaUtils.create(Cities)
|
||||
assertEquals(true, connected)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenManualCommit_thenOk() {
|
||||
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
|
||||
transaction {
|
||||
assertTrue(this is Transaction)
|
||||
commit()
|
||||
commit()
|
||||
commit()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenInsert_thenGeneratedKeys() {
|
||||
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
|
||||
transaction {
|
||||
SchemaUtils.create(StarWarsFilms)
|
||||
val id = StarWarsFilms.insertAndGetId {
|
||||
it[name] = "The Last Jedi"
|
||||
it[sequelId] = 8
|
||||
it[director] = "Rian Johnson"
|
||||
}
|
||||
assertEquals(1, id.value)
|
||||
val insert = StarWarsFilms.insert {
|
||||
it[name] = "The Force Awakens"
|
||||
it[sequelId] = 7
|
||||
it[director] = "J.J. Abrams"
|
||||
}
|
||||
assertEquals(2, insert[StarWarsFilms.id]?.value)
|
||||
val selectAll = StarWarsFilms.selectAll()
|
||||
selectAll.forEach {
|
||||
assertTrue { it[StarWarsFilms.sequelId] >= 7 }
|
||||
}
|
||||
StarWarsFilms.slice(StarWarsFilms.name, StarWarsFilms.director).selectAll()
|
||||
.forEach {
|
||||
assertTrue { it[StarWarsFilms.name].startsWith("The") }
|
||||
}
|
||||
val select = StarWarsFilms.select { (StarWarsFilms.director like "J.J.%") and (StarWarsFilms.sequelId eq 7) }
|
||||
assertEquals(1, select.count())
|
||||
StarWarsFilms.update ({ StarWarsFilms.sequelId eq 8 }) {
|
||||
it[name] = "Episode VIII – The Last Jedi"
|
||||
with(SqlExpressionBuilder) {
|
||||
it.update(StarWarsFilms.sequelId, StarWarsFilms.sequelId + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenForeignKey_thenAutoJoin() {
|
||||
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
|
||||
transaction {
|
||||
addLogger(StdOutSqlLogger)
|
||||
SchemaUtils.create(StarWarsFilms, Players)
|
||||
StarWarsFilms.insert {
|
||||
it[name] = "The Last Jedi"
|
||||
it[sequelId] = 8
|
||||
it[director] = "Rian Johnson"
|
||||
}
|
||||
StarWarsFilms.insert {
|
||||
it[name] = "The Force Awakens"
|
||||
it[sequelId] = 7
|
||||
it[director] = "J.J. Abrams"
|
||||
}
|
||||
Players.insert {
|
||||
it[name] = "Mark Hamill"
|
||||
it[sequelId] = 7
|
||||
}
|
||||
Players.insert {
|
||||
it[name] = "Mark Hamill"
|
||||
it[sequelId] = 8
|
||||
}
|
||||
val simpleInnerJoin = (StarWarsFilms innerJoin Players).selectAll()
|
||||
assertEquals(2, simpleInnerJoin.count())
|
||||
simpleInnerJoin.forEach {
|
||||
assertNotNull(it[StarWarsFilms.name])
|
||||
assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId])
|
||||
assertEquals("Mark Hamill", it[Players.name])
|
||||
}
|
||||
val innerJoinWithCondition = (StarWarsFilms innerJoin Players)
|
||||
.select { StarWarsFilms.sequelId eq Players.sequelId }
|
||||
assertEquals(2, innerJoinWithCondition.count())
|
||||
innerJoinWithCondition.forEach {
|
||||
assertNotNull(it[StarWarsFilms.name])
|
||||
assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId])
|
||||
assertEquals("Mark Hamill", it[Players.name])
|
||||
}
|
||||
val complexInnerJoin = Join(StarWarsFilms, Players, joinType = JoinType.INNER, onColumn = StarWarsFilms.sequelId, otherColumn = Players.sequelId, additionalConstraint = {
|
||||
StarWarsFilms.sequelId eq 8
|
||||
}).selectAll()
|
||||
assertEquals(1, complexInnerJoin.count())
|
||||
complexInnerJoin.forEach {
|
||||
assertNotNull(it[StarWarsFilms.name])
|
||||
assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId])
|
||||
assertEquals("Mark Hamill", it[Players.name])
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenJoinWithAlias_thenFun() {
|
||||
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
|
||||
transaction {
|
||||
addLogger(StdOutSqlLogger)
|
||||
SchemaUtils.create(StarWarsFilms, Players)
|
||||
StarWarsFilms.insert {
|
||||
it[name] = "The Last Jedi"
|
||||
it[sequelId] = 8
|
||||
it[director] = "Rian Johnson"
|
||||
}
|
||||
StarWarsFilms.insert {
|
||||
it[name] = "The Force Awakens"
|
||||
it[sequelId] = 7
|
||||
it[director] = "J.J. Abrams"
|
||||
}
|
||||
val sequel = StarWarsFilms.alias("sequel")
|
||||
Join(StarWarsFilms, sequel,
|
||||
additionalConstraint = { sequel[StarWarsFilms.sequelId] eq StarWarsFilms.sequelId + 1 })
|
||||
.selectAll().forEach {
|
||||
assertEquals(it[sequel[StarWarsFilms.sequelId]], it[StarWarsFilms.sequelId] + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenEntity_thenDAO() {
|
||||
val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
|
||||
val connection = database.connector.invoke() //Keep a connection open so the DB is not destroyed after the first transaction
|
||||
val inserted = transaction {
|
||||
addLogger(StdOutSqlLogger)
|
||||
SchemaUtils.create(StarWarsFilms, Players)
|
||||
val theLastJedi = StarWarsFilm.new {
|
||||
name = "The Last Jedi"
|
||||
sequelId = 8
|
||||
director = "Rian Johnson"
|
||||
}
|
||||
assertFalse(TransactionManager.current().entityCache.inserts.isEmpty())
|
||||
assertEquals(1, theLastJedi.id.value) //Reading this causes a flush
|
||||
assertTrue(TransactionManager.current().entityCache.inserts.isEmpty())
|
||||
theLastJedi
|
||||
}
|
||||
transaction {
|
||||
val theLastJedi = StarWarsFilm.findById(1)
|
||||
assertNotNull(theLastJedi)
|
||||
assertEquals(inserted.id, theLastJedi?.id)
|
||||
}
|
||||
connection.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenManyToOne_thenNavigation() {
|
||||
val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
|
||||
val connection = database.connector.invoke()
|
||||
transaction {
|
||||
addLogger(StdOutSqlLogger)
|
||||
SchemaUtils.create(StarWarsFilms, Players, Users, UserRatings)
|
||||
val theLastJedi = StarWarsFilm.new {
|
||||
name = "The Last Jedi"
|
||||
sequelId = 8
|
||||
director = "Rian Johnson"
|
||||
}
|
||||
val someUser = User.new {
|
||||
name = "Some User"
|
||||
}
|
||||
val rating = UserRating.new {
|
||||
value = 9
|
||||
user = someUser
|
||||
film = theLastJedi
|
||||
}
|
||||
assertEquals(theLastJedi, rating.film)
|
||||
assertEquals(someUser, rating.user)
|
||||
assertEquals(rating, theLastJedi.ratings.first())
|
||||
}
|
||||
transaction {
|
||||
val theLastJedi = StarWarsFilm.find { StarWarsFilms.sequelId eq 8 }.first()
|
||||
val ratings = UserRating.find { UserRatings.film eq theLastJedi.id }
|
||||
assertEquals(1, ratings.count())
|
||||
val rating = ratings.first()
|
||||
assertEquals("Some User", rating.user.name)
|
||||
assertEquals(rating, theLastJedi.ratings.first())
|
||||
UserRating.new {
|
||||
value = 8
|
||||
user = rating.user
|
||||
film = theLastJedi
|
||||
}
|
||||
assertEquals(2, theLastJedi.ratings.count())
|
||||
}
|
||||
connection.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenManyToMany_thenAssociation() {
|
||||
val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
|
||||
val connection = database.connector.invoke()
|
||||
val film = transaction {
|
||||
SchemaUtils.create(StarWarsFilms)
|
||||
StarWarsFilm.new {
|
||||
name = "The Last Jedi"
|
||||
sequelId = 8
|
||||
director = "Rian Johnson"
|
||||
}
|
||||
}
|
||||
|
||||
val actor = transaction {
|
||||
SchemaUtils.create(Actors)
|
||||
Actor.new {
|
||||
firstname = "Daisy"
|
||||
lastname = "Ridley"
|
||||
}
|
||||
}
|
||||
|
||||
transaction {
|
||||
SchemaUtils.create(StarWarsFilmActors)
|
||||
film.actors = SizedCollection(listOf(actor))
|
||||
}
|
||||
connection.close()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
object Cities: IntIdTable() {
|
||||
val name = varchar("name", 50)
|
||||
}
|
||||
|
||||
object StarWarsFilms_Simple : Table() {
|
||||
val id = integer("id").autoIncrement().primaryKey()
|
||||
val sequelId = integer("sequel_id").uniqueIndex()
|
||||
val name = varchar("name", 50)
|
||||
val director = varchar("director", 50)
|
||||
}
|
||||
|
||||
object StarWarsFilms : IntIdTable() {
|
||||
val sequelId = integer("sequel_id").uniqueIndex()
|
||||
val name = varchar("name", 50)
|
||||
val director = varchar("director", 50)
|
||||
}
|
||||
|
||||
object Players : Table() {
|
||||
//val sequelId = integer("sequel_id").uniqueIndex().references(StarWarsFilms.sequelId)
|
||||
val sequelId = reference("sequel_id", StarWarsFilms.sequelId).uniqueIndex()
|
||||
//val filmId = reference("film_id", StarWarsFilms).nullable()
|
||||
val name = varchar("name", 50)
|
||||
}
|
||||
|
||||
class StarWarsFilm(id: EntityID<Int>) : Entity<Int>(id) {
|
||||
companion object : EntityClass<Int, StarWarsFilm>(StarWarsFilms)
|
||||
|
||||
var sequelId by StarWarsFilms.sequelId
|
||||
var name by StarWarsFilms.name
|
||||
var director by StarWarsFilms.director
|
||||
var actors by Actor via StarWarsFilmActors
|
||||
val ratings by UserRating referrersOn UserRatings.film
|
||||
}
|
||||
|
||||
object Users: IntIdTable() {
|
||||
val name = varchar("name", 50)
|
||||
}
|
||||
|
||||
object UserRatings: IntIdTable() {
|
||||
val value = long("value")
|
||||
val film = reference("film", StarWarsFilms)
|
||||
val user = reference("user", Users)
|
||||
}
|
||||
|
||||
class User(id: EntityID<Int>): IntEntity(id) {
|
||||
companion object : IntEntityClass<User>(Users)
|
||||
|
||||
var name by Users.name
|
||||
}
|
||||
|
||||
class UserRating(id: EntityID<Int>): IntEntity(id) {
|
||||
companion object : IntEntityClass<UserRating>(UserRatings)
|
||||
|
||||
var value by UserRatings.value
|
||||
var film by StarWarsFilm referencedOn UserRatings.film
|
||||
var user by User referencedOn UserRatings.user
|
||||
}
|
||||
|
||||
object Actors: IntIdTable() {
|
||||
val firstname = varchar("firstname", 50)
|
||||
val lastname = varchar("lastname", 50)
|
||||
}
|
||||
|
||||
class Actor(id: EntityID<Int>): IntEntity(id) {
|
||||
companion object : IntEntityClass<Actor>(Actors)
|
||||
|
||||
var firstname by Actors.firstname
|
||||
var lastname by Actors.lastname
|
||||
}
|
||||
|
||||
object StarWarsFilmActors : Table() {
|
||||
val starWarsFilm = reference("starWarsFilm", StarWarsFilms).primaryKey(0)
|
||||
val actor = reference("actor", Actors).primaryKey(1)
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.hibernate.joincolumn;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Address {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "ZIP")
|
||||
private String zipCode;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getZipCode() {
|
||||
return zipCode;
|
||||
}
|
||||
|
||||
public void setZipCode(String zipCode) {
|
||||
this.zipCode = zipCode;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
package com.baeldung.hibernate.joincolumn;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToOne;
|
||||
|
||||
@Entity
|
||||
public class Email {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
private String address;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "employee_id")
|
||||
private Employee employee;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public Employee getEmployee() {
|
||||
return employee;
|
||||
}
|
||||
|
||||
public void setEmployee(Employee employee) {
|
||||
this.employee = employee;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.hibernate.joincolumn;
|
||||
|
||||
import java.util.List;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.OneToMany;
|
||||
|
||||
@Entity
|
||||
public class Employee {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@OneToMany(fetch = FetchType.LAZY, mappedBy = "employee")
|
||||
private List<Email> emails;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public List<Email> getEmails() {
|
||||
return emails;
|
||||
}
|
||||
|
||||
public void setEmails(List<Email> emails) {
|
||||
this.emails = emails;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.hibernate.joincolumn;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.JoinColumns;
|
||||
import javax.persistence.ManyToOne;
|
||||
|
||||
@Entity
|
||||
public class Office {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumns({
|
||||
@JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
|
||||
@JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
|
||||
})
|
||||
private Address address;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(Address address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
package com.baeldung.hibernate.joincolumn;
|
||||
|
||||
import com.baeldung.hibernate.HibernateUtil;
|
||||
import java.io.IOException;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.Transaction;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
|
||||
public class JoinColumnIntegrationTest {
|
||||
|
||||
private Session session;
|
||||
private Transaction transaction;
|
||||
|
||||
@Before
|
||||
public void setUp() throws IOException {
|
||||
session = HibernateUtil.getSessionFactory("hibernate-spatial.properties")
|
||||
.openSession();
|
||||
transaction = session.beginTransaction();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
transaction.rollback();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOfficeEntity_setAddress_shouldPersist() {
|
||||
Office office = new Office();
|
||||
|
||||
Address address = new Address();
|
||||
address.setZipCode("11-111");
|
||||
office.setAddress(address);
|
||||
|
||||
session.save(office);
|
||||
session.flush();
|
||||
session.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeEntity_setEmails_shouldPersist() {
|
||||
Employee employee = new Employee();
|
||||
|
||||
Email email = new Email();
|
||||
email.setAddress("example@email.com");
|
||||
email.setEmployee(employee);
|
||||
|
||||
session.save(employee);
|
||||
session.flush();
|
||||
session.clear();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
<idea-plugin>
|
||||
<id>com.baeldung.intellij.stackoverflowplugin</id>
|
||||
<name>Stack Overflow Plugin for IntelliJ</name>
|
||||
<version>1.0</version>
|
||||
<vendor email="eugene@baeldung.com" url="http://www.baeldung.com">Baeldung</vendor>
|
||||
|
||||
<description><![CDATA[
|
||||
Plugin to help search Stack Overflow from inside IntelliJ
|
||||
]]></description>
|
||||
|
||||
<change-notes><![CDATA[
|
||||
<ul>
|
||||
<li>1.0 - Initial release</li>
|
||||
</ul>
|
||||
]]>
|
||||
</change-notes>
|
||||
|
||||
<!-- please see http://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/build_number_ranges.html for description -->
|
||||
<idea-version since-build="173.0"/>
|
||||
|
||||
<!-- please see http://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/plugin_compatibility.html
|
||||
on how to target different products -->
|
||||
<!-- uncomment to enable plugin in all products
|
||||
<depends>com.intellij.modules.lang</depends>
|
||||
-->
|
||||
|
||||
<extensions defaultExtensionNs="com.intellij">
|
||||
<!-- Add your extensions here -->
|
||||
</extensions>
|
||||
|
||||
<actions>
|
||||
|
||||
<!-- Add Ask question action to Tools Menu -->
|
||||
<action id="StackOverflow.AskQuestion.ToolsMenu"
|
||||
class="com.baeldung.intellij.stackoverflowplugin.AskQuestionAction"
|
||||
text="Ask Question on Stack Overflow"
|
||||
icon="so-icon-16x16.png"
|
||||
description="Ask a Question on Stack Overflow">
|
||||
<add-to-group group-id="ToolsMenu" anchor="last"/>
|
||||
</action>
|
||||
|
||||
<!-- Add action to search Stack Overflow from file editor -->
|
||||
<action id="StackOverflow.Search.Editor"
|
||||
class="com.baeldung.intellij.stackoverflowplugin.SearchAction"
|
||||
text="Search on Stack Overflow"
|
||||
icon="so-icon-16x16.png"
|
||||
description="Search on Stack Overflow">
|
||||
<add-to-group group-id="EditorPopupMenu" anchor="last"/>
|
||||
</action>
|
||||
|
||||
<!-- Add action to search Stack Overflow from console editor -->
|
||||
<action id="StackOverflow.Search.Console"
|
||||
class="com.baeldung.intellij.stackoverflowplugin.SearchAction"
|
||||
text="Search on Stack Overflow"
|
||||
icon="so-icon-16x16.png"
|
||||
description="Search on Stack Overflow">
|
||||
<add-to-group group-id="ConsoleEditorPopupMenu" anchor="last"/>
|
||||
</action>
|
||||
|
||||
</actions>
|
||||
|
||||
</idea-plugin>
|
Binary file not shown.
After Width: | Height: | Size: 454 B |
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.intellij.stackoverflowplugin;
|
||||
|
||||
import com.intellij.ide.BrowserUtil;
|
||||
import com.intellij.openapi.actionSystem.AnAction;
|
||||
import com.intellij.openapi.actionSystem.AnActionEvent;
|
||||
|
||||
public class AskQuestionAction extends AnAction
|
||||
{
|
||||
@Override
|
||||
public void actionPerformed(AnActionEvent e)
|
||||
{
|
||||
BrowserUtil.browse("https://stackoverflow.com/questions/ask");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
package com.baeldung.intellij.stackoverflowplugin;
|
||||
|
||||
import com.intellij.ide.BrowserUtil;
|
||||
import com.intellij.lang.Language;
|
||||
import com.intellij.openapi.actionSystem.ActionManager;
|
||||
import com.intellij.openapi.actionSystem.AnAction;
|
||||
import com.intellij.openapi.actionSystem.AnActionEvent;
|
||||
import com.intellij.openapi.actionSystem.CommonDataKeys;
|
||||
import com.intellij.openapi.editor.CaretModel;
|
||||
import com.intellij.openapi.editor.Editor;
|
||||
import com.intellij.psi.PsiFile;
|
||||
|
||||
public class SearchAction extends AnAction
|
||||
{
|
||||
/**
|
||||
* Convert selected text to a URL friendly string.
|
||||
* @param e
|
||||
*/
|
||||
@Override
|
||||
public void actionPerformed(AnActionEvent e)
|
||||
{
|
||||
final Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
|
||||
CaretModel caretModel = editor.getCaretModel();
|
||||
|
||||
// For searches from the editor, we should also get file type information
|
||||
// to help add scope to the search using the Stack overflow search syntax.
|
||||
//
|
||||
// https://stackoverflow.com/help/searching
|
||||
|
||||
String languageTag = "";
|
||||
PsiFile file = e.getData(CommonDataKeys.PSI_FILE);
|
||||
if(file != null)
|
||||
{
|
||||
Language lang = e.getData(CommonDataKeys.PSI_FILE).getLanguage();
|
||||
languageTag = "+[" + lang.getDisplayName().toLowerCase() + "]";
|
||||
}
|
||||
|
||||
// The update method below is only called periodically so need
|
||||
// to be careful to check for selected text
|
||||
if(caretModel.getCurrentCaret().hasSelection())
|
||||
{
|
||||
String query = caretModel.getCurrentCaret().getSelectedText().replace(' ', '+') + languageTag;
|
||||
BrowserUtil.browse("https://stackoverflow.com/search?q=" + query);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Only make this action visible when text is selected.
|
||||
* @param e
|
||||
*/
|
||||
@Override
|
||||
public void update(AnActionEvent e)
|
||||
{
|
||||
final Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
|
||||
CaretModel caretModel = editor.getCaretModel();
|
||||
e.getPresentation().setEnabledAndVisible(caretModel.getCurrentCaret().hasSelection());
|
||||
}
|
||||
}
|
|
@ -1,7 +1,6 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>jackson</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>jackson</name>
|
||||
|
@ -119,17 +118,16 @@
|
|||
|
||||
<properties>
|
||||
<!-- marshalling -->
|
||||
<jackson.version>2.9.4</jackson.version>
|
||||
<jackson.version>2.9.6</jackson.version>
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<joda-time.version>2.9.6</joda-time.version>
|
||||
<gson.version>2.8.0</gson.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<commons-lang3.version>3.8</commons-lang3.version>
|
||||
<joda-time.version>2.10</joda-time.version>
|
||||
<gson.version>2.8.5</gson.version>
|
||||
<commons-collections4.version>4.2</commons-collections4.version>
|
||||
|
||||
<!-- testing -->
|
||||
<rest-assured.version>3.0.1</rest-assured.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<rest-assured.version>3.1.1</rest-assured.version>
|
||||
<assertj.version>3.11.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,26 @@
|
|||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
*.txt
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
|
@ -0,0 +1,24 @@
|
|||
=========
|
||||
|
||||
## Java Dates Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [TemporalAdjuster in Java](http://www.baeldung.com/java-temporal-adjuster)
|
||||
- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings)
|
||||
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
|
||||
- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference)
|
||||
- [RegEx for matching Date Pattern in Java](http://www.baeldung.com/java-date-regular-expressions)
|
||||
- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api)
|
||||
- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro)
|
||||
- [Get the Current Date, Time and Timestamp in Java 8](http://www.baeldung.com/current-date-time-and-timestamp-in-java-8)
|
||||
- [Get Date Without Time in Java](http://www.baeldung.com/java-date-without-time)
|
||||
- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
|
||||
- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime)
|
||||
- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
|
||||
- [Extracting Year, Month and Day from Date in Java](http://www.baeldung.com/java-year-month-day)
|
||||
- [Guide to java.util.GregorianCalendar](http://www.baeldung.com/java-gregorian-calendar)
|
||||
- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time)
|
||||
- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
|
||||
- [Calculate Age in Java](http://www.baeldung.com/java-get-age)
|
||||
- [Increment Date in Java](http://www.baeldung.com/java-increment-date)
|
||||
- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date)
|
|
@ -0,0 +1,103 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>java-dates</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>java-dates</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${joda-time.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.darwinsys</groupId>
|
||||
<artifactId>hirondelle-date4j</artifactId>
|
||||
<version>RELEASE</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>java-dates</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<lombok.version>1.16.12</lombok.version>
|
||||
<joda-time.version>2.10</joda-time.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<maven.compiler.source>9</maven.compiler.source>
|
||||
<maven.compiler.target>9</maven.compiler.target>
|
||||
</properties>
|
||||
</project>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue