Merge branch 'master' into master
This commit is contained in:
commit
6d6cc2d50e
|
@ -3,7 +3,8 @@ language: java
|
|||
before_install:
|
||||
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
|
||||
|
||||
install: travis_wait 60 mvn -q test -fae
|
||||
install: skip
|
||||
script: travis_wait 60 mvn -q test -fae
|
||||
|
||||
sudo: required
|
||||
|
||||
|
|
|
@ -15,3 +15,4 @@
|
|||
- [Introduction to JGraphT](http://www.baeldung.com/jgrapht)
|
||||
- [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm)
|
||||
- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance)
|
||||
- [How to Find the Kth Largest Element in Java](http://www.baeldung.com/java-kth-largest-element)
|
||||
|
|
|
@ -39,6 +39,12 @@
|
|||
<artifactId>jgrapht-core</artifactId>
|
||||
<version>1.0.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.9.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
|
|
@ -0,0 +1,111 @@
|
|||
package com.baeldung.algorithms.kthlargest;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class FindKthLargest {
|
||||
|
||||
public int findKthLargestBySorting(Integer[] arr, int k) {
|
||||
Arrays.sort(arr);
|
||||
int targetIndex = arr.length - k;
|
||||
return arr[targetIndex];
|
||||
}
|
||||
|
||||
public int findKthLargestBySortingDesc(Integer[] arr, int k) {
|
||||
Arrays.sort(arr, Collections.reverseOrder());
|
||||
return arr[k - 1];
|
||||
}
|
||||
|
||||
public int findKthElementByQuickSelect(Integer[] arr, int left, int right, int k) {
|
||||
if (k >= 0 && k <= right - left + 1) {
|
||||
int pos = partition(arr, left, right);
|
||||
if (pos - left == k) {
|
||||
return arr[pos];
|
||||
}
|
||||
if (pos - left > k) {
|
||||
return findKthElementByQuickSelect(arr, left, pos - 1, k);
|
||||
}
|
||||
return findKthElementByQuickSelect(arr, pos + 1, right, k - pos + left - 1);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int findKthElementByQuickSelectWithIterativePartition(Integer[] arr, int left, int right, int k) {
|
||||
if (k >= 0 && k <= right - left + 1) {
|
||||
int pos = partitionIterative(arr, left, right);
|
||||
if (pos - left == k) {
|
||||
return arr[pos];
|
||||
}
|
||||
if (pos - left > k) {
|
||||
return findKthElementByQuickSelectWithIterativePartition(arr, left, pos - 1, k);
|
||||
}
|
||||
return findKthElementByQuickSelectWithIterativePartition(arr, pos + 1, right, k - pos + left - 1);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private int partition(Integer[] arr, int left, int right) {
|
||||
int pivot = arr[right];
|
||||
Integer[] leftArr;
|
||||
Integer[] rightArr;
|
||||
|
||||
leftArr = IntStream.range(left, right)
|
||||
.filter(i -> arr[i] < pivot)
|
||||
.map(i -> arr[i])
|
||||
.boxed()
|
||||
.toArray(Integer[]::new);
|
||||
|
||||
rightArr = IntStream.range(left, right)
|
||||
.filter(i -> arr[i] > pivot)
|
||||
.map(i -> arr[i])
|
||||
.boxed()
|
||||
.toArray(Integer[]::new);
|
||||
|
||||
int leftArraySize = leftArr.length;
|
||||
System.arraycopy(leftArr, 0, arr, left, leftArraySize);
|
||||
arr[leftArraySize + left] = pivot;
|
||||
System.arraycopy(rightArr, 0, arr, left + leftArraySize + 1, rightArr.length);
|
||||
|
||||
return left + leftArraySize;
|
||||
}
|
||||
|
||||
private int partitionIterative(Integer[] arr, int left, int right) {
|
||||
int pivot = arr[right], i = left;
|
||||
for (int j = left; j <= right - 1; j++) {
|
||||
if (arr[j] <= pivot) {
|
||||
swap(arr, i, j);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
swap(arr, i, right);
|
||||
return i;
|
||||
}
|
||||
|
||||
public int findKthElementByRandomizedQuickSelect(Integer[] arr, int left, int right, int k) {
|
||||
if (k >= 0 && k <= right - left + 1) {
|
||||
int pos = randomPartition(arr, left, right);
|
||||
if (pos - left == k) {
|
||||
return arr[pos];
|
||||
}
|
||||
if (pos - left > k) {
|
||||
return findKthElementByRandomizedQuickSelect(arr, left, pos - 1, k);
|
||||
}
|
||||
return findKthElementByRandomizedQuickSelect(arr, pos + 1, right, k - pos + left - 1);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private int randomPartition(Integer arr[], int left, int right) {
|
||||
int n = right - left + 1;
|
||||
int pivot = (int) (Math.random()) % n;
|
||||
swap(arr, left + pivot, right);
|
||||
return partition(arr, left, right);
|
||||
}
|
||||
|
||||
private void swap(Integer[] arr, int n1, int n2) {
|
||||
int temp = arr[n2];
|
||||
arr[n2] = arr[n1];
|
||||
arr[n1] = temp;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
package com.baeldung.algorithms.kthlargest;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FindKthLargestUnitTest {
|
||||
|
||||
private FindKthLargest findKthLargest;
|
||||
private Integer[] arr = { 3, 7, 1, 2, 8, 10, 4, 5, 6, 9 };
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
findKthLargest = new FindKthLargest();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntArray_whenFindKthLargestBySorting_thenGetResult() {
|
||||
int k = 3;
|
||||
assertThat(findKthLargest.findKthLargestBySorting(arr, k)).isEqualTo(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntArray_whenFindKthLargestBySortingDesc_thenGetResult() {
|
||||
int k = 3;
|
||||
assertThat(findKthLargest.findKthLargestBySortingDesc(arr, k)).isEqualTo(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntArray_whenFindKthLargestByQuickSelect_thenGetResult() {
|
||||
int k = 3;
|
||||
int kthLargest = arr.length - k;
|
||||
assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntArray_whenFindKthElementByQuickSelectIterative_thenGetResult() {
|
||||
int k = 3;
|
||||
int kthLargest = arr.length - k;
|
||||
assertThat(findKthLargest.findKthElementByQuickSelectWithIterativePartition(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntArray_whenFindKthSmallestByQuickSelect_thenGetResult() {
|
||||
int k = 3;
|
||||
assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, k - 1)).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntArray_whenFindKthLargestByRandomizedQuickSelect_thenGetResult() {
|
||||
int k = 3;
|
||||
int kthLargest = arr.length - k;
|
||||
assertThat(findKthLargest.findKthElementByRandomizedQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.streamApi;
|
||||
package com.baeldung.stream;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
|
@ -16,7 +16,7 @@ public class StreamApi {
|
|||
}
|
||||
|
||||
public static String getLastElementUsingSkip(List<String> valueList) {
|
||||
long count = valueList.stream().count();
|
||||
long count = (long) valueList.size();
|
||||
Stream<String> stream = valueList.stream();
|
||||
return stream.skip(count - 1).findFirst().orElse(null);
|
||||
}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.streamApi.Product;
|
||||
import com.baeldung.stream.Product;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
|
|
|
@ -6,6 +6,7 @@ import java.util.Arrays;
|
|||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
@ -65,7 +66,9 @@ public class PrimitiveStreamsUnitTest {
|
|||
@Test
|
||||
public void givenAnArrayWhenSumIsCalledThenTheCorrectSumIsReturned() {
|
||||
|
||||
int sum = Arrays.asList(33,45).stream().mapToInt(a -> a).sum();
|
||||
int sum = Stream.of(33,45)
|
||||
.mapToInt(i -> i)
|
||||
.sum();
|
||||
|
||||
assertEquals(78, sum);
|
||||
}
|
||||
|
|
|
@ -0,0 +1,101 @@
|
|||
package com.baeldung.stringjoiner;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.StringJoiner;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringJoinerUnitTest {
|
||||
private final String DELIMITER_COMMA = ",";
|
||||
private final String DELIMITER_HYPHEN = "-";
|
||||
private final String PREFIX = "[";
|
||||
private final String SUFFIX = "]";
|
||||
private final String EMPTY_JOINER = "empty";
|
||||
|
||||
@Test
|
||||
public void whenJoinerWithoutPrefixSuffixWithoutEmptyValue_thenReturnDefault() {
|
||||
StringJoiner commaSeparatedJoiner = new StringJoiner(DELIMITER_COMMA);
|
||||
assertEquals(0, commaSeparatedJoiner.toString().length());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoinerWithPrefixSuffixWithoutEmptyValue_thenReturnDefault() {
|
||||
StringJoiner commaSeparatedPrefixSuffixJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
|
||||
assertEquals(commaSeparatedPrefixSuffixJoiner.toString(), PREFIX + SUFFIX);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoinerWithoutPrefixSuffixWithEmptyValue_thenReturnDefault() {
|
||||
StringJoiner commaSeparatedJoiner = new StringJoiner(DELIMITER_COMMA);
|
||||
commaSeparatedJoiner.setEmptyValue(EMPTY_JOINER);
|
||||
|
||||
assertEquals(commaSeparatedJoiner.toString(), EMPTY_JOINER);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoinerWithPrefixSuffixWithEmptyValue_thenReturnDefault() {
|
||||
StringJoiner commaSeparatedPrefixSuffixJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
|
||||
commaSeparatedPrefixSuffixJoiner.setEmptyValue(EMPTY_JOINER);
|
||||
|
||||
assertEquals(commaSeparatedPrefixSuffixJoiner.toString(), EMPTY_JOINER);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddElements_thenJoinElements() {
|
||||
StringJoiner rgbJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
|
||||
rgbJoiner.add("Red")
|
||||
.add("Green")
|
||||
.add("Blue");
|
||||
|
||||
assertEquals(rgbJoiner.toString(), "[Red,Green,Blue]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddListElements_thenJoinListElements() {
|
||||
List<String> rgbList = new ArrayList<String>();
|
||||
rgbList.add("Red");
|
||||
rgbList.add("Green");
|
||||
rgbList.add("Blue");
|
||||
|
||||
StringJoiner rgbJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
|
||||
|
||||
for (String color : rgbList) {
|
||||
rgbJoiner.add(color);
|
||||
}
|
||||
|
||||
assertEquals(rgbJoiner.toString(), "[Red,Green,Blue]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMergeJoiners_thenReturnMerged() {
|
||||
StringJoiner rgbJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
|
||||
StringJoiner cmybJoiner = new StringJoiner(DELIMITER_HYPHEN, PREFIX, SUFFIX);
|
||||
|
||||
rgbJoiner.add("Red")
|
||||
.add("Green")
|
||||
.add("Blue");
|
||||
cmybJoiner.add("Cyan")
|
||||
.add("Magenta")
|
||||
.add("Yellow")
|
||||
.add("Black");
|
||||
|
||||
rgbJoiner.merge(cmybJoiner);
|
||||
|
||||
assertEquals(rgbJoiner.toString(), "[Red,Green,Blue,Cyan-Magenta-Yellow-Black]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsedWithinCollectors_thenJoin() {
|
||||
List<String> rgbList = Arrays.asList("Red", "Green", "Blue");
|
||||
String commaSeparatedRGB = rgbList.stream()
|
||||
.map(color -> color.toString())
|
||||
.collect(Collectors.joining(","));
|
||||
|
||||
assertEquals(commaSeparatedRGB, "Red,Green,Blue");
|
||||
}
|
||||
}
|
|
@ -2,10 +2,10 @@
|
|||
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>core-java9</artifactId>
|
||||
<artifactId>core-java-9</artifactId>
|
||||
<version>0.2-SNAPSHOT</version>
|
||||
|
||||
<name>core-java9</name>
|
||||
<name>core-java-9</name>
|
||||
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
|
|
|
@ -1,20 +1,21 @@
|
|||
package com.baeldung.concurrent.stopping;
|
||||
|
||||
import com.jayway.awaitility.Awaitility;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.jayway.awaitility.Awaitility.await;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.jayway.awaitility.Awaitility;
|
||||
|
||||
public class StopThreadTest {
|
||||
|
||||
@Test
|
||||
public void whenStoppedThreadIsStopped() throws InterruptedException {
|
||||
|
||||
int interval = 100;
|
||||
int interval = 5;
|
||||
|
||||
ControlSubThread controlSubThread = new ControlSubThread(interval);
|
||||
controlSubThread.start();
|
||||
|
@ -33,13 +34,13 @@ public class StopThreadTest {
|
|||
@Test
|
||||
public void whenInterruptedThreadIsStopped() throws InterruptedException {
|
||||
|
||||
int interval = 5000;
|
||||
int interval = 50;
|
||||
|
||||
ControlSubThread controlSubThread = new ControlSubThread(interval);
|
||||
controlSubThread.start();
|
||||
|
||||
// Give things a chance to get set up
|
||||
Thread.sleep(100);
|
||||
Thread.sleep(interval);
|
||||
assertTrue(controlSubThread.isRunning());
|
||||
assertFalse(controlSubThread.isStopped());
|
||||
|
||||
|
@ -48,6 +49,7 @@ public class StopThreadTest {
|
|||
|
||||
// Wait less than the time we would normally sleep, and make sure we exited.
|
||||
Awaitility.await()
|
||||
.pollDelay(2, TimeUnit.MILLISECONDS)
|
||||
.atMost(interval/ 10, TimeUnit.MILLISECONDS)
|
||||
.until(controlSubThread::isStopped);
|
||||
}
|
||||
|
|
|
@ -131,4 +131,6 @@
|
|||
- [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array)
|
||||
- [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class)
|
||||
- [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)
|
||||
|
|
|
@ -389,6 +389,16 @@
|
|||
</arguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>3.0.0-M1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
|
||||
</plugins>
|
||||
|
|
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.iteratorguide;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
|
||||
public class IteratorGuide {
|
||||
|
||||
public static void main(String[] args) {
|
||||
List<String> items = new ArrayList<>();
|
||||
items.add("ONE");
|
||||
items.add("TWO");
|
||||
items.add("THREE");
|
||||
Iterator<String> iter = items.iterator();
|
||||
while (iter.hasNext()) {
|
||||
String next = iter.next();
|
||||
System.out.println(next);
|
||||
iter.remove();
|
||||
}
|
||||
ListIterator<String> listIterator = items.listIterator();
|
||||
while(listIterator.hasNext()) {
|
||||
String nextWithIndex = items.get(listIterator.nextIndex());
|
||||
String next = listIterator.next();
|
||||
if( "ONE".equals(next)) {
|
||||
listIterator.set("SWAPPED");
|
||||
}
|
||||
}
|
||||
listIterator.add("FOUR");
|
||||
while(listIterator.hasPrevious()) {
|
||||
String previousWithIndex = items.get(listIterator.previousIndex());
|
||||
String previous = listIterator.previous();
|
||||
System.out.println(previous);
|
||||
}
|
||||
listIterator.forEachRemaining(e -> {
|
||||
System.out.println(e);
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.javadoc;
|
||||
|
||||
public class Person {
|
||||
/**
|
||||
* This is a first name
|
||||
*/
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,64 @@
|
|||
package com.baeldung.javadoc;
|
||||
|
||||
/**
|
||||
* Hero is the main entity we will be using to . . .
|
||||
* @author Captain America
|
||||
*
|
||||
*/
|
||||
public class SuperHero extends Person {
|
||||
|
||||
/**
|
||||
* The public name of a hero that is common knowledge
|
||||
*/
|
||||
private String heroName;
|
||||
private String uniquePower;
|
||||
private int health;
|
||||
private int defense;
|
||||
|
||||
/**
|
||||
* <p>This is a simple description of the method. . .
|
||||
* <a href="http://www.supermanisthegreatest.com">Superman!</a>
|
||||
* </p>
|
||||
* @param incomingDamage the amount of incoming damage
|
||||
* @return the amount of health hero has after attack
|
||||
* @see <a href="http://www.link_to_jira/HERO-402">HERO-402</a>
|
||||
* @since 1.0
|
||||
*/
|
||||
public int successfullyAttacked(int incomingDamage, String damageType) {
|
||||
// do things
|
||||
return 0;
|
||||
}
|
||||
|
||||
public String getHeroName() {
|
||||
return heroName;
|
||||
}
|
||||
|
||||
public void setHeroName(String heroName) {
|
||||
this.heroName = heroName;
|
||||
}
|
||||
|
||||
public String getUniquePower() {
|
||||
return uniquePower;
|
||||
}
|
||||
|
||||
public void setUniquePower(String uniquePower) {
|
||||
this.uniquePower = uniquePower;
|
||||
}
|
||||
|
||||
public int getHealth() {
|
||||
return health;
|
||||
}
|
||||
|
||||
public void setHealth(int health) {
|
||||
this.health = health;
|
||||
}
|
||||
|
||||
public int getDefense() {
|
||||
return defense;
|
||||
}
|
||||
|
||||
public void setDefense(int defense) {
|
||||
this.defense = defense;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.regexp.datepattern;
|
||||
|
||||
public interface DateMatcher {
|
||||
|
||||
boolean matches(String date);
|
||||
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.regexp.datepattern;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
class FormattedDateMatcher implements DateMatcher {
|
||||
|
||||
private static final Pattern DATE_PATTERN = Pattern.compile(
|
||||
"^\\d{4}-\\d{2}-\\d{2}$");
|
||||
|
||||
@Override
|
||||
public boolean matches(String date) {
|
||||
return DATE_PATTERN.matcher(date).matches();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.regexp.datepattern;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
class RangedDateMatcher implements DateMatcher {
|
||||
|
||||
private static final Pattern DATE_PATTERN = Pattern.compile(
|
||||
"^((19|2[0-9])[0-9]{2})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$");
|
||||
|
||||
@Override
|
||||
public boolean matches(String date) {
|
||||
return DATE_PATTERN.matcher(date).matches();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.regexp.datepattern.gregorian;
|
||||
|
||||
import com.baeldung.regexp.datepattern.DateMatcher;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class February29thMatcher implements DateMatcher {
|
||||
|
||||
private static final Pattern DATE_PATTERN = Pattern.compile(
|
||||
"^((2000|2400|2800|(19|2[0-9](0[48]|[2468][048]|[13579][26])))-02-29)$");
|
||||
|
||||
@Override
|
||||
public boolean matches(String date) {
|
||||
return DATE_PATTERN.matcher(date).matches();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.regexp.datepattern.gregorian;
|
||||
|
||||
import com.baeldung.regexp.datepattern.DateMatcher;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class FebruaryGeneralMatcher implements DateMatcher {
|
||||
|
||||
private static final Pattern DATE_PATTERN = Pattern.compile(
|
||||
"^(((19|2[0-9])[0-9]{2})-02-(0[1-9]|1[0-9]|2[0-8]))$");
|
||||
|
||||
@Override
|
||||
public boolean matches(String date) {
|
||||
return DATE_PATTERN.matcher(date).matches();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.regexp.datepattern.gregorian;
|
||||
|
||||
import com.baeldung.regexp.datepattern.DateMatcher;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
class GregorianDateMatcher implements DateMatcher {
|
||||
|
||||
private static final Pattern DATE_PATTERN = Pattern.compile(
|
||||
"^((2000|2400|2800|(19|2[0-9](0[48]|[2468][048]|[13579][26])))-02-29)$"
|
||||
+ "|^(((19|2[0-9])[0-9]{2})-02-(0[1-9]|1[0-9]|2[0-8]))$"
|
||||
+ "|^(((19|2[0-9])[0-9]{2})-(0[13578]|10|12)-(0[1-9]|[12][0-9]|3[01]))$"
|
||||
+ "|^(((19|2[0-9])[0-9]{2})-(0[469]|11)-(0[1-9]|[12][0-9]|30))$");
|
||||
|
||||
@Override
|
||||
public boolean matches(String date) {
|
||||
return DATE_PATTERN.matcher(date).matches();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.regexp.datepattern.gregorian;
|
||||
|
||||
import com.baeldung.regexp.datepattern.DateMatcher;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class MonthsOf30DaysMatcher implements DateMatcher {
|
||||
|
||||
private static final Pattern DATE_PATTERN = Pattern.compile(
|
||||
"^(((19|2[0-9])[0-9]{2})-(0[469]|11)-(0[1-9]|[12][0-9]|30))$");
|
||||
|
||||
@Override
|
||||
public boolean matches(String date) {
|
||||
return DATE_PATTERN.matcher(date).matches();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.regexp.datepattern.gregorian;
|
||||
|
||||
import com.baeldung.regexp.datepattern.DateMatcher;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class MonthsOf31DaysMatcher implements DateMatcher {
|
||||
|
||||
private static final Pattern DATE_PATTERN = Pattern.compile(
|
||||
"^(((19|2[0-9])[0-9]{2})-(0[13578]|10|12)-(0[1-9]|[12][0-9]|3[01]))$");
|
||||
|
||||
@Override
|
||||
public boolean matches(String date) {
|
||||
return DATE_PATTERN.matcher(date).matches();
|
||||
}
|
||||
|
||||
}
|
|
@ -16,7 +16,7 @@ public class EchoMultiServer {
|
|||
try {
|
||||
serverSocket = new ServerSocket(port);
|
||||
while (true)
|
||||
new EchoClientHandler(serverSocket.accept()).run();
|
||||
new EchoClientHandler(serverSocket.accept()).start();
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
|
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.staticclass;
|
||||
|
||||
public class Pizza {
|
||||
|
||||
private static String cookedCount;
|
||||
private boolean isThinCrust;
|
||||
|
||||
// Accessible globally
|
||||
public static class PizzaSalesCounter {
|
||||
|
||||
private static String orderedCount;
|
||||
public static String deliveredCount;
|
||||
|
||||
PizzaSalesCounter() {
|
||||
System.out.println("Static field of enclosing class is "
|
||||
+ Pizza.cookedCount);
|
||||
System.out.println("Non-static field of enclosing class is "
|
||||
+ new Pizza().isThinCrust);
|
||||
}
|
||||
}
|
||||
|
||||
Pizza() {
|
||||
System.out.println("Non private static field of static class is "
|
||||
+ PizzaSalesCounter.deliveredCount);
|
||||
System.out.println("Private static field of static class is "
|
||||
+ PizzaSalesCounter.orderedCount);
|
||||
}
|
||||
|
||||
public static void main(String[] a) {
|
||||
// Create instance of the static class without an instance of enclosing class
|
||||
new Pizza.PizzaSalesCounter();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.threadlocalrandom;
|
||||
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
public class ThreadLocalRandomBenchMarkRunner {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
Options options = new OptionsBuilder().include(ThreadLocalRandomBenchMarker.class.getSimpleName())
|
||||
.threads(1)
|
||||
.forks(1)
|
||||
.shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server")
|
||||
.build();
|
||||
|
||||
new Runner(options).run();
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,64 @@
|
|||
package com.baeldung.threadlocalrandom;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Level;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.Setup;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.annotations.Warmup;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@Warmup(iterations = 1)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
@State(Scope.Benchmark)
|
||||
public class ThreadLocalRandomBenchMarker {
|
||||
|
||||
List<Callable<Integer>> randomCallables = new ArrayList<>();
|
||||
List<Callable<Integer>> threadLocalRandomCallables = new ArrayList<>();
|
||||
|
||||
@Setup(Level.Iteration)
|
||||
public void init() {
|
||||
Random random = new Random();
|
||||
randomCallables = new ArrayList<>();
|
||||
threadLocalRandomCallables = new ArrayList<>();
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
randomCallables.add(() -> {
|
||||
return random.nextInt();
|
||||
});
|
||||
}
|
||||
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
threadLocalRandomCallables.add(() -> {
|
||||
return ThreadLocalRandom.current()
|
||||
.nextInt();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void randomValuesUsingRandom() throws InterruptedException {
|
||||
ExecutorService executor = Executors.newWorkStealingPool();
|
||||
executor.invokeAll(randomCallables);
|
||||
executor.shutdown();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void randomValuesUsingThreadLocalRandom() throws InterruptedException {
|
||||
ExecutorService executor = Executors.newWorkStealingPool();
|
||||
executor.invokeAll(threadLocalRandomCallables);
|
||||
executor.shutdown();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.regexp.datepattern;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FormattedDateMatcherUnitTest {
|
||||
|
||||
private DateMatcher matcher = new FormattedDateMatcher();
|
||||
|
||||
@Test
|
||||
public void whenUsingFormattedDateMatcher_thenFormatConstraintsSatisfied() {
|
||||
Assert.assertTrue(matcher.matches("2017-12-31"));
|
||||
Assert.assertTrue(matcher.matches("2018-01-01"));
|
||||
Assert.assertTrue(matcher.matches("0000-00-00"));
|
||||
Assert.assertTrue(matcher.matches("1029-99-72"));
|
||||
|
||||
Assert.assertFalse(matcher.matches("2018-01"));
|
||||
Assert.assertFalse(matcher.matches("2018-01-01-01"));
|
||||
Assert.assertFalse(matcher.matches("2018-01-XX"));
|
||||
Assert.assertFalse(matcher.matches(" 2018-01-01"));
|
||||
Assert.assertFalse(matcher.matches("2018-01-01 "));
|
||||
Assert.assertFalse(matcher.matches("2018/01/01"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.regexp.datepattern;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class RangedDateMatcherUnitTest {
|
||||
|
||||
private DateMatcher matcher = new RangedDateMatcher();
|
||||
|
||||
@Test
|
||||
public void whenUsingRangedDateMatcher_thenFormatConstraintsSatisfied() {
|
||||
Assert.assertFalse(matcher.matches("2018-01"));
|
||||
Assert.assertFalse(matcher.matches("2018-01-01-01"));
|
||||
Assert.assertFalse(matcher.matches("2018-01-XX"));
|
||||
Assert.assertFalse(matcher.matches(" 2018-01-01"));
|
||||
Assert.assertFalse(matcher.matches("2018-01-01 "));
|
||||
Assert.assertFalse(matcher.matches("2018/01/01"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingRangedDateMatcher_thenRangeConstraintsSatisfied() {
|
||||
Assert.assertTrue(matcher.matches("1900-01-01"));
|
||||
Assert.assertTrue(matcher.matches("2018-02-31"));
|
||||
Assert.assertTrue(matcher.matches("2999-12-31"));
|
||||
|
||||
Assert.assertFalse(matcher.matches("1899-12-31"));
|
||||
Assert.assertFalse(matcher.matches("2018-05-35"));
|
||||
Assert.assertFalse(matcher.matches("2018-13-05"));
|
||||
Assert.assertFalse(matcher.matches("3000-01-01"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.regexp.datepattern.gregorian;
|
||||
|
||||
import com.baeldung.regexp.datepattern.DateMatcher;
|
||||
import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper;
|
||||
import org.junit.Test;
|
||||
|
||||
public class February29thMatcherUnitTest {
|
||||
|
||||
private DateMatcher matcher = new February29thMatcher();
|
||||
|
||||
private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher);
|
||||
|
||||
@Test
|
||||
public void whenYearIsLeap_thenYearHasFebruary29th() {
|
||||
testHelper.assertFebruary29th();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.regexp.datepattern.gregorian;
|
||||
|
||||
import com.baeldung.regexp.datepattern.DateMatcher;
|
||||
import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FebruaryGeneralMatcherUnitTest {
|
||||
|
||||
private DateMatcher matcher = new FebruaryGeneralMatcher();
|
||||
|
||||
private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher);
|
||||
|
||||
@Test
|
||||
public void whenMonthIsFebruary_thenMonthContainsUpTo28Days() {
|
||||
testHelper.assertFebruaryGeneralDates();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.regexp.datepattern.gregorian;
|
||||
|
||||
import com.baeldung.regexp.datepattern.DateMatcher;
|
||||
import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GregorianDateMatcherUnitTest {
|
||||
|
||||
private DateMatcher matcher = new GregorianDateMatcher();
|
||||
|
||||
private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher);
|
||||
|
||||
@Test
|
||||
public void whenUsingGregorianDateMatcher_thenFormatConstraintsSatisfied() {
|
||||
testHelper.assertFormat();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingGregorianDateMatcher_thenRangeConstraintsSatisfied() {
|
||||
testHelper.assertRange();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenYearIsLeap_thenFebruaryHas29Days() {
|
||||
testHelper.assertFebruary29th();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMonthIsFebruary_thenMonthContainsUpTo28Days() {
|
||||
testHelper.assertFebruaryGeneralDates();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMonthIsShort_thenMonthContainsUpTo30Days() {
|
||||
testHelper.assertMonthsOf30Days();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMonthIsLong_thenMonthContainsUpTo31Days() {
|
||||
testHelper.assertMonthsOf31Dates();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.regexp.datepattern.gregorian;
|
||||
|
||||
import com.baeldung.regexp.datepattern.DateMatcher;
|
||||
import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper;
|
||||
import org.junit.Test;
|
||||
|
||||
public class MonthsOf30DaysMatcherUnitTest {
|
||||
|
||||
private DateMatcher matcher = new MonthsOf30DaysMatcher();
|
||||
|
||||
private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher);
|
||||
|
||||
@Test
|
||||
public void whenMonthIsShort_thenMonthContainsUpTo30Days() {
|
||||
testHelper.assertMonthsOf30Days();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.regexp.datepattern.gregorian;
|
||||
|
||||
import com.baeldung.regexp.datepattern.DateMatcher;
|
||||
import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper;
|
||||
import org.junit.Test;
|
||||
|
||||
public class MonthsOf31DaysMatcherUnitTest {
|
||||
|
||||
private DateMatcher matcher = new MonthsOf31DaysMatcher();
|
||||
|
||||
private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher);
|
||||
|
||||
@Test
|
||||
public void whenMonthIsLong_thenMonthContainsUpTo31Days() {
|
||||
testHelper.assertMonthsOf31Dates();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,102 @@
|
|||
package com.baeldung.regexp.datepattern.gregorian.testhelper;
|
||||
|
||||
import com.baeldung.regexp.datepattern.DateMatcher;
|
||||
import org.junit.Assert;
|
||||
|
||||
public class GregorianDateTestHelper {
|
||||
|
||||
private final DateMatcher matcher;
|
||||
|
||||
public GregorianDateTestHelper(DateMatcher matcher) {
|
||||
this.matcher = matcher;
|
||||
}
|
||||
|
||||
public void assertFormat() {
|
||||
Assert.assertTrue(matcher.matches("2017-12-31"));
|
||||
Assert.assertTrue(matcher.matches("2018-01-01"));
|
||||
|
||||
Assert.assertFalse(matcher.matches("2018-02"));
|
||||
Assert.assertFalse(matcher.matches("2018-02-01-01"));
|
||||
Assert.assertFalse(matcher.matches("2018-02-XX"));
|
||||
Assert.assertFalse(matcher.matches(" 2018-02-01"));
|
||||
Assert.assertFalse(matcher.matches("2018-02-01 "));
|
||||
Assert.assertFalse(matcher.matches("2020/02/28"));
|
||||
Assert.assertFalse(matcher.matches("2020.02.29"));
|
||||
}
|
||||
|
||||
public void assertRange() {
|
||||
Assert.assertTrue(matcher.matches("1900-01-01"));
|
||||
Assert.assertTrue(matcher.matches("2205-05-25"));
|
||||
Assert.assertTrue(matcher.matches("2999-12-31"));
|
||||
|
||||
Assert.assertFalse(matcher.matches("1899-12-31"));
|
||||
Assert.assertFalse(matcher.matches("2018-05-35"));
|
||||
Assert.assertFalse(matcher.matches("2018-13-05"));
|
||||
Assert.assertFalse(matcher.matches("3000-01-01"));
|
||||
Assert.assertFalse(matcher.matches("3200-02-29"));
|
||||
}
|
||||
|
||||
public void assertFebruary29th() {
|
||||
Assert.assertTrue(matcher.matches("2000-02-29"));
|
||||
Assert.assertTrue(matcher.matches("2400-02-29"));
|
||||
Assert.assertTrue(matcher.matches("2800-02-29"));
|
||||
Assert.assertTrue(matcher.matches("2020-02-29"));
|
||||
Assert.assertTrue(matcher.matches("2024-02-29"));
|
||||
Assert.assertTrue(matcher.matches("2028-02-29"));
|
||||
|
||||
Assert.assertFalse(matcher.matches("2017-02-29"));
|
||||
Assert.assertFalse(matcher.matches("2018-02-29"));
|
||||
Assert.assertFalse(matcher.matches("2019-02-29"));
|
||||
Assert.assertFalse(matcher.matches("2100-02-29"));
|
||||
Assert.assertFalse(matcher.matches("2200-02-29"));
|
||||
Assert.assertFalse(matcher.matches("2300-02-29"));
|
||||
}
|
||||
|
||||
public void assertFebruaryGeneralDates() {
|
||||
Assert.assertTrue(matcher.matches("2018-02-01"));
|
||||
Assert.assertTrue(matcher.matches("2019-02-13"));
|
||||
Assert.assertTrue(matcher.matches("2020-02-25"));
|
||||
|
||||
Assert.assertFalse(matcher.matches("2000-02-30"));
|
||||
Assert.assertFalse(matcher.matches("2400-02-62"));
|
||||
Assert.assertFalse(matcher.matches("2420-02-94"));
|
||||
}
|
||||
|
||||
public void assertMonthsOf30Days() {
|
||||
Assert.assertTrue(matcher.matches("2018-04-30"));
|
||||
Assert.assertTrue(matcher.matches("2019-06-30"));
|
||||
Assert.assertTrue(matcher.matches("2020-09-30"));
|
||||
Assert.assertTrue(matcher.matches("2021-11-30"));
|
||||
|
||||
Assert.assertTrue(matcher.matches("2022-04-02"));
|
||||
Assert.assertTrue(matcher.matches("2023-06-14"));
|
||||
Assert.assertTrue(matcher.matches("2024-09-26"));
|
||||
|
||||
Assert.assertFalse(matcher.matches("2018-04-31"));
|
||||
Assert.assertFalse(matcher.matches("2019-06-31"));
|
||||
Assert.assertFalse(matcher.matches("2020-09-31"));
|
||||
Assert.assertFalse(matcher.matches("2021-11-31"));
|
||||
|
||||
Assert.assertFalse(matcher.matches("2022-04-32"));
|
||||
Assert.assertFalse(matcher.matches("2023-06-64"));
|
||||
Assert.assertFalse(matcher.matches("2024-09-96"));
|
||||
}
|
||||
|
||||
public void assertMonthsOf31Dates() {
|
||||
Assert.assertTrue(matcher.matches("2018-01-31"));
|
||||
Assert.assertTrue(matcher.matches("2019-03-31"));
|
||||
Assert.assertTrue(matcher.matches("2020-05-31"));
|
||||
Assert.assertTrue(matcher.matches("2021-07-31"));
|
||||
Assert.assertTrue(matcher.matches("2022-08-31"));
|
||||
Assert.assertTrue(matcher.matches("2023-10-31"));
|
||||
Assert.assertTrue(matcher.matches("2024-12-31"));
|
||||
|
||||
Assert.assertTrue(matcher.matches("2025-01-03"));
|
||||
Assert.assertTrue(matcher.matches("2026-03-15"));
|
||||
Assert.assertTrue(matcher.matches("2027-05-27"));
|
||||
|
||||
Assert.assertFalse(matcher.matches("2018-01-32"));
|
||||
Assert.assertFalse(matcher.matches("2019-03-64"));
|
||||
Assert.assertFalse(matcher.matches("2020-05-96"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
package com.baeldung.threadlocalrandom;
|
||||
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ThreadLocalRandomTest {
|
||||
|
||||
@Test
|
||||
public void givenUsingThreadLocalRandom_whenGeneratingRandomIntBounded_thenCorrect() {
|
||||
int leftLimit = 1;
|
||||
int rightLimit = 100;
|
||||
int generatedInt = ThreadLocalRandom.current().nextInt(leftLimit, rightLimit);
|
||||
|
||||
assertTrue(generatedInt < rightLimit && generatedInt >= leftLimit);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingThreadLocalRandom_whenGeneratingRandomIntUnbounded_thenCorrect() {
|
||||
int generatedInt = ThreadLocalRandom.current().nextInt();
|
||||
|
||||
assertTrue(generatedInt < Integer.MAX_VALUE && generatedInt >= Integer.MIN_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingThreadLocalRandom_whenGeneratingRandomLongBounded_thenCorrect() {
|
||||
long leftLimit = 1L;
|
||||
long rightLimit = 100L;
|
||||
long generatedLong = ThreadLocalRandom.current().nextLong(leftLimit, rightLimit);
|
||||
|
||||
assertTrue(generatedLong < rightLimit && generatedLong >= leftLimit);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingThreadLocalRandom_whenGeneratingRandomLongUnbounded_thenCorrect() {
|
||||
long generatedInt = ThreadLocalRandom.current().nextLong();
|
||||
|
||||
assertTrue(generatedInt < Long.MAX_VALUE && generatedInt >= Long.MIN_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingThreadLocalRandom_whenGeneratingRandomDoubleBounded_thenCorrect() {
|
||||
double leftLimit = 1D;
|
||||
double rightLimit = 100D;
|
||||
double generatedInt = ThreadLocalRandom.current().nextDouble(leftLimit, rightLimit);
|
||||
|
||||
assertTrue(generatedInt < rightLimit && generatedInt >= leftLimit);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingThreadLocalRandom_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
|
||||
double generatedInt = ThreadLocalRandom.current().nextDouble();
|
||||
|
||||
assertTrue(generatedInt < Double.MAX_VALUE && generatedInt >= Double.MIN_VALUE);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void givenUsingThreadLocalRandom_whenSettingSeed_thenThrowUnsupportedOperationException() {
|
||||
ThreadLocalRandom.current().setSeed(0l);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,25 +1,30 @@
|
|||
package com.baeldung.ethereumj.controllers;
|
||||
|
||||
import com.baeldung.ethereumj.ApplicationMain;
|
||||
import com.baeldung.ethereumj.Constants;
|
||||
import com.baeldung.ethereumj.transfer.EthResponse;
|
||||
import static junit.framework.TestCase.assertTrue;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.context.embedded.LocalServerPort;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import static junit.framework.TestCase.assertTrue;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import com.baeldung.ethereumj.ApplicationMain;
|
||||
import com.baeldung.ethereumj.Constants;
|
||||
import com.baeldung.ethereumj.transfer.EthResponse;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = ApplicationMain.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
|
||||
@TestPropertySource(properties = "server.port=8080")
|
||||
public class EthControllerTestOne {
|
||||
public class EthControllerLiveTest {
|
||||
|
||||
@LocalServerPort
|
||||
int port;
|
|
@ -1,58 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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>
|
||||
|
||||
<artifactId>flyway-callbacks</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>flyway-callbacks</name>
|
||||
<description>Flyway Callbacks Demo</description>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-boot-5</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-5</relativePath>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
<version>5.0.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jdbc</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
</project>
|
|
@ -1,5 +1,5 @@
|
|||
flyway.user=root
|
||||
flyway.password=mysql
|
||||
flyway.user=sa
|
||||
flyway.password=
|
||||
flyway.schemas=app-db
|
||||
flyway.url=jdbc:mysql://localhost:3306/
|
||||
flyway.url=jdbc:h2:mem:DATABASE
|
||||
flyway.locations=filesystem:db/migration
|
108
flyway/pom.xml
108
flyway/pom.xml
|
@ -1,34 +1,76 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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>flyway</artifactId>
|
||||
<version>1.0</version>
|
||||
<name>flyway</name>
|
||||
<description>A sample project to demonstrate Flyway migrations</description>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>6.0.3</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-maven-plugin</artifactId>
|
||||
<version>4.0.3</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
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>flyway</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>flyway</name>
|
||||
<description>Flyway Callbacks Demo</description>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-boot-5</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-boot-5</relativePath>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
<version>5.0.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jdbc</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>6.0.3</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-maven-plugin</artifactId>
|
||||
<version>5.0.2</version>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -89,7 +89,7 @@ public class GuavaCacheUnitTest {
|
|||
cache.getUnchecked("hello");
|
||||
assertEquals(1, cache.size());
|
||||
cache.getUnchecked("hello");
|
||||
Thread.sleep(300);
|
||||
Thread.sleep(3);
|
||||
cache.getUnchecked("test");
|
||||
assertEquals(1, cache.size());
|
||||
assertNull(cache.getIfPresent("hello"));
|
||||
|
@ -106,7 +106,7 @@ public class GuavaCacheUnitTest {
|
|||
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().expireAfterWrite(2, TimeUnit.MILLISECONDS).build(loader);
|
||||
cache.getUnchecked("hello");
|
||||
assertEquals(1, cache.size());
|
||||
Thread.sleep(300);
|
||||
Thread.sleep(3);
|
||||
cache.getUnchecked("test");
|
||||
assertEquals(1, cache.size());
|
||||
assertNull(cache.getIfPresent("hello"));
|
||||
|
@ -203,8 +203,9 @@ public class GuavaCacheUnitTest {
|
|||
|
||||
private String getSuffix(final String str) {
|
||||
final int lastIndex = str.lastIndexOf('.');
|
||||
if (lastIndex == -1)
|
||||
if (lastIndex == -1) {
|
||||
return null;
|
||||
}
|
||||
return str.substring(lastIndex + 1);
|
||||
}
|
||||
|
||||
|
|
|
@ -4,3 +4,4 @@
|
|||
- [An Overview of Identifiers in Hibernate](http://www.baeldung.com/hibernate-identifiers)
|
||||
- [Hibernate – Mapping Date and Time](http://www.baeldung.com/hibernate-date-time)
|
||||
- [Hibernate Inheritance Mapping](http://www.baeldung.com/hibernate-inheritance)
|
||||
- [A Guide to Multitenancy in Hibernate 5](http://www.baeldung.com/hibernate-5-multitenancy)
|
||||
|
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.hibernate.interceptors;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
import org.hibernate.EmptyInterceptor;
|
||||
import org.hibernate.type.Type;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.baeldung.hibernate.interceptors.entity.User;
|
||||
|
||||
public class CustomInterceptor extends EmptyInterceptor {
|
||||
private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class);
|
||||
|
||||
@Override
|
||||
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
|
||||
if (entity instanceof User) {
|
||||
logger.info(((User) entity).toString());
|
||||
}
|
||||
return super.onSave(entity, id, state, propertyNames, types);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object [] previousState, String[] propertyNames, Type[] types) {
|
||||
if (entity instanceof User) {
|
||||
((User) entity).setLastModified(new Date());
|
||||
logger.info(((User) entity).toString());
|
||||
}
|
||||
return super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,122 @@
|
|||
package com.baeldung.hibernate.interceptors;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Iterator;
|
||||
|
||||
import org.hibernate.CallbackException;
|
||||
import org.hibernate.EntityMode;
|
||||
import org.hibernate.Interceptor;
|
||||
import org.hibernate.Transaction;
|
||||
import org.hibernate.type.Type;
|
||||
|
||||
public class CustomInterceptorImpl implements Interceptor {
|
||||
|
||||
@Override
|
||||
public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCollectionRecreate(Object collection, Serializable key) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCollectionRemove(Object collection, Serializable key) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCollectionUpdate(Object collection, Serializable key) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void preFlush(Iterator entities) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postFlush(Iterator entities) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean isTransient(Object entity) {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getEntityName(Object object) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getEntity(String entityName, Serializable id) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterTransactionBegin(Transaction tx) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeTransactionCompletion(Transaction tx) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterTransactionCompletion(Transaction tx) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String onPrepareStatement(String sql) {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,79 @@
|
|||
package com.baeldung.hibernate.interceptors;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.hibernate.Interceptor;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.Metadata;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.SessionFactoryBuilder;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
|
||||
import com.baeldung.hibernate.interceptors.entity.User;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Properties;
|
||||
|
||||
public class HibernateUtil {
|
||||
private static SessionFactory sessionFactory;
|
||||
private static String PROPERTY_FILE_NAME;
|
||||
|
||||
public static SessionFactory getSessionFactory() throws IOException {
|
||||
return getSessionFactory(null);
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
|
||||
PROPERTY_FILE_NAME = propertyFileName;
|
||||
if (sessionFactory == null) {
|
||||
ServiceRegistry serviceRegistry = configureServiceRegistry();
|
||||
sessionFactory = getSessionFactoryBuilder(serviceRegistry).build();
|
||||
}
|
||||
return sessionFactory;
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactoryWithInterceptor(String propertyFileName, Interceptor interceptor) throws IOException {
|
||||
PROPERTY_FILE_NAME = propertyFileName;
|
||||
if (sessionFactory == null) {
|
||||
ServiceRegistry serviceRegistry = configureServiceRegistry();
|
||||
sessionFactory = getSessionFactoryBuilder(serviceRegistry).applyInterceptor(interceptor)
|
||||
.build();
|
||||
}
|
||||
return sessionFactory;
|
||||
}
|
||||
|
||||
public static Session getSessionWithInterceptor(Interceptor interceptor) throws IOException {
|
||||
return getSessionFactory().withOptions()
|
||||
.interceptor(interceptor)
|
||||
.openSession();
|
||||
}
|
||||
|
||||
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
|
||||
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
|
||||
metadataSources.addPackage("com.baeldung.hibernate.interceptors");
|
||||
metadataSources.addAnnotatedClass(User.class);
|
||||
|
||||
Metadata metadata = metadataSources.buildMetadata();
|
||||
return metadata.getSessionFactoryBuilder();
|
||||
|
||||
}
|
||||
|
||||
private static ServiceRegistry configureServiceRegistry() throws IOException {
|
||||
Properties properties = getProperties();
|
||||
return new StandardServiceRegistryBuilder().applySettings(properties)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static Properties getProperties() throws IOException {
|
||||
Properties properties = new Properties();
|
||||
URL propertiesURL = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate-interceptors.properties"));
|
||||
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
|
||||
properties.load(inputStream);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,64 @@
|
|||
package com.baeldung.hibernate.interceptors.entity;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import javax.persistence.Basic;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Temporal;
|
||||
import javax.persistence.TemporalType;
|
||||
|
||||
@Entity(name = "hbi_user")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE)
|
||||
private long id;
|
||||
private String name;
|
||||
private String about;
|
||||
@Basic
|
||||
@Temporal(TemporalType.DATE)
|
||||
private Date lastModified;
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Date getLastModified() {
|
||||
return lastModified;
|
||||
}
|
||||
|
||||
public void setLastModified(Date lastModified) {
|
||||
this.lastModified = lastModified;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getAbout() {
|
||||
return about;
|
||||
}
|
||||
|
||||
public void setAbout(String about) {
|
||||
this.about = about;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("ID: %d\nName: %s\nLast Modified: %s\nAbout: %s\n", getId(), getName(), getLastModified(), getAbout());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
package com.baeldung.hibernate.interceptors;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.Transaction;
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.hibernate.interceptors.entity.User;
|
||||
|
||||
public class HibernateInterceptorTest {
|
||||
private static SessionFactory sessionFactory;
|
||||
private static Serializable userId;
|
||||
|
||||
@Before
|
||||
public void init() throws IOException {
|
||||
sessionFactory = HibernateUtil.getSessionFactoryWithInterceptor(null, new CustomInterceptor());
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void finish() {
|
||||
if(userId != null) {
|
||||
Session session = sessionFactory.getCurrentSession();
|
||||
Transaction transaction = session.beginTransaction();
|
||||
User user = session.load(User.class, userId);
|
||||
if(user != null) {
|
||||
session.delete(user);
|
||||
}
|
||||
transaction.commit();
|
||||
session.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHibernateInterceptorAndSessionScoped_whenUserCreated_shouldSucceed() {
|
||||
Session session = sessionFactory.withOptions().interceptor(new CustomInterceptor()).openSession();
|
||||
User user = new User("Benjamin Franklin");
|
||||
Transaction transaction = session.beginTransaction();
|
||||
userId = session.save(user);
|
||||
transaction.commit();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHibernateInterceptorAndSessionFactoryScoped_whenUserModified_shouldSucceed() {
|
||||
Session session = sessionFactory.openSession();
|
||||
Transaction transaction = session.beginTransaction();
|
||||
User user = session.load(User.class, userId);
|
||||
if(user != null) {
|
||||
user.setAbout("I am a scientist.");
|
||||
session.update(user);
|
||||
}
|
||||
transaction.commit();
|
||||
session.close();
|
||||
}
|
||||
|
||||
}
|
|
@ -8,12 +8,15 @@ import java.util.Properties;
|
|||
import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
|
||||
import org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider;
|
||||
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
|
||||
import org.junit.Assert;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class SchemaMultiTenantConnectionProvider extends AbstractMultiTenantConnectionProvider {
|
||||
|
||||
private final ConnectionProvider connectionProvider = initConnectionProvider();
|
||||
private final ConnectionProvider connectionProvider;
|
||||
|
||||
public SchemaMultiTenantConnectionProvider() throws IOException {
|
||||
connectionProvider = initConnectionProvider();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConnectionProvider getAnyConnectionProvider() {
|
||||
|
@ -33,13 +36,9 @@ public class SchemaMultiTenantConnectionProvider extends AbstractMultiTenantConn
|
|||
return connection;
|
||||
}
|
||||
|
||||
private ConnectionProvider initConnectionProvider() {
|
||||
private ConnectionProvider initConnectionProvider() throws IOException {
|
||||
Properties properties = new Properties();
|
||||
try {
|
||||
properties.load(getClass().getResourceAsStream("/hibernate-schema-multitenancy.properties"));
|
||||
} catch (IOException e) {
|
||||
Assert.fail("Error loading resource. Cause: " + e.getMessage());
|
||||
}
|
||||
properties.load(getClass().getResourceAsStream("/hibernate-schema-multitenancy.properties"));
|
||||
|
||||
DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
|
||||
connectionProvider.configure(properties);
|
||||
|
|
|
@ -0,0 +1,10 @@
|
|||
hibernate.connection.driver_class=org.h2.Driver
|
||||
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
|
||||
hibernate.connection.username=sa
|
||||
hibernate.connection.autocommit=true
|
||||
jdbc.password=
|
||||
|
||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
hibernate.show_sql=true
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
hibernate.current_session_context_class=org.hibernate.context.internal.ThreadLocalSessionContext
|
|
@ -7,10 +7,10 @@
|
|||
<name>hystrix</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-boot-4</artifactId>
|
||||
<artifactId>parent-boot-5</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-boot-4</relativePath>
|
||||
<relativePath>../parent-boot-5</relativePath>
|
||||
</parent>
|
||||
|
||||
|
||||
|
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [RESTFul CRUD application with JavaLite] ()
|
|
@ -0,0 +1,96 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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>org.baeldung</groupId>
|
||||
<artifactId>java-lite</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<jetty.maven.plugin.version>9.4.8.v20171121</jetty.maven.plugin.version>
|
||||
<activejdbc.version>1.4.13</activejdbc.version>
|
||||
<activeweb.version>1.15</activeweb.version>
|
||||
<mysql.connector.java.version>5.1.45</mysql.connector.java.version>
|
||||
<sun.tools.version>1.7.0</sun.tools.version>
|
||||
<jackson.version>1.8.2</jackson.version>
|
||||
<junit.version>4.11</junit.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-maven-plugin</artifactId>
|
||||
<version>${jetty.maven.plugin.version}</version>
|
||||
<configuration>
|
||||
<systemProperties>
|
||||
<systemProperty>
|
||||
<name>activejdbc.log</name>
|
||||
<value></value>
|
||||
</systemProperty>
|
||||
<systemProperty>
|
||||
<name>active_reload</name>
|
||||
<value>true</value>
|
||||
</systemProperty>
|
||||
<systemProperty>
|
||||
<name>activeweb.log.request</name>
|
||||
<value>true</value>
|
||||
</systemProperty>
|
||||
</systemProperties>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.javalite</groupId>
|
||||
<artifactId>activejdbc-instrumentation</artifactId>
|
||||
<version>${activejdbc.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>process-classes</phase>
|
||||
<goals>
|
||||
<goal>instrument</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.javalite</groupId>
|
||||
<artifactId>activeweb</artifactId>
|
||||
<version>${activeweb.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>${mysql.connector.java.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun</groupId>
|
||||
<artifactId>tools</artifactId>
|
||||
<version>${sun.tools.version}</version>
|
||||
<scope>system</scope>
|
||||
<systemPath>${java.home}/../lib/tools.jar</systemPath>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,9 @@
|
|||
package app.config;
|
||||
|
||||
import org.javalite.activeweb.AppContext;
|
||||
import org.javalite.activeweb.Bootstrap;
|
||||
|
||||
public class AppBootstrap extends Bootstrap {
|
||||
public void init(AppContext context) {
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package app.config;
|
||||
|
||||
import app.controllers.ProductsController;
|
||||
import org.javalite.activeweb.AbstractControllerConfig;
|
||||
import org.javalite.activeweb.AppContext;
|
||||
import org.javalite.activeweb.controller_filters.DBConnectionFilter;
|
||||
import org.javalite.activeweb.controller_filters.TimingFilter;
|
||||
|
||||
public class AppControllerConfig extends AbstractControllerConfig {
|
||||
@Override
|
||||
public void init(AppContext appContext) {
|
||||
addGlobalFilters(new TimingFilter());
|
||||
add(new DBConnectionFilter()).to(ProductsController.class);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package app.config;
|
||||
|
||||
import org.javalite.activeweb.AbstractDBConfig;
|
||||
import org.javalite.activeweb.AppContext;
|
||||
|
||||
public class DbConfig extends AbstractDBConfig {
|
||||
@Override
|
||||
public void init(AppContext appContext) {
|
||||
this.configFile("/database.properties");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,103 @@
|
|||
package app.controllers;
|
||||
|
||||
import app.models.Product;
|
||||
import org.codehaus.jackson.map.ObjectMapper;
|
||||
import org.javalite.activeweb.AppController;
|
||||
import org.javalite.activeweb.annotations.RESTful;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RESTful
|
||||
public class ProductsController extends AppController {
|
||||
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
public void index() {
|
||||
try {
|
||||
view("products", Product.findAll());
|
||||
render().contentType("application/json");
|
||||
} catch (Exception e) {
|
||||
view("message", "There was an error.", "code", 200);
|
||||
render("message");
|
||||
}
|
||||
}
|
||||
|
||||
public void create() {
|
||||
try {
|
||||
Map payload = mapper.readValue(getRequestString(), Map.class);
|
||||
Product p = new Product();
|
||||
p.fromMap(payload);
|
||||
p.saveIt();
|
||||
view("message", "Successfully saved product id " + p.get("id"), "code", 200);
|
||||
render("message");
|
||||
} catch (Exception e) {
|
||||
view("message", "There was an error.", "code", 200);
|
||||
render("message");
|
||||
}
|
||||
}
|
||||
|
||||
public void update() {
|
||||
try {
|
||||
Map payload = mapper.readValue(getRequestString(), Map.class);
|
||||
String id = getId();
|
||||
Product p = Product.findById(id);
|
||||
if (p == null) {
|
||||
view("message", "Product id " + id + " not found.", "code", 200);
|
||||
render("message");
|
||||
return;
|
||||
}
|
||||
p.fromMap(payload);
|
||||
p.saveIt();
|
||||
view("message", "Successfully updated product id " + id, "code", 200);
|
||||
render("message");
|
||||
} catch (Exception e) {
|
||||
view("message", "There was an error.", "code", 200);
|
||||
render("message");
|
||||
}
|
||||
}
|
||||
|
||||
public void show() {
|
||||
try {
|
||||
String id = getId();
|
||||
Product p = Product.findById(id);
|
||||
if (p == null) {
|
||||
view("message", "Product id " + id + " not found.", "code", 200);
|
||||
render("message");
|
||||
return;
|
||||
}
|
||||
view("product", p);
|
||||
render("_product");
|
||||
} catch (Exception e) {
|
||||
view("message", "There was an error.", "code", 200);
|
||||
render("message");
|
||||
}
|
||||
}
|
||||
|
||||
public void destroy() {
|
||||
try {
|
||||
String id = getId();
|
||||
Product p = Product.findById(id);
|
||||
if (p == null) {
|
||||
view("message", "Product id " + id + " not found.", "code", 200);
|
||||
render("message");
|
||||
return;
|
||||
}
|
||||
p.delete();
|
||||
view("message", "Successfully deleted product id " + id, "code", 200);
|
||||
render("message");
|
||||
} catch (Exception e) {
|
||||
view("message", "There was an error.", "code", 200);
|
||||
render("message");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getContentType() {
|
||||
return "application/json";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getLayout() {
|
||||
return null;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package app.models;
|
||||
|
||||
import org.javalite.activejdbc.Model;
|
||||
|
||||
public class Product extends Model {
|
||||
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
development.driver=com.mysql.jdbc.Driver
|
||||
development.username=user
|
||||
development.password=password
|
||||
development.url=jdbc:mysql://localhost/dbname
|
|
@ -0,0 +1 @@
|
|||
,
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"id" : ${product.id},
|
||||
"name" : "${product.name}"
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
[<@render partial="product" collection=products spacer="comma"/>]
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"message" : "${message}",
|
||||
"code" : ${code}
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
|
||||
|
||||
|
||||
<filter>
|
||||
<filter-name>dispatcher</filter-name>
|
||||
<filter-class>org.javalite.activeweb.RequestDispatcher</filter-class>
|
||||
<init-param>
|
||||
<param-name>exclusions</param-name>
|
||||
<param-value>css,images,js,ico</param-value>
|
||||
</init-param>
|
||||
<init-param>
|
||||
<param-name>encoding</param-name>
|
||||
<param-value>UTF-8</param-value>
|
||||
</init-param>
|
||||
</filter>
|
||||
|
||||
|
||||
<filter-mapping>
|
||||
<filter-name>dispatcher</filter-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
</filter-mapping>
|
||||
|
||||
</web-app>
|
|
@ -0,0 +1,25 @@
|
|||
package app.models;
|
||||
|
||||
import org.javalite.activejdbc.Base;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ProductTest {
|
||||
|
||||
//@Test
|
||||
public void givenSavedProduct_WhenFindFirst_ThenSavedProductIsReturned() {
|
||||
//Open DB connection
|
||||
Base.open("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/dbname", "user", "password");
|
||||
|
||||
//Create a product and save it
|
||||
Product toSaveProduct = new Product();
|
||||
toSaveProduct.set("name", "Bread");
|
||||
toSaveProduct.saveIt();
|
||||
|
||||
//Find product
|
||||
Product savedProduct = Product.findFirst("name = ?", "Bread");
|
||||
|
||||
Assert.assertEquals(toSaveProduct.get("name"), savedProduct.get("name"));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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.samples</groupId>
|
||||
<artifactId>java-vavr-stream</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.vavr</groupId>
|
||||
<artifactId>vavr</artifactId>
|
||||
<version>0.9.2</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
|
@ -0,0 +1,98 @@
|
|||
package com.baeldung.samples.java.vavr;
|
||||
|
||||
import io.vavr.collection.Stream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author baeldung
|
||||
*/
|
||||
public class VavrSampler {
|
||||
|
||||
static int[] intArray = new int[]{1, 2, 4};
|
||||
static List<Integer> intList = new ArrayList<Integer>();
|
||||
static int[][] intOfInts = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
|
||||
|
||||
public static void main(String[] args) {
|
||||
vavrStreamElementAccess();
|
||||
System.out.println("====================================");
|
||||
vavrParallelStreamAccess();
|
||||
System.out.println("====================================");
|
||||
jdkFlatMapping();
|
||||
System.out.println("====================================");
|
||||
vavrStreamManipulation();
|
||||
System.out.println("====================================");
|
||||
vavrStreamDistinct();
|
||||
}
|
||||
|
||||
public static void vavrStreamElementAccess() {
|
||||
System.out.println("Vavr Element Access");
|
||||
System.out.println("====================================");
|
||||
Stream<Integer> vavredStream = Stream.ofAll(intArray);
|
||||
System.out.println("Vavr index access: " + vavredStream.get(2));
|
||||
System.out.println("Vavr head element access: " + vavredStream.get());
|
||||
|
||||
Stream<String> vavredStringStream = Stream.of("foo", "bar", "baz");
|
||||
System.out.println("Find foo " + vavredStringStream.indexOf("foo"));
|
||||
}
|
||||
|
||||
public static void vavrParallelStreamAccess() {
|
||||
try {
|
||||
System.out.println("Vavr Stream Concurrent Modification");
|
||||
System.out.println("====================================");
|
||||
Stream<Integer> vavrStream = Stream.ofAll(intList);
|
||||
intList.add(5);
|
||||
vavrStream.forEach(i -> System.out.println("in a Vavr Stream: " + i));
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
|
||||
Stream<Integer> wrapped = Stream.ofAll(intArray);
|
||||
intArray[2] = 5;
|
||||
wrapped.forEach(i -> System.out.println("Vavr looped " + i));
|
||||
}
|
||||
|
||||
public static void jdkFlatMapping() {
|
||||
System.out.println("JDK FlatMap -> Uncomment line 68 to test");
|
||||
System.out.println("====================================");
|
||||
int[][] intOfInts = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
|
||||
|
||||
IntStream mapToInt = Arrays.stream(intOfInts)
|
||||
.map(intArr -> Arrays.stream(intArr))
|
||||
.flatMapToInt(val -> val.map(n -> {
|
||||
return n * n;
|
||||
}))
|
||||
.peek(n -> System.out.println("Peeking at " + n));
|
||||
//Uncomment to execute pipeline
|
||||
//mapToInt.forEach(n -> System.out.println("FlatMapped Result "+n));
|
||||
}
|
||||
|
||||
public static void vavrStreamManipulation() {
|
||||
System.out.println("Vavr Stream Manipulation");
|
||||
System.out.println("====================================");
|
||||
List<String> stringList = new ArrayList<>();
|
||||
stringList.add("foo");
|
||||
stringList.add("bar");
|
||||
stringList.add("baz");
|
||||
Stream<String> vavredStream = Stream.ofAll(stringList);
|
||||
vavredStream.forEach(item -> System.out.println("Vavr Stream item: " + item));
|
||||
Stream<String> vavredStream2 = vavredStream.insert(2, "buzz");
|
||||
vavredStream2.forEach(item -> System.out.println("Vavr Stream item after stream addition: " + item));
|
||||
stringList.forEach(item -> System.out.println("List item after stream addition: " + item));
|
||||
Stream<String> deletionStream = vavredStream.remove("bar");
|
||||
deletionStream.forEach(item -> System.out.println("Vavr Stream item after stream item deletion: " + item));
|
||||
|
||||
}
|
||||
|
||||
public static void vavrStreamDistinct() {
|
||||
Stream<String> vavredStream = Stream.of("foo", "bar", "baz", "buxx", "bar", "bar", "foo");
|
||||
Stream<String> distinctVavrStream = vavredStream.distinctBy((y, z) -> {
|
||||
return y.compareTo(z);
|
||||
});
|
||||
distinctVavrStream.forEach(item -> System.out.println("Vavr Stream item after distinct query " + item));
|
||||
|
||||
}
|
||||
}
|
|
@ -12,10 +12,10 @@
|
|||
<description>Exercising the JJWT</description>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-boot-4</artifactId>
|
||||
<artifactId>parent-boot-5</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-boot-4</relativePath>
|
||||
<relativePath>../parent-boot-5</relativePath>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
|
|
|
@ -2,12 +2,12 @@ package io.jsonwebtoken.jjwtfun;
|
|||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.SpringApplicationConfiguration;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringApplicationConfiguration(classes = JJWTFunApplication.class)
|
||||
@SpringBootTest(classes = JJWTFunApplication.class)
|
||||
@WebAppConfiguration
|
||||
public class DemoApplicationIntegrationTest {
|
||||
|
||||
|
|
|
@ -107,7 +107,7 @@
|
|||
<!-- /Neuroph -->
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.7.0</version>
|
||||
<version>3.7.0</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
|
@ -639,6 +639,33 @@
|
|||
<version>${googleclient.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--Java Docker API Client-->
|
||||
<dependency>
|
||||
<groupId>com.github.docker-java</groupId>
|
||||
<artifactId>docker-java</artifactId>
|
||||
<version>${docker.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-log4j12</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey</groupId>
|
||||
<artifactId>jersey-client</artifactId>
|
||||
<version>1.19.4</version>
|
||||
</dependency>
|
||||
<!--Java Docker API Client-->
|
||||
|
||||
<!-- google api -->
|
||||
<dependency>
|
||||
<groupId>com.google.api-client</groupId>
|
||||
|
@ -758,5 +785,6 @@
|
|||
<google-api.version>1.23.0</google-api.version>
|
||||
<google-sheets.version>v4-rev493-1.21.0</google-sheets.version>
|
||||
<kafka.version>1.0.0</kafka.version>
|
||||
<docker.version>3.0.14</docker.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,165 @@
|
|||
package com.baeldung.dockerapi;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.CreateContainerResponse;
|
||||
import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import com.github.dockerjava.api.model.Container;
|
||||
import com.github.dockerjava.api.model.PortBinding;
|
||||
import com.github.dockerjava.core.DockerClientBuilder;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.core.Is.is;
|
||||
|
||||
public class ContainerLiveTest {
|
||||
|
||||
private static DockerClient dockerClient;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
dockerClient = DockerClientBuilder.getInstance().build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListingRunningContainers_thenReturnNonEmptyList() {
|
||||
|
||||
//when
|
||||
List<Container> containers = dockerClient.listContainersCmd().exec();
|
||||
|
||||
//then
|
||||
assertThat(containers.size(), is(not(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListingExitedContainers_thenReturnNonEmptyList() {
|
||||
|
||||
//when
|
||||
List<Container> containers = dockerClient.listContainersCmd()
|
||||
.withShowSize(true)
|
||||
.withShowAll(true)
|
||||
.withStatusFilter("exited")
|
||||
.exec();
|
||||
|
||||
//then
|
||||
assertThat(containers.size(), is(not(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingContainer_thenMustReturnContainerId() {
|
||||
|
||||
//when
|
||||
CreateContainerResponse container
|
||||
= dockerClient.createContainerCmd("mongo:3.6")
|
||||
.withCmd("--bind_ip_all")
|
||||
.withName("mongo")
|
||||
.withHostName("baeldung")
|
||||
.withEnv("MONGO_LATEST_VERSION=3.6")
|
||||
.withPortBindings(PortBinding.parse("9999:27017"))
|
||||
.exec();
|
||||
|
||||
//then
|
||||
assertThat(container.getId(), is(not(null)));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenHavingContainer_thenRunContainer() throws InterruptedException {
|
||||
|
||||
//when
|
||||
CreateContainerResponse container
|
||||
= dockerClient.createContainerCmd("alpine:3.6")
|
||||
.withCmd("sleep", "10000")
|
||||
.exec();
|
||||
|
||||
Thread.sleep(3000);
|
||||
//then
|
||||
dockerClient.startContainerCmd(container.getId())
|
||||
.exec();
|
||||
|
||||
dockerClient.stopContainerCmd(container.getId())
|
||||
.exec();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRunningContainer_thenStopContainer() throws InterruptedException {
|
||||
|
||||
//when
|
||||
CreateContainerResponse container
|
||||
= dockerClient.createContainerCmd("alpine:3.6")
|
||||
.withCmd("sleep", "10000")
|
||||
.exec();
|
||||
|
||||
Thread.sleep(3000);
|
||||
dockerClient.startContainerCmd(container.getId())
|
||||
.exec();
|
||||
|
||||
//then
|
||||
dockerClient.stopContainerCmd(container.getId())
|
||||
.exec();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRunningContainer_thenKillContainer() throws InterruptedException {
|
||||
|
||||
//when
|
||||
CreateContainerResponse container
|
||||
= dockerClient.createContainerCmd("alpine:3.6")
|
||||
.withCmd("sleep", "10000")
|
||||
.exec();
|
||||
|
||||
dockerClient.startContainerCmd(container.getId())
|
||||
.exec();
|
||||
|
||||
Thread.sleep(3000);
|
||||
dockerClient.stopContainerCmd(container.getId())
|
||||
.exec();
|
||||
|
||||
//then
|
||||
dockerClient.killContainerCmd(container.getId())
|
||||
.exec();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenHavingContainer_thenInspectContainer() {
|
||||
|
||||
//when
|
||||
CreateContainerResponse container
|
||||
= dockerClient.createContainerCmd("alpine:3.6")
|
||||
.withCmd("sleep", "10000")
|
||||
.exec();
|
||||
|
||||
//then
|
||||
InspectContainerResponse containerResponse
|
||||
= dockerClient.inspectContainerCmd(container.getId())
|
||||
.exec();
|
||||
|
||||
assertThat(containerResponse.getId(), is(container.getId()));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenContainer_whenCommittingContainer_thenMustReturnImageId() {
|
||||
|
||||
//given
|
||||
CreateContainerResponse container
|
||||
= dockerClient.createContainerCmd("alpine:3.6")
|
||||
.withCmd("sleep", "10000")
|
||||
.exec();
|
||||
|
||||
//when
|
||||
String imageId = dockerClient.commitCmd(container.getId())
|
||||
.withEnv("SNAPSHOT_YEAR=2018")
|
||||
.withMessage("add git support")
|
||||
.withCmd("sleep", "10000")
|
||||
.withRepository("alpine")
|
||||
.withTag("3.6.v2").exec();
|
||||
|
||||
//then
|
||||
assertThat(imageId, is(not(null)));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
package com.baeldung.dockerapi;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.core.DefaultDockerClientConfig;
|
||||
import com.github.dockerjava.core.DockerClientBuilder;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class DockerClientLiveTest {
|
||||
|
||||
@Test
|
||||
public void whenCreatingDockerClient_thenReturnDefaultInstance() {
|
||||
|
||||
//when
|
||||
DefaultDockerClientConfig.Builder config
|
||||
= DefaultDockerClientConfig.createDefaultConfigBuilder();
|
||||
DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
|
||||
|
||||
//then
|
||||
assertNotNull(dockerClient);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingDockerClientWithDockerHost_thenReturnInstance() {
|
||||
//when
|
||||
DockerClient dockerClient
|
||||
= DockerClientBuilder.getInstance("tcp://docker.bealdung.com:2375")
|
||||
.build();
|
||||
|
||||
//then
|
||||
assertNotNull(dockerClient);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingAdvanceDockerClient_thenReturnInstance() {
|
||||
|
||||
//when
|
||||
DefaultDockerClientConfig config
|
||||
= DefaultDockerClientConfig.createDefaultConfigBuilder()
|
||||
.withRegistryEmail("info@bealdung.com")
|
||||
.withRegistryUrl("register.bealdung.io/v2/")
|
||||
.withRegistryPassword("strongpassword")
|
||||
.withRegistryUsername("bealdung")
|
||||
.withDockerCertPath("/home/bealdung/public/.docker/certs")
|
||||
.withDockerConfig("/home/bealdung/public/.docker/")
|
||||
.withDockerTlsVerify("1")
|
||||
.withDockerHost("tcp://docker.beauldung.com:2376")
|
||||
.build();
|
||||
|
||||
DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
|
||||
|
||||
//then
|
||||
assertNotNull(dockerClient);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingDockerClientWithProperties_thenReturnInstance() {
|
||||
|
||||
//when
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("registry.email", "info@bealdung.com");
|
||||
properties.setProperty("registry.url", "register.bealdung.io/v2/");
|
||||
properties.setProperty("registry.password", "strongpassword");
|
||||
properties.setProperty("registry.username", "bealdung");
|
||||
properties.setProperty("DOCKER_CERT_PATH", "/home/bealdung/public/.docker/certs");
|
||||
properties.setProperty("DOCKER_CONFIG", "/home/bealdung/public/.docker/");
|
||||
properties.setProperty("DOCKER_TLS_VERIFY", "1");
|
||||
properties.setProperty("DOCKER_HOST", "tcp://docker.bealdung.com:2376");
|
||||
|
||||
DefaultDockerClientConfig config
|
||||
= DefaultDockerClientConfig.createDefaultConfigBuilder()
|
||||
.withProperties(properties)
|
||||
.build();
|
||||
|
||||
DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
|
||||
|
||||
//then
|
||||
assertNotNull(dockerClient);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,155 @@
|
|||
package com.baeldung.dockerapi;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.InspectImageResponse;
|
||||
import com.github.dockerjava.api.model.Image;
|
||||
import com.github.dockerjava.api.model.SearchItem;
|
||||
import com.github.dockerjava.core.DockerClientBuilder;
|
||||
import com.github.dockerjava.core.command.BuildImageResultCallback;
|
||||
import com.github.dockerjava.core.command.PullImageResultCallback;
|
||||
import com.github.dockerjava.core.command.PushImageResultCallback;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.hamcrest.Matchers.lessThan;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.core.Is.is;
|
||||
|
||||
public class ImageLiveTest {
|
||||
|
||||
private static DockerClient dockerClient;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
dockerClient = DockerClientBuilder.getInstance().build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListingImages_thenReturnNonEmptyList() {
|
||||
|
||||
//when
|
||||
List<Image> images = dockerClient.listImagesCmd().exec();
|
||||
|
||||
//then
|
||||
assertThat(images.size(), is(not(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListingImagesWithIntermediateImages_thenReturnNonEmptyList() {
|
||||
|
||||
//when
|
||||
List<Image> images = dockerClient.listImagesCmd()
|
||||
.withShowAll(true).exec();
|
||||
|
||||
//then
|
||||
assertThat(images.size(), is(not(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListingDanglingImages_thenReturnNonNullList() {
|
||||
|
||||
//when
|
||||
List<Image> images = dockerClient.listImagesCmd()
|
||||
.withDanglingFilter(true).exec();
|
||||
|
||||
//then
|
||||
assertThat(images, is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBuildingImage_thenMustReturnImageId() {
|
||||
|
||||
//when
|
||||
String imageId = dockerClient.buildImageCmd()
|
||||
.withDockerfile(new File("src/test/resources/dockerapi/Dockerfile"))
|
||||
.withPull(true)
|
||||
.withNoCache(true)
|
||||
.withTag("alpine:git")
|
||||
.exec(new BuildImageResultCallback())
|
||||
.awaitImageId();
|
||||
|
||||
//then
|
||||
assertThat(imageId, is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfImages_whenInspectImage_thenMustReturnObject() {
|
||||
|
||||
//given
|
||||
List<Image> images = dockerClient.listImagesCmd().exec();
|
||||
Image image = images.get(0);
|
||||
|
||||
//when
|
||||
InspectImageResponse imageResponse
|
||||
= dockerClient.inspectImageCmd(image.getId()).exec();
|
||||
|
||||
//then
|
||||
assertThat(imageResponse.getId(), is(image.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfImages_whenTagImage_thenListMustIncrement() {
|
||||
|
||||
//given
|
||||
List<Image> images = dockerClient.listImagesCmd().exec();
|
||||
Image image = images.get(0);
|
||||
|
||||
//when
|
||||
dockerClient.tagImageCmd(image.getId(), "baeldung/alpine", "3.6.v2").exec();
|
||||
|
||||
//then
|
||||
List<Image> imagesNow = dockerClient.listImagesCmd().exec();
|
||||
assertThat(imagesNow.size(), is(greaterThan(images.size())));
|
||||
}
|
||||
|
||||
public void pushingAnImage() throws InterruptedException {
|
||||
|
||||
dockerClient.pushImageCmd("baeldung/alpine")
|
||||
.withTag("3.6.v2")
|
||||
.exec(new PushImageResultCallback())
|
||||
.awaitCompletion(90, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPullingImage_thenImageListNotEmpty() throws InterruptedException {
|
||||
|
||||
//when
|
||||
dockerClient.pullImageCmd("alpine")
|
||||
.withTag("latest")
|
||||
.exec(new PullImageResultCallback())
|
||||
.awaitCompletion(30, TimeUnit.SECONDS);
|
||||
|
||||
//then
|
||||
List<Image> images = dockerClient.listImagesCmd().exec();
|
||||
assertThat(images.size(), is(not(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemovingImage_thenImageListDecrease() {
|
||||
|
||||
//when
|
||||
List<Image> images = dockerClient.listImagesCmd().exec();
|
||||
Image image = images.get(0);
|
||||
dockerClient.removeImageCmd(image.getId()).exec();
|
||||
|
||||
//then
|
||||
List<Image> imagesNow = dockerClient.listImagesCmd().exec();
|
||||
assertThat(imagesNow.size(), is(lessThan(images.size())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSearchingImage_thenMustReturn25Items() {
|
||||
|
||||
//when
|
||||
List<SearchItem> items = dockerClient.searchImagesCmd("Java").exec();
|
||||
|
||||
//then
|
||||
assertThat(items.size(), is(25));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,91 @@
|
|||
package com.baeldung.dockerapi;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.CreateNetworkResponse;
|
||||
import com.github.dockerjava.api.model.Network;
|
||||
import com.github.dockerjava.api.model.Network.Ipam;
|
||||
import com.github.dockerjava.core.DockerClientBuilder;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.core.Is.is;
|
||||
|
||||
public class NetworkLiveTest {
|
||||
|
||||
private static DockerClient dockerClient;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
dockerClient = DockerClientBuilder.getInstance().build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListingNetworks_thenSizeMustBeGreaterThanZero() {
|
||||
|
||||
//when
|
||||
List<Network> networks = dockerClient.listNetworksCmd().exec();
|
||||
|
||||
//then
|
||||
assertThat(networks.size(), is(greaterThan(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingNetwork_thenRetrieveResponse() {
|
||||
|
||||
//when
|
||||
CreateNetworkResponse networkResponse
|
||||
= dockerClient.createNetworkCmd()
|
||||
.withName("baeldungDefault")
|
||||
.withDriver("bridge").exec();
|
||||
|
||||
//then
|
||||
assertThat(networkResponse, is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingAdvanceNetwork_thenRetrieveResponse() {
|
||||
|
||||
//when
|
||||
CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd()
|
||||
.withName("baeldungAdvanced")
|
||||
.withIpam(new Ipam()
|
||||
.withConfig(new Ipam.Config()
|
||||
.withSubnet("172.36.0.0/16")
|
||||
.withIpRange("172.36.5.0/24")))
|
||||
.withDriver("bridge").exec();
|
||||
|
||||
//then
|
||||
assertThat(networkResponse, is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInspectingNetwork_thenSizeMustBeGreaterThanZero() {
|
||||
|
||||
//when
|
||||
String networkName = "bridge";
|
||||
Network network
|
||||
= dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec();
|
||||
|
||||
//then
|
||||
assertThat(network.getName(), is(networkName));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingNetwork_thenRemove() throws InterruptedException {
|
||||
|
||||
//when
|
||||
CreateNetworkResponse networkResponse
|
||||
= dockerClient.createNetworkCmd()
|
||||
.withName("baeldungDefault")
|
||||
.withDriver("bridge").exec();
|
||||
|
||||
//then
|
||||
Thread.sleep(4000);
|
||||
dockerClient.removeNetworkCmd(networkResponse.getId()).exec();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,86 @@
|
|||
package com.baeldung.dockerapi;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.CreateVolumeResponse;
|
||||
import com.github.dockerjava.api.command.InspectVolumeResponse;
|
||||
import com.github.dockerjava.api.command.ListVolumesResponse;
|
||||
import com.github.dockerjava.core.DockerClientBuilder;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.core.Is.is;
|
||||
|
||||
public class VolumeLiveTest {
|
||||
|
||||
private static DockerClient dockerClient;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
dockerClient = DockerClientBuilder.getInstance().build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListingVolumes_thenSizeMustBeGreaterThanZero() {
|
||||
|
||||
//when
|
||||
ListVolumesResponse volumesResponse = dockerClient.listVolumesCmd().exec();
|
||||
|
||||
//then
|
||||
List<InspectVolumeResponse> volumes = volumesResponse.getVolumes();
|
||||
assertThat(volumes.size(), is(greaterThan(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVolumes_whenInspectingVolume_thenReturnNonNullResponse() {
|
||||
|
||||
//given
|
||||
ListVolumesResponse volumesResponse = dockerClient.listVolumesCmd().exec();
|
||||
List<InspectVolumeResponse> volumes = volumesResponse.getVolumes();
|
||||
InspectVolumeResponse volume = volumes.get(0);
|
||||
|
||||
//when
|
||||
InspectVolumeResponse volumeResponse
|
||||
= dockerClient.inspectVolumeCmd(volume.getName()).exec();
|
||||
|
||||
//then
|
||||
assertThat(volumeResponse, is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingUnnamedVolume_thenGetVolumeId() {
|
||||
|
||||
//when
|
||||
CreateVolumeResponse unnamedVolume = dockerClient.createVolumeCmd().exec();
|
||||
|
||||
//then
|
||||
assertThat(unnamedVolume.getName(), is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingNamedVolume_thenGetVolumeId() {
|
||||
|
||||
//when
|
||||
CreateVolumeResponse namedVolume
|
||||
= dockerClient.createVolumeCmd().withName("myNamedVolume").exec();
|
||||
|
||||
//then
|
||||
assertThat(namedVolume.getName(), is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGettingNamedVolume_thenRemove() throws InterruptedException {
|
||||
|
||||
//when
|
||||
CreateVolumeResponse namedVolume
|
||||
= dockerClient.createVolumeCmd().withName("anotherNamedVolume").exec();
|
||||
|
||||
//then
|
||||
Thread.sleep(4000);
|
||||
dockerClient.removeVolumeCmd(namedVolume.getName()).exec();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
FROM alpine:3.6
|
||||
|
||||
RUN apk --update add git openssh && \
|
||||
rm -rf /var/lib/apt/lists/* && \
|
||||
rm /var/cache/apk/*
|
||||
|
||||
ENTRYPOINT ["git"]
|
||||
CMD ["--help"]
|
|
@ -1,27 +1,40 @@
|
|||
package com.baeldung.metrics.micrometer;
|
||||
|
||||
import com.netflix.spectator.atlas.AtlasConfig;
|
||||
import static org.hamcrest.CoreMatchers.allOf;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.collection.IsMapContaining.hasEntry;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import io.micrometer.atlas.AtlasMeterRegistry;
|
||||
import io.micrometer.core.instrument.*;
|
||||
import io.micrometer.core.instrument.Clock;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Gauge;
|
||||
import io.micrometer.core.instrument.LongTaskTimer;
|
||||
import io.micrometer.core.instrument.Measurement;
|
||||
import io.micrometer.core.instrument.Meter.Type;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import io.micrometer.core.instrument.composite.CompositeMeterRegistry;
|
||||
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
|
||||
import io.micrometer.core.instrument.stats.hist.Histogram;
|
||||
import io.micrometer.core.instrument.stats.quantile.WindowSketchQuantiles;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static io.micrometer.core.instrument.Meter.Type;
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.hamcrest.collection.IsMapContaining.hasEntry;
|
||||
import static org.hamcrest.core.IsCollectionContaining.hasItems;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.netflix.spectator.atlas.AtlasConfig;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
|
@ -135,15 +148,15 @@ public class MicrometerAtlasTest {
|
|||
Timer timer = registry.timer("app.event");
|
||||
timer.record(() -> {
|
||||
try {
|
||||
TimeUnit.MILLISECONDS.sleep(1500);
|
||||
TimeUnit.MILLISECONDS.sleep(15);
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
});
|
||||
|
||||
timer.record(3000, TimeUnit.MILLISECONDS);
|
||||
timer.record(30, TimeUnit.MILLISECONDS);
|
||||
|
||||
assertTrue(2 == timer.count());
|
||||
assertTrue(4510 > timer.totalTime(TimeUnit.MILLISECONDS) && 4500 <= timer.totalTime(TimeUnit.MILLISECONDS));
|
||||
assertTrue(50 > timer.totalTime(TimeUnit.MILLISECONDS) && 45 <= timer.totalTime(TimeUnit.MILLISECONDS));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -155,12 +168,12 @@ public class MicrometerAtlasTest {
|
|||
|
||||
long currentTaskId = longTaskTimer.start();
|
||||
try {
|
||||
TimeUnit.SECONDS.sleep(2);
|
||||
TimeUnit.MILLISECONDS.sleep(2);
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
long timeElapsed = longTaskTimer.stop(currentTaskId);
|
||||
|
||||
assertTrue(timeElapsed / (int) 1e9 == 2);
|
||||
assertTrue(timeElapsed / (int) 1e6 == 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -1,5 +1,19 @@
|
|||
package com.baeldung.metrics.servo;
|
||||
|
||||
import static java.util.concurrent.TimeUnit.MILLISECONDS;
|
||||
import static java.util.concurrent.TimeUnit.SECONDS;
|
||||
import static java.util.stream.Collectors.toMap;
|
||||
import static org.hamcrest.Matchers.allOf;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.hamcrest.Matchers.hasEntry;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.netflix.servo.monitor.BasicCounter;
|
||||
import com.netflix.servo.monitor.BasicGauge;
|
||||
import com.netflix.servo.monitor.BasicInformational;
|
||||
|
@ -17,18 +31,6 @@ import com.netflix.servo.monitor.StatsTimer;
|
|||
import com.netflix.servo.monitor.StepCounter;
|
||||
import com.netflix.servo.monitor.Stopwatch;
|
||||
import com.netflix.servo.stats.StatsConfig;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static java.util.concurrent.TimeUnit.SECONDS;
|
||||
import static java.util.stream.Collectors.toMap;
|
||||
import static org.hamcrest.Matchers.allOf;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.hamcrest.Matchers.hasEntry;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class MetricTypeTest {
|
||||
|
||||
|
@ -104,17 +106,18 @@ public class MetricTypeTest {
|
|||
public void givenTimer_whenExecuteTask_thenTimerUpdated() throws Exception {
|
||||
BasicTimer timer = new BasicTimer(MonitorConfig
|
||||
.builder("test")
|
||||
.build(), SECONDS);
|
||||
.build(), MILLISECONDS);
|
||||
|
||||
Stopwatch stopwatch = timer.start();
|
||||
SECONDS.sleep(1);
|
||||
timer.record(2, SECONDS);
|
||||
MILLISECONDS.sleep(1);
|
||||
timer.record(2, MILLISECONDS);
|
||||
stopwatch.stop();
|
||||
|
||||
assertEquals("timer should count 1 second", 1, timer
|
||||
assertEquals("timer should count 1 millisecond", 1, timer
|
||||
.getValue()
|
||||
.intValue());
|
||||
assertEquals("timer should count 3 seconds in total", 3.0, timer.getTotalTime(), 0.01);
|
||||
assertEquals("timer should count 3 millisecond in total", 3, timer.getTotalTime()
|
||||
.intValue());
|
||||
assertEquals("timer should record 2 updates", 2, timer
|
||||
.getCount()
|
||||
.intValue());
|
||||
|
@ -158,6 +161,7 @@ public class MetricTypeTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
//==
|
||||
public void givenStatsTimer_whenExecuteTask_thenStatsCalculated() throws Exception {
|
||||
System.setProperty("netflix.servo", "1000");
|
||||
StatsTimer timer = new StatsTimer(MonitorConfig
|
||||
|
@ -171,20 +175,20 @@ public class MetricTypeTest {
|
|||
.withPublishMean(true)
|
||||
.withPublishStdDev(true)
|
||||
.withPublishVariance(true)
|
||||
.build(), SECONDS);
|
||||
.build(), MILLISECONDS);
|
||||
|
||||
Stopwatch stopwatch = timer.start();
|
||||
SECONDS.sleep(1);
|
||||
timer.record(3, SECONDS);
|
||||
MILLISECONDS.sleep(1);
|
||||
timer.record(3, MILLISECONDS);
|
||||
stopwatch.stop();
|
||||
|
||||
stopwatch = timer.start();
|
||||
timer.record(6, SECONDS);
|
||||
SECONDS.sleep(2);
|
||||
timer.record(6, MILLISECONDS);
|
||||
MILLISECONDS.sleep(2);
|
||||
stopwatch.stop();
|
||||
|
||||
assertEquals("timer should count 12 seconds in total", 12, timer.getTotalTime());
|
||||
assertEquals("timer should count 12 seconds in total", 12, timer.getTotalMeasurement());
|
||||
assertEquals("timer should count 12 milliseconds in total", 12, timer.getTotalTime());
|
||||
assertEquals("timer should count 12 milliseconds in total", 12, timer.getTotalMeasurement());
|
||||
assertEquals("timer should record 4 updates", 4, timer.getCount());
|
||||
assertEquals("stats timer value time-cost/update should be 2", 3, timer
|
||||
.getValue()
|
||||
|
|
Binary file not shown.
|
@ -0,0 +1 @@
|
|||
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip
|
|
@ -0,0 +1,22 @@
|
|||
Setting up the Maven Wrapper on an Application
|
||||
==============================================
|
||||
|
||||
This is the code that shows the configurations of maven wrapper on a SpringBoot project.
|
||||
|
||||
### Requirements
|
||||
|
||||
- Maven
|
||||
- JDK 7
|
||||
|
||||
### Running
|
||||
|
||||
To build and start the server simply type
|
||||
|
||||
```bash
|
||||
$ ./mvn clean install
|
||||
$ ./mvn spring-boot:run
|
||||
```
|
||||
|
||||
Now with default configurations it will be available at: [http://localhost:8080](http://localhost:8080)
|
||||
|
||||
Enjoy it :)
|
|
@ -0,0 +1,227 @@
|
|||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Maven2 Start Up Batch script
|
||||
#
|
||||
# Required ENV vars:
|
||||
# ------------------
|
||||
# JAVA_HOME - location of a JDK home dir
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# M2_HOME - location of maven2's installed home dir
|
||||
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
# e.g. to debug Maven itself, use
|
||||
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
if [ -z "$MAVEN_SKIP_RC" ] ; then
|
||||
|
||||
if [ -f /etc/mavenrc ] ; then
|
||||
. /etc/mavenrc
|
||||
fi
|
||||
|
||||
if [ -f "$HOME/.mavenrc" ] ; then
|
||||
. "$HOME/.mavenrc"
|
||||
fi
|
||||
|
||||
fi
|
||||
|
||||
# OS specific support. $var _must_ be set to either true or false.
|
||||
cygwin=false;
|
||||
darwin=false;
|
||||
mingw=false
|
||||
case "`uname`" in
|
||||
CYGWIN*) cygwin=true ;;
|
||||
MINGW*) mingw=true;;
|
||||
Darwin*) darwin=true
|
||||
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
|
||||
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
if [ -x "/usr/libexec/java_home" ]; then
|
||||
export JAVA_HOME="`/usr/libexec/java_home`"
|
||||
else
|
||||
export JAVA_HOME="/Library/Java/Home"
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
if [ -r /etc/gentoo-release ] ; then
|
||||
JAVA_HOME=`java-config --jre-home`
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$M2_HOME" ] ; then
|
||||
## resolve links - $0 may be a link to maven's home
|
||||
PRG="$0"
|
||||
|
||||
# need this for relative symlinks
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG="`dirname "$PRG"`/$link"
|
||||
fi
|
||||
done
|
||||
|
||||
saveddir=`pwd`
|
||||
|
||||
M2_HOME=`dirname "$PRG"`/..
|
||||
|
||||
# make it fully qualified
|
||||
M2_HOME=`cd "$M2_HOME" && pwd`
|
||||
|
||||
cd "$saveddir"
|
||||
# echo Using m2 at $M2_HOME
|
||||
fi
|
||||
|
||||
# For Cygwin, ensure paths are in UNIX format before anything is touched
|
||||
if $cygwin ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --unix "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
|
||||
fi
|
||||
|
||||
# For Mingw, ensure paths are in UNIX format before anything is touched
|
||||
if $mingw ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME="`(cd "$M2_HOME"; pwd)`"
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
|
||||
# TODO classpath?
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
javaExecutable="`which javac`"
|
||||
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
|
||||
# readlink(1) is not available as standard on Solaris 10.
|
||||
readLink=`which readlink`
|
||||
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
|
||||
if $darwin ; then
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
|
||||
else
|
||||
javaExecutable="`readlink -f \"$javaExecutable\"`"
|
||||
fi
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
|
||||
JAVA_HOME="$javaHome"
|
||||
export JAVA_HOME
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$JAVACMD" ] ; then
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
else
|
||||
JAVACMD="`which java`"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
echo "Error: JAVA_HOME is not defined correctly." >&2
|
||||
echo " We cannot execute $JAVACMD" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
echo "Warning: JAVA_HOME environment variable is not set."
|
||||
fi
|
||||
|
||||
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
|
||||
|
||||
# traverses directory structure from process work directory to filesystem root
|
||||
# first directory with .mvn subdirectory is considered project base directory
|
||||
find_maven_basedir() {
|
||||
|
||||
if [ -z "$1" ]
|
||||
then
|
||||
echo "Path not specified to find_maven_basedir"
|
||||
return 1
|
||||
fi
|
||||
|
||||
basedir="$1"
|
||||
wdir="$1"
|
||||
while [ "$wdir" != '/' ] ; do
|
||||
if [ -d "$wdir"/.mvn ] ; then
|
||||
basedir=$wdir
|
||||
break
|
||||
fi
|
||||
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
|
||||
if [ -d "${wdir}" ]; then
|
||||
wdir=`cd "$wdir/.."; pwd`
|
||||
fi
|
||||
# end of workaround
|
||||
done
|
||||
echo "${basedir}"
|
||||
}
|
||||
|
||||
# concatenates all lines of a file
|
||||
concat_lines() {
|
||||
if [ -f "$1" ]; then
|
||||
echo "$(tr -s '\n' ' ' < "$1")"
|
||||
fi
|
||||
}
|
||||
|
||||
BASE_DIR=`find_maven_basedir "$(pwd)"`
|
||||
if [ -z "$BASE_DIR" ]; then
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo $MAVEN_PROJECTBASEDIR
|
||||
fi
|
||||
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --path --windows "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
|
||||
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
|
||||
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
|
||||
fi
|
||||
|
||||
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
exec "$JAVACMD" \
|
||||
$MAVEN_OPTS \
|
||||
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
|
||||
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
|
||||
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
|
|
@ -0,0 +1,145 @@
|
|||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM http://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Maven2 Start Up Batch script
|
||||
@REM
|
||||
@REM Required ENV vars:
|
||||
@REM JAVA_HOME - location of a JDK home dir
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM M2_HOME - location of maven2's installed home dir
|
||||
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
|
||||
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
|
||||
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
@REM e.g. to debug Maven itself, use
|
||||
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
|
||||
@echo off
|
||||
@REM set title of command window
|
||||
title %0
|
||||
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
|
||||
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
|
||||
|
||||
@REM set %HOME% to equivalent of $HOME
|
||||
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
|
||||
|
||||
@REM Execute a user defined script before this one
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
|
||||
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
|
||||
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
|
||||
:skipRcPre
|
||||
|
||||
@setlocal
|
||||
|
||||
set ERROR_CODE=0
|
||||
|
||||
@REM To isolate internal variables from possible post scripts, we use another setlocal
|
||||
@setlocal
|
||||
|
||||
@REM ==== START VALIDATION ====
|
||||
if not "%JAVA_HOME%" == "" goto OkJHome
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME not found in your environment. >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
:OkJHome
|
||||
if exist "%JAVA_HOME%\bin\java.exe" goto init
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME is set to an invalid directory. >&2
|
||||
echo JAVA_HOME = "%JAVA_HOME%" >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
@REM ==== END VALIDATION ====
|
||||
|
||||
:init
|
||||
|
||||
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
|
||||
@REM Fallback to current working directory if not found.
|
||||
|
||||
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
|
||||
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
|
||||
|
||||
set EXEC_DIR=%CD%
|
||||
set WDIR=%EXEC_DIR%
|
||||
:findBaseDir
|
||||
IF EXIST "%WDIR%"\.mvn goto baseDirFound
|
||||
cd ..
|
||||
IF "%WDIR%"=="%CD%" goto baseDirNotFound
|
||||
set WDIR=%CD%
|
||||
goto findBaseDir
|
||||
|
||||
:baseDirFound
|
||||
set MAVEN_PROJECTBASEDIR=%WDIR%
|
||||
cd "%EXEC_DIR%"
|
||||
goto endDetectBaseDir
|
||||
|
||||
:baseDirNotFound
|
||||
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
|
||||
cd "%EXEC_DIR%"
|
||||
|
||||
:endDetectBaseDir
|
||||
|
||||
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
|
||||
|
||||
@setlocal EnableExtensions EnableDelayedExpansion
|
||||
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
|
||||
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
|
||||
|
||||
:endReadAdditionalConfig
|
||||
|
||||
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
|
||||
|
||||
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
|
||||
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
|
||||
if ERRORLEVEL 1 goto error
|
||||
goto end
|
||||
|
||||
:error
|
||||
set ERROR_CODE=1
|
||||
|
||||
:end
|
||||
@endlocal & set ERROR_CODE=%ERROR_CODE%
|
||||
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
|
||||
@REM check for post script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
|
||||
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
|
||||
:skipRcPost
|
||||
|
||||
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
|
||||
if "%MAVEN_BATCH_PAUSE%" == "on" pause
|
||||
|
||||
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
|
||||
|
||||
exit /B %ERROR_CODE%
|
|
@ -0,0 +1,45 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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>
|
||||
|
||||
<artifactId>mvn-wrapper</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>mvn-wrapper</name>
|
||||
<description>Setting up the Maven Wrapper</description>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-boot-5</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-boot-5</relativePath>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class MvnWrapperApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(MvnWrapperApplication.class, args);
|
||||
}
|
||||
}
|
|
@ -1 +0,0 @@
|
|||
## Relevant articles:
|
|
@ -1,81 +0,0 @@
|
|||
<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>parent-boot-4</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
<name>Parent Boot 4</name>
|
||||
<description>Parent for all spring boot 1.4 modules</description>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<rest-assured.version>3.0.1</rest-assured.version>
|
||||
<!-- plugins -->
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<version>1.4.4.RELEASE</version>
|
||||
<relativePath />
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.rest-assured</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
<version>${rest-assured.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<forkCount>3</forkCount>
|
||||
<reuseForks>true</reuseForks>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
<exclude>**/JdbcTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue