Merge pull request #1 from eugenp/master

Merge
This commit is contained in:
Krzysztof Majewski 2021-03-31 15:22:55 +02:00 committed by GitHub
commit 1b2d44a9eb
292 changed files with 3920 additions and 697 deletions

View File

@ -38,8 +38,6 @@
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<akka.http.version>10.0.11</akka.http.version>
<akka.stream.version>2.5.11</akka.stream.version>
</properties>

View File

@ -91,8 +91,6 @@
<commons-collections4.version>4.3</commons-collections4.version>
<guava.version>28.0-jre</guava.version>
<retrofit.version>2.6.0</retrofit.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator.version>1.19</jmh-generator.version>
<commons.lang3.version>3.8.1</commons.lang3.version>
<JUnitParams.version>1.1.0</JUnitParams.version>
</properties>

View File

@ -13,22 +13,22 @@ public class KadaneAlgorithm {
int start = 0;
int end = 0;
int maxSoFar = 0, maxEndingHere = 0;
int maxSoFar = arr[0], maxEndingHere = arr[0];
for (int i = 0; i < size; i++) {
if (arr[i] > maxEndingHere + arr[i]) {
start = i;
maxEndingHere = arr[i];
} else
} else {
maxEndingHere = maxEndingHere + arr[i];
}
if (maxSoFar < maxEndingHere) {
maxSoFar = maxEndingHere;
end = i;
}
}
logger.info("Found Maximum Subarray between {} and {}", start, end);
logger.info("Found Maximum Subarray between {} and {}", Math.min(start, end), end);
return maxSoFar;
}
}

View File

@ -9,11 +9,22 @@ class KadaneAlgorithmUnitTest {
@Test
void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturns6() {
//given
int[] arr = new int[]{-3, 1, -8, 4, -1, 2, 1, -5, 5};
int[] arr = new int[] { -3, 1, -8, 4, -1, 2, 1, -5, 5 };
//when
KadaneAlgorithm algorithm = new KadaneAlgorithm();
int maxSum = algorithm.maxSubArraySum(arr);
//then
assertEquals(6, maxSum);
}
@Test
void givenArrayWithAllNegativeNumbersWhenMaximumSubarrayThenReturnsExpectedResult() {
//given
int[] arr = new int[] { -8, -7, -5, -4, -3, -1, -2 };
//when
KadaneAlgorithm algorithm = new KadaneAlgorithm();
int maxSum = algorithm.maxSubArraySum(arr);
//then
assertEquals(-1, maxSum);
}
}

View File

@ -13,7 +13,7 @@ import java.util.Objects;
import static org.junit.Assert.*;
public class AvroSerealizerDeSerealizerUnitTest {
public class AvroSerealizerDeSerealizerIntegrationTest {
AvroSerealizer serealizer;
AvroDeSerealizer deSerealizer;

View File

@ -17,7 +17,7 @@ import okhttp3.Request;
import okhttp3.Response;
@RunWith(MonoMeecrowave.Runner.class)
public class ArticleEndpointsUnitTest {
public class ArticleEndpointsIntegrationTest {
@ConfigurationInject
private Meecrowave.Builder config;

View File

@ -11,3 +11,4 @@ This module contains articles about Apache POI
- [Get String Value of Excel Cell with Apache POI](https://www.baeldung.com/java-apache-poi-cell-string-value)
- [Read Excel Cell Value Rather Than Formula With Apache POI](https://www.baeldung.com/apache-poi-read-cell-value-formula)
- [Setting Formulas in Excel with Apache POI](https://www.baeldung.com/java-apache-poi-set-formulas)
- [Insert a Row in Excel Using Apache POI](https://www.baeldung.com/apache-poi-insert-excel-row)

View File

@ -100,7 +100,6 @@
</build>
<properties>
<java.version>1.8</java.version>
<spring.version>2.2.1.RELEASE</spring.version>
<awssdk.version>2.10.27</awssdk.version>
</properties>

View File

@ -115,7 +115,6 @@
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.plugin.version}</version>
<configuration>
<useFile>false</useFile>
<includes>
@ -186,7 +185,6 @@
<logback.version>1.2.3</logback.version>
<groovy.version>2.5.7</groovy.version>
<assembly.plugin.version>3.1.0</assembly.plugin.version>
<surefire.plugin.version>2.20.1</surefire.plugin.version>
<compiler.plugin.version>3.8.0</compiler.plugin.version>
<groovy.compiler.version>3.3.0-01</groovy.compiler.version>
</properties>

View File

@ -101,7 +101,6 @@
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.plugin.version}</version>
<configuration>
<useFile>false</useFile>
<includes>
@ -128,7 +127,6 @@
<hsqldb.version>2.4.0</hsqldb.version>
<spock-core.version>1.1-groovy-2.4</spock-core.version>
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
<surefire.plugin.version>2.20.1</surefire.plugin.version>
</properties>
</project>

View File

@ -11,3 +11,4 @@ This module contains articles about Java 10 core features
- [Copying Sets in Java](https://www.baeldung.com/java-copy-sets)
- [Converting between a List and a Set in Java](https://www.baeldung.com/convert-list-to-set-and-set-to-list)
- [Java IndexOutOfBoundsException “Source Does Not Fit in Dest”](https://www.baeldung.com/java-indexoutofboundsexception)
- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection)

View File

@ -0,0 +1,20 @@
package com.baeldung.java10.streams;
import static java.util.stream.Collectors.toUnmodifiableList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class StreamToImmutableJava10UnitTest {
@Test
public void whenUsingCollectorsToUnmodifiableList_thenSuccess() {
List<String> givenList = Arrays.asList("a", "b", "c");
List<String> result = givenList.stream()
.collect(toUnmodifiableList());
System.out.println(result.getClass());
}
}

View File

@ -32,12 +32,12 @@
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
<version>${jmh-generator.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
@ -105,7 +105,6 @@
<guava.version>27.1-jre</guava.version>
<assertj.version>3.11.1</assertj.version>
<uberjar.name>benchmarks</uberjar.name>
<jmh.version>1.22</jmh.version>
<eclipse.collections.version>10.0.0</eclipse.collections.version>
<shade.plugin.version>3.2.4</shade.plugin.version>
</properties>

View File

@ -17,16 +17,18 @@
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.19.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<jmh.version>1.19</jmh.version>
</properties>
</project>

View File

@ -2,7 +2,6 @@ package com.baeldung.genericarrays;
import org.junit.Test;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

View File

@ -0,0 +1,77 @@
package com.baeldung.genericarrays;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.IntFunction;
import java.util.stream.Stream;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class StreamToArrayUnitTest {
@Test
public void givenAStream_thenCanGetArrayOfObject() {
Object[] strings = Stream.of("A", "AAA", "B", "AAB", "C")
.filter(string -> string.startsWith("A"))
.toArray();
assertThat(strings).containsExactly("A", "AAA", "AAB");
assertThat(strings).isNotInstanceOf(String[].class);
}
@Test
public void givenAStream_thenCanGetArrayOfString() {
String[] strings = Stream.of("A", "AAA", "B", "AAB", "C")
.filter(string -> string.startsWith("A"))
.toArray(String[]::new);
assertThat(strings).containsExactly("A", "AAA", "AAB");
assertThat(strings).isInstanceOf(String[].class);
}
@SuppressWarnings("unchecked")
@Test
public void givenAStream_whenConvertToOptional_thenCanGetArrayOfOptional() {
Stream<Optional<String>> stream = Stream.of("A", "AAA", "B", "AAB", "C")
.filter(string -> string.startsWith("A"))
.map(Optional::of);
Optional<String>[] strings = stream
.toArray(Optional[]::new);
assertThat(strings).containsExactly(Optional.of("A"),
Optional.of("AAA"),
Optional.of("AAB"));
assertThat(strings).isInstanceOf(Optional[].class);
}
@Test
public void givenAStream_whenConvertToOptional_thenCanGetArrayOfOptionalWithHelper() {
Optional<String>[] strings = Stream.of("A", "AAA", "B", "AAB", "C")
.filter(string -> string.startsWith("A"))
.map(Optional::of)
.toArray(genericArray(Optional[]::new));
assertThat(strings).containsExactly(Optional.of("A"),
Optional.of("AAA"),
Optional.of("AAB"));
assertThat(strings).isInstanceOf(Optional[].class);
}
@Test
public void whenInvalidUseOfGenericArray_thenIllegalCast() {
assertThatThrownBy(() -> {
ArrayList<String>[] lists = Stream.of(singletonList("A"))
.toArray(genericArray(List[]::new));
}).isInstanceOf(ClassCastException.class);
}
@SuppressWarnings("unchecked")
private static <T, R extends T> IntFunction<R[]> genericArray(IntFunction<T[]> arrayCreator) {
return size -> (R[])arrayCreator.apply(size);
}
}

View File

@ -24,12 +24,12 @@
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
@ -68,7 +68,6 @@
<properties>
<shade.plugin.version>3.2.0</shade.plugin.version>
<jmh.version>1.19</jmh.version>
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>

View File

@ -31,12 +31,12 @@
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
<version>${jmh-generator.version}</version>
</dependency>
<!-- Testing -->
@ -77,7 +77,6 @@
<properties>
<shade.plugin.version>3.2.0</shade.plugin.version>
<guava.version>28.2-jre</guava.version>
<jmh.version>1.19</jmh.version>
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>

View File

@ -25,17 +25,16 @@
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${openjdk.jmh.version}</version>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${openjdk.jmh.version}</version>
<version>${jmh-generator.version}</version>
</dependency>
</dependencies>
<properties>
<openjdk.jmh.version>1.19</openjdk.jmh.version>
<assertj.version>3.11.1</assertj.version>
</properties>

View File

@ -24,7 +24,7 @@
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${openjdk.jmh.version}</version>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
@ -40,7 +40,6 @@
</dependencies>
<properties>
<openjdk.jmh.version>1.19</openjdk.jmh.version>
<assertj.version>3.11.1</assertj.version>
<jol-core.version>0.10</jol-core.version>
</properties>

View File

@ -5,3 +5,4 @@
### Relevant Articles:
- [ArrayList vs. LinkedList vs. HashMap in Java](https://www.baeldung.com/java-arraylist-vs-linkedlist-vs-hashmap)
- [Java Deque vs. Stack](https://www.baeldung.com/java-deque-vs-stack)

View File

@ -58,7 +58,7 @@
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-core.version}</version>
<version>${jmh-generator.version}</version>
</dependency>
</dependencies>

View File

@ -8,6 +8,7 @@ import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
@ -18,12 +19,12 @@ import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
public class PrimitivesListPerformance {
private List<Integer> arrayList = new ArrayList<>();
private TIntArrayList tList = new TIntArrayList();
private cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList();
private IntArrayList fastUtilList = new IntArrayList();
private List<Integer> arrayList = new ArrayList<>(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9));
private TIntArrayList tList = new TIntArrayList(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
private cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
private IntArrayList fastUtilList = new IntArrayList(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
private int getValue = 10;
private int getValue = 4;
@Benchmark
public boolean addArrayList() {

View File

@ -8,4 +8,5 @@ This module contains articles about Map data structures in Java.
- [The Map.computeIfAbsent() Method](https://www.baeldung.com/java-map-computeifabsent)
- [Collections.synchronizedMap vs. ConcurrentHashMap](https://www.baeldung.com/java-synchronizedmap-vs-concurrenthashmap)
- [Java HashMap Load Factor](https://www.baeldung.com/java-hashmap-load-factor)
- [Converting java.util.Properties to HashMap](https://www.baeldung.com/java-convert-properties-to-hashmap)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2)

View File

@ -25,17 +25,16 @@
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${openjdk.jmh.version}</version>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${openjdk.jmh.version}</version>
<version>${jmh-generator.version}</version>
</dependency>
</dependencies>
<properties>
<openjdk.jmh.version>1.19</openjdk.jmh.version>
<assertj.version>3.11.1</assertj.version>
</properties>

View File

@ -29,7 +29,7 @@
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator-annprocess.version}</version>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
@ -51,8 +51,6 @@
</build>
<properties>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
<assertj.version>3.6.1</assertj.version>
</properties>

View File

@ -23,12 +23,12 @@
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
@ -39,7 +39,6 @@
</dependencies>
<properties>
<jmh.version>1.21</jmh.version>
<guava.version>28.2-jre</guava.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>

View File

@ -21,14 +21,16 @@ public class ThreadPoolInParallelStreamIntegrationTest {
long lastNum = 1_000_000;
List<Long> aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList());
ForkJoinPool customThreadPool = new ForkJoinPool(4);
long actualTotal = customThreadPool
.submit(() -> aList.parallelStream()
.reduce(0L, Long::sum))
.get();
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
try {
long actualTotal = customThreadPool
.submit(() -> aList.parallelStream().reduce(0L, Long::sum))
.get();
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
} finally {
customThreadPool.shutdown();
}
}
@Test

View File

@ -5,12 +5,12 @@ import com.google.common.io.CharSource;
import com.google.common.io.Files;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.ReaderInputStream;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class JavaXToInputStreamUnitTest {
protected final Logger logger = LoggerFactory.getLogger(getClass());
@ -28,7 +28,7 @@ public class JavaXToInputStreamUnitTest {
@Test
public final void givenUsingGuava_whenConvertingStringToInputStream_thenCorrect() throws IOException {
final String initialString = "text";
final InputStream targetStream = new ReaderInputStream(CharSource.wrap(initialString).openStream());
final InputStream targetStream = CharSource.wrap(initialString).asByteSource(StandardCharsets.UTF_8).openStream();
IOUtils.closeQuietly(targetStream);
}

View File

@ -77,7 +77,6 @@
<assertj.version>3.6.1</assertj.version>
<!-- instrumentation -->
<javaassist.version>3.27.0-GA</javaassist.version>
<esapi.version>2.1.0.1</esapi.version>
<sun.tools.version>1.8.0</sun.tools.version>
<jol-core.version>0.10</jol-core.version>
<asm.version>8.0.1</asm.version>

View File

@ -65,8 +65,6 @@
</build>
<properties>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator.version>1.19</jmh-generator.version>
<assertj.version>3.12.2</assertj.version>
<commons.beanutils.version>1.9.4</commons.beanutils.version>
<guava.version>29.0-jre</guava.version>

View File

@ -0,0 +1,5 @@
## Core Java Lang (Part 4)
This module contains articles about core features in the Java language
- [The Java final Keyword Impact on Performance](https://www.baeldung.com/java-final-performance)

View File

@ -0,0 +1,43 @@
<?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>core-java-lang-4</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-lang-4</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-lang-4</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>

View File

@ -0,0 +1,34 @@
package com.baeldung.finalkeyword;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import java.util.concurrent.TimeUnit;
public class BenchmarkRunner {
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public static String concatNonFinalStrings() {
String x = "x";
String y = "y";
return x + y;
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public static String concatFinalStrings() {
final String x = "x";
final String y = "y";
return x + y;
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.finalkeyword;
import java.io.Console;
public class ClassVariableFinal {
static final boolean doX = false;
static final boolean doY = true;
public static void main(String[] args) {
Console console = System.console();
if (doX) {
console.writer().println("x");
} else if (doY) {
console.writer().println("y");
}
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.finalkeyword;
import java.io.Console;
public class ClassVariableNonFinal {
static boolean doX = false;
static boolean doY = true;
public static void main(String[] args) {
Console console = System.console();
if (doX) {
console.writer().println("x");
} else if (doY) {
console.writer().println("y");
}
}
}

View File

@ -58,7 +58,7 @@
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
<version>${jmh-generator.version}</version>
</dependency>
</dependencies>
@ -83,7 +83,6 @@
<nd4j.version>1.0.0-beta4</nd4j.version>
<colt.version>1.2.0</colt.version>
<la4j.version>0.6.0</la4j.version>
<jmh.version>1.19</jmh.version>
</properties>
</project>

View File

@ -0,0 +1,135 @@
package com.baeldung.classfile;
import org.apache.commons.lang3.StringUtils;
import com.baeldung.classfile.HelloWorld.HelloSomeone;
public class Outer {
// Static Nested class
static class StaticNested {
public String message() {
return "This is a static Nested Class";
}
}
// Non-static Nested class
class Nested {
public String message() {
return "This is a non-static Nested Class";
}
}
// Local class
public String message() {
class Local {
private String message() {
return "This is a Local Class within a method";
}
}
Local local = new Local();
return local.message();
}
// Local class within if clause
public String message(String name) {
if (StringUtils.isEmpty(name)) {
class Local {
private String message() {
return "This is a Local Class within if clause";
}
}
Local local = new Local();
return local.message();
} else
return "Welcome to " + name;
}
// Anonymous Inner class extending a class
public String greet() {
Outer anonymous = new Outer() {
@Override
public String greet() {
return "Running Anonymous Class...";
}
};
return anonymous.greet();
}
// Anonymous inner class implementing an interface
public String greet(String name) {
HelloWorld helloWorld = new HelloWorld() {
@Override
public String greet(String name) {
return "Welcome to " + name;
}
};
return helloWorld.greet(name);
}
// Anonymous inner class implementing nested interface
public String greetSomeone(String name) {
HelloSomeone helloSomeOne = new HelloSomeone() {
@Override
public String greet(String name) {
return "Hello " + name;
}
};
return helloSomeOne.greet(name);
}
// Nested interface within a class
interface HelloOuter {
public String hello(String name);
}
// Enum within a class
enum Color {
RED, GREEN, BLUE;
}
}
interface HelloWorld {
public String greet(String name);
// Nested class within an interface
class InnerClass implements HelloWorld {
@Override
public String greet(String name) {
return "Inner class within an interface";
}
}
// Nested interface within an interfaces
interface HelloSomeone {
public String greet(String name);
}
// Enum within an interface
enum Directon {
NORTH, SOUTH, EAST, WEST;
}
}
enum Level {
LOW, MEDIUM, HIGH;
}
enum Foods {
DRINKS, EATS;
// Enum within Enum
enum DRINKS {
APPLE_JUICE, COLA;
}
enum EATS {
POTATO, RICE;
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.classfile;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import com.baeldung.classfile.Outer.Nested;
public class OuterUnitTest {
@Test
public void when_static_nestedClass_then_verifyOutput() {
Outer.StaticNested nestedClass = new Outer.StaticNested();
assertEquals("This is a static Nested Class", nestedClass.message());
}
@Test
public void when_nestedClass_then_verifyOutput() {
Outer outer = new Outer();
Nested nestedClass = outer.new Nested();
assertEquals("This is a non-static Nested Class", nestedClass.message());
}
@Test
public void when_localClass_then_verifyOutput() {
Outer outer = new Outer();
assertEquals("This is a Local Class within a method", outer.message());
}
@Test
public void when_localClassInIfClause_then_verifyOutput() {
Outer outer = new Outer();
assertEquals("Welcome to Baeldung", outer.message("Baeldung"));
assertEquals("This is a Local Class within if clause", outer.message(""));
}
@Test
public void when_anonymousClass_then_verifyOutput() {
Outer outer = new Outer();
assertEquals("Running Anonymous Class...", outer.greet());
}
@Test
public void when_anonymousClassHelloWorld_then_verifyOutput() {
Outer outer = new Outer();
assertEquals("Welcome to Baeldung", outer.greet("Baeldung"));
}
}

View File

@ -67,8 +67,6 @@
<properties>
<hibernate.core.version>5.4.0.Final</hibernate.core.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator.version>1.19</jmh-generator.version>
<guava.version>27.1-jre</guava.version>
<assertj.version>3.10.0</assertj.version>
<rest-assured.version>3.1.1</rest-assured.version>

View File

@ -4,3 +4,4 @@
- [Set Field Value With Reflection](https://www.baeldung.com/java-set-private-field-value)
- [Checking If a Method is Static Using Reflection in Java](https://www.baeldung.com/java-check-method-is-static)
- [Checking if a Java Class is abstract Using Reflection](https://www.baeldung.com/java-reflection-is-class-abstract)
- [Invoking a Private Method in Java](https://www.baeldung.com/java-call-private-method)

View File

@ -14,6 +14,15 @@
<relativePath>../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-reflection-2</finalName>
<resources>
@ -40,5 +49,6 @@
<maven-compiler-plugin.version>3.8.0</maven-compiler-plugin.version>
<source.version>1.8</source.version>
<target.version>1.8</target.version>
<spring.version>5.3.4</spring.version>
</properties>
</project>

View File

@ -0,0 +1,18 @@
package com.baeldung.reflection.access.privatemethods;
public class LongArrayUtil {
public static int indexOf(long[] array, long target) {
return indexOf(array, target, 0, array.length);
}
private static int indexOf(long[] array, long target, int start, int end) {
for (int i = start; i < end; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.reflection.access.privatemethods;
import org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;
import java.lang.reflect.Method;
import static org.junit.jupiter.api.Assertions.assertEquals;
class InvokePrivateMethodsUnitTest {
private final long[] someLongArray = new long[] { 1L, 2L, 1L, 4L, 2L };
@Test
void whenSearchingForLongValueInSubsequenceUsingReflection_thenTheCorrectIndexOfTheValueIsReturned() throws Exception {
Method indexOfMethod = LongArrayUtil.class.getDeclaredMethod("indexOf", long[].class, long.class, int.class, int.class);
indexOfMethod.setAccessible(true);
assertEquals(2, indexOfMethod.invoke(LongArrayUtil.class, someLongArray, 1L, 1, someLongArray.length), "The index should be 2.");
}
@Test
void whenSearchingForLongValueInSubsequenceUsingSpring_thenTheCorrectIndexOfTheValueIsReturned() throws Exception {
int indexOfSearchTarget = ReflectionTestUtils.invokeMethod(LongArrayUtil.class, "indexOf", someLongArray, 1L, 1, someLongArray.length);
assertEquals(2, indexOfSearchTarget, "The index should be 2.");
}
}

View File

@ -15,4 +15,5 @@ This module contains articles about core Java Security
- [Security Context Basics: User, Subject and Principal](https://www.baeldung.com/security-context-basics)
- [Java AES Encryption and Decryption](https://www.baeldung.com/java-aes-encryption-decryption)
- [InvalidAlgorithmParameterException: Wrong IV Length](https://www.baeldung.com/java-invalidalgorithmparameter-exception)
- [The java.security.egd JVM Option](https://www.baeldung.com/java-security-egd)
- More articles: [[<-- prev]](/core-java-modules/core-java-security)

View File

@ -47,7 +47,6 @@
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
<assertj.version>3.11.1</assertj.version>

View File

@ -49,8 +49,6 @@
<properties>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<!-- plugins -->
<maven-surefire-plugin.version>2.22.1</maven-surefire-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,95 @@
package com.baeldung.streams.streamvscollection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamVsCollectionExample {
static ArrayList<String> userNameSource = new ArrayList<>();
static {
userNameSource.add("john");
userNameSource.add("smith");
userNameSource.add("tom");
userNameSource.add("rob");
userNameSource.add("charlie");
userNameSource.add("alfred");
}
public static Stream<String> userNames() {
return userNameSource.stream();
}
public static List<String> userNameList() {
return userNames().collect(Collectors.toList());
}
public static Set<String> userNameSet() {
return userNames().collect(Collectors.toSet());
}
public static Map<String, String> userNameMap() {
return userNames().collect(Collectors.toMap(u1 -> u1.toString(), u1 -> u1.toString()));
}
public static Stream<String> filterUserNames() {
return userNames().filter(i -> i.length() >= 4);
}
public static Stream<String> sortUserNames() {
return userNames().sorted();
}
public static Stream<String> limitUserNames() {
return userNames().limit(3);
}
public static Stream<String> sortFilterLimitUserNames() {
return filterUserNames().sorted().limit(3);
}
public static void printStream(Stream<String> stream) {
stream.forEach(System.out::println);
}
public static void modifyList() {
userNameSource.remove(2);
}
public static Map<String, String> modifyMap() {
Map<String, String> userNameMap = userNameMap();
userNameMap.put("bob", "bob");
userNameMap.remove("alfred");
return userNameMap;
}
public static void tryStreamTraversal() {
Stream<String> userNameStream = userNames();
userNameStream.forEach(System.out::println);
try {
userNameStream.forEach(System.out::println);
} catch(IllegalStateException e) {
System.out.println("stream has already been operated upon or closed");
}
}
public static void main(String[] args) {
System.out.println(userNameMap());
System.out.println(modifyMap());
tryStreamTraversal();
Set<String> set = userNames().collect(Collectors.toCollection(TreeSet::new));
set.forEach(val -> System.out.println(val));
}
}

View File

@ -34,7 +34,7 @@
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-core.version}</version>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>

View File

@ -39,7 +39,7 @@
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-core.version}</version>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
<groupId>com.vdurmont</groupId>

View File

@ -59,7 +59,6 @@
<compiler.plugin.version>3.8.0</compiler.plugin.version>
<source.version>1.9</source.version>
<target.version>1.9</target.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<assertj-core.version>3.12.2</assertj-core.version>
</properties>

View File

@ -82,6 +82,7 @@
<module>core-java-lang</module>
<module>core-java-lang-2</module>
<module>core-java-lang-3</module>
<module>core-java-lang-4</module>
<module>core-java-lang-math</module>
<module>core-java-lang-math-2</module>
<module>core-java-lang-math-3</module>
@ -147,18 +148,6 @@
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
<junit-jupiter.version>5.6.2</junit-jupiter.version>

View File

@ -45,7 +45,6 @@
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
<pmdVersion>6.0.1</pmdVersion>
<maven.compiler.source>1.8</maven.compiler.source>

View File

@ -10,10 +10,8 @@ public class CircularBuffer<E> {
@SuppressWarnings("unchecked")
public CircularBuffer(int capacity) {
this.capacity = (capacity < 1) ? DEFAULT_CAPACITY : capacity;
this.data = (E[]) new Object[capacity];
this.data = (E[]) new Object[this.capacity];
this.readSequence = 0;
this.writeSequence = -1;
}

View File

@ -5,7 +5,7 @@ import org.slf4j.LoggerFactory;
public class CircularLinkedList {
final Logger LOGGER = LoggerFactory.getLogger(CircularLinkedList.class);
final Logger logger = LoggerFactory.getLogger(CircularLinkedList.class);
private Node head = null;
private Node tail = null;
@ -42,24 +42,29 @@ public class CircularLinkedList {
}
public void deleteNode(int valueToDelete) {
Node currentNode = head;
if (head != null) {
if (currentNode.value == valueToDelete) {
head = head.nextNode;
tail.nextNode = head;
} else {
do {
Node nextNode = currentNode.nextNode;
if (nextNode.value == valueToDelete) {
currentNode.nextNode = nextNode.nextNode;
break;
}
currentNode = currentNode.nextNode;
} while (currentNode != head);
}
if (head == null) {
return;
}
do {
Node nextNode = currentNode.nextNode;
if (nextNode.value == valueToDelete) {
if (tail == head) {
head = null;
tail = null;
} else {
currentNode.nextNode = nextNode.nextNode;
if (head == nextNode) {
head = head.nextNode;
}
if (tail == nextNode) {
tail = currentNode;
}
}
break;
}
currentNode = nextNode;
} while (currentNode != head);
}
public void traverseList() {
@ -68,7 +73,7 @@ public class CircularLinkedList {
if (head != null) {
do {
LOGGER.info(currentNode.value + " ");
logger.info(currentNode.value + " ");
currentNode = currentNode.nextNode;
} while (currentNode != head);
}

View File

@ -148,48 +148,46 @@ public class BinaryTree {
}
}
public void traverseInOrderWithoutRecursion() {
Stack<Node> stack = new Stack<Node>();
Stack<Node> stack = new Stack<>();
Node current = root;
while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.push(current);
current = current.left;
}
Node top = stack.pop();
visit(top.value);
current = top.right;
}
}
public void traversePreOrderWithoutRecursion() {
Stack<Node> stack = new Stack<>();
Node current = root;
stack.push(root);
while(! stack.isEmpty()) {
while(current.left != null) {
current = current.left;
stack.push(current);
}
while (current != null && !stack.isEmpty()) {
current = stack.pop();
visit(current.value);
if(current.right != null) {
current = current.right;
stack.push(current);
}
if (current.right != null)
stack.push(current.right);
if (current.left != null)
stack.push(current.left);
}
}
public void traversePreOrderWithoutRecursion() {
Stack<Node> stack = new Stack<Node>();
Node current = root;
stack.push(root);
while(! stack.isEmpty()) {
current = stack.pop();
visit(current.value);
if(current.right != null)
stack.push(current.right);
if(current.left != null)
stack.push(current.left);
}
}
public void traversePostOrderWithoutRecursion() {
Stack<Node> stack = new Stack<Node>();
Stack<Node> stack = new Stack<>();
Node prev = root;
Node current = root;
stack.push(root);
while (!stack.isEmpty()) {
while (current != null && !stack.isEmpty()) {
current = stack.peek();
boolean hasChild = (current.left != null || current.right != null);
boolean isPrevLastChild = (prev == current.right || (prev == current.left && current.right == null));

View File

@ -1,10 +1,10 @@
package com.baeldung.circularlinkedlist;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class CircularLinkedListUnitTest {
@Test
@ -23,7 +23,7 @@ public class CircularLinkedListUnitTest {
}
@Test
public void givenACircularLinkedList_WhenDeletingElements_ThenListDoesNotContainThoseElements() {
public void givenACircularLinkedList_WhenDeletingInOrderHeadMiddleTail_ThenListDoesNotContainThoseElements() {
CircularLinkedList cll = createCircularLinkedList();
assertTrue(cll.containsNode(13));
@ -39,6 +39,32 @@ public class CircularLinkedListUnitTest {
assertFalse(cll.containsNode(46));
}
@Test
public void givenACircularLinkedList_WhenDeletingInOrderTailMiddleHead_ThenListDoesNotContainThoseElements() {
CircularLinkedList cll = createCircularLinkedList();
assertTrue(cll.containsNode(46));
cll.deleteNode(46);
assertFalse(cll.containsNode(46));
assertTrue(cll.containsNode(1));
cll.deleteNode(1);
assertFalse(cll.containsNode(1));
assertTrue(cll.containsNode(13));
cll.deleteNode(13);
assertFalse(cll.containsNode(13));
}
@Test
public void givenACircularLinkedListWithOneNode_WhenDeletingElement_ThenListDoesNotContainTheElement() {
CircularLinkedList cll = new CircularLinkedList();
cll.addNode(1);
cll.deleteNode(1);
assertFalse(cll.containsNode(1));
}
private CircularLinkedList createCircularLinkedList() {
CircularLinkedList cll = new CircularLinkedList();

View File

@ -13,7 +13,7 @@ public class BinaryTreeUnitTest {
BinaryTree bt = createBinaryTree();
assertTrue(!bt.isEmpty());
assertFalse(bt.isEmpty());
}
@Test
@ -72,6 +72,7 @@ public class BinaryTreeUnitTest {
@Test
public void it_deletes_the_root() {
int value = 12;
BinaryTree bt = new BinaryTree();
bt.add(value);
@ -91,6 +92,14 @@ public class BinaryTreeUnitTest {
bt.traverseInOrderWithoutRecursion();
}
@Test
public void givenAnEmptyBinaryTree_WhenTraversingInOrderWithoutRecursion_ThenNoException() {
BinaryTree empty = new BinaryTree();
empty.traverseInOrderWithoutRecursion();
}
@Test
public void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() {
@ -101,6 +110,14 @@ public class BinaryTreeUnitTest {
bt.traversePreOrderWithoutRecursion();
}
@Test
public void givenAnEmptyBinaryTree_WhenTraversingPreOrderWithoutRecursion_ThenNoException() {
BinaryTree empty = new BinaryTree();
empty.traversePreOrderWithoutRecursion();
}
@Test
public void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() {
@ -111,6 +128,14 @@ public class BinaryTreeUnitTest {
bt.traversePostOrderWithoutRecursion();
}
@Test
public void givenAnEmptyBinaryTree_WhenTraversingPostOrderWithoutRecursion_ThenNoException() {
BinaryTree empty = new BinaryTree();
empty.traversePostOrderWithoutRecursion();
}
@Test
public void givenABinaryTree_WhenTraversingLevelOrder_ThenPrintValues() {

View File

@ -29,7 +29,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<enableAssertions>true</enableAssertions>
</configuration>

View File

@ -66,7 +66,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<forkCount>0</forkCount>
</configuration>
@ -75,13 +74,10 @@
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<source.version>9</source.version>
<target.version>9</target.version>
<compiler.plugin.version>3.8.1</compiler.plugin.version>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
<appmodules.version>1.0</appmodules.version>

View File

@ -99,15 +99,6 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<joda-money.version>1.0.1</joda-money.version>

View File

@ -97,7 +97,6 @@
<!-- Skip normal test execution, we use gwt:test instead -->
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.plugin.version}</version>
<configuration>
<skip>true</skip>
</configuration>
@ -113,12 +112,8 @@
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!-- Don't let your Mac use a crazy non-standard encoding -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<gwt.version>2.8.2</gwt.version>
<gwt.plugin.version>1.0-rc-8</gwt.plugin.version>
<surefire.plugin.version>2.17</surefire.plugin.version>
</properties>
</project>

View File

@ -66,14 +66,6 @@
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<properties>

View File

@ -38,14 +38,6 @@
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<properties>

View File

@ -37,14 +37,6 @@
<build>
<finalName>guava-collections-set</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<properties>

View File

@ -71,14 +71,6 @@
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<properties>

View File

@ -40,14 +40,6 @@
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
</project>

View File

@ -52,14 +52,6 @@
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<properties>

View File

@ -46,17 +46,8 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<properties>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
<guava.version>29.0-jre</guava.version>
</properties>

View File

@ -50,16 +50,6 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<properties>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties>

View File

@ -51,14 +51,6 @@
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<properties>

View File

@ -3,3 +3,4 @@
- [Java Map With Case-Insensitive Keys](https://www.baeldung.com/java-map-with-case-insensitive-keys)
- [Using a Byte Array as Map Key in Java](https://www.baeldung.com/java-map-key-byte-array)
- [Using the Map.Entry Java Class](https://www.baeldung.com/java-map-entry)
- [Optimizing HashMaps Performance](https://www.baeldung.com/java-hashmap-optimize-performance)

View File

@ -1,44 +1,42 @@
package com.baeldung.rmi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.Test;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class JavaRMIIntegrationTest {
@BeforeClass
public static void whenRunServer_thenServerStarts() {
try {
MessengerServiceImpl server = new MessengerServiceImpl();
server.createStubAndBind();
} catch (RemoteException e) {
fail("Exception Occurred");
}
}
@Test
public void whenClientSendsMessageToServer_thenServerSendsResponseMessage() {
try {
Registry registry = LocateRegistry.getRegistry();
MessengerService server = (MessengerService) registry.lookup("MessengerService");
String responseMessage = server.sendMessage("Client Message");
String expectedMessage = "Server Message";
assertEquals(responseMessage, expectedMessage);
} catch (RemoteException e) {
fail("Exception Occurred");
} catch (NotBoundException nb) {
fail("Exception Occurred");
}
}
private MessengerServiceImpl messengerService;
@Before
public void init() {
try {
messengerService = new MessengerServiceImpl();
messengerService.createStubAndBind();
} catch (RemoteException e) {
fail("Exception Occurred: " + e);
}
}
@Test
public void whenClientSendsMessageToServer_thenServerSendsResponseMessage() {
try {
Registry registry = LocateRegistry.getRegistry();
MessengerService server = (MessengerService) registry.lookup("MessengerService");
String responseMessage = server.sendMessage("Client Message");
String expectedMessage = "Server Message";
assertEquals(responseMessage, expectedMessage);
} catch (RemoteException | NotBoundException e) {
fail("Exception Occurred: " + e);
}
}
}

View File

@ -523,7 +523,6 @@
<jersey.version>2.25</jersey.version>
<arquillian-glassfish.version>1.0.0.Final</arquillian-glassfish.version>
<org.springframework.security.version>4.2.3.RELEASE</org.springframework.security.version>
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<taglibs.standard.version>1.1.2</taglibs.standard.version>
<com.sun.faces.jsf.version>2.2.14</com.sun.faces.jsf.version>
<httpclient.version>4.5</httpclient.version>

View File

@ -12,7 +12,7 @@ import javax.batch.runtime.StepExecution;
import org.junit.jupiter.api.Test;
class CustomCheckPointUnitTest {
class CustomCheckPointIntegrationTest {
@Test
public void givenChunk_whenCustomCheckPoint_thenCommitCountIsThree() throws Exception {
JobOperator jobOperator = BatchRuntime.getJobOperator();

View File

@ -16,7 +16,7 @@ import javax.batch.runtime.StepExecution;
import org.junit.jupiter.api.Test;
class JobSequenceUnitTest {
class JobSequenceIntegrationTest {
@Test
public void givenTwoSteps_thenBatch_CompleteWithSuccess() throws Exception {
JobOperator jobOperator = BatchRuntime.getJobOperator();

View File

@ -11,7 +11,7 @@ import javax.batch.runtime.JobExecution;
import org.junit.jupiter.api.Test;
class SimpleBatchLetUnitTest {
class SimpleBatchLetIntegrationTest {
@Test
public void givenBatchLet_thenBatch_CompleteWithSuccess() throws Exception {
JobOperator jobOperator = BatchRuntime.getJobOperator();

View File

@ -16,7 +16,7 @@ import javax.batch.runtime.StepExecution;
import org.junit.jupiter.api.Test;
class SimpleChunkUnitTest {
class SimpleChunkIntegrationTest {
@Test
public void givenChunk_thenBatch_CompletesWithSucess() throws Exception {
JobOperator jobOperator = BatchRuntime.getJobOperator();

View File

@ -13,7 +13,7 @@ import javax.batch.runtime.StepExecution;
import org.junit.jupiter.api.Test;
class SimpleErrorChunkUnitTest {
class SimpleErrorChunkIntegrationTest {
@Test
public void givenChunkError_thenBatch_CompletesWithFailed() throws Exception {

View File

@ -1099,8 +1099,6 @@
<scala.version>2.12.6</scala.version>
<node.version>v10.15.0</node.version>
<npm.version>6.4.1</npm.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<project.testresult.directory>${project.build.directory}/test-results</project.testresult.directory>
<maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
<maven.compiler.source>${java.version}</maven.compiler.source>

View File

@ -1020,8 +1020,6 @@
<scala.version>2.12.6</scala.version>
<node.version>v8.12.0</node.version>
<npm.version>6.4.1</npm.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<project.testresult.directory>${project.build.directory}/test-results</project.testresult.directory>
<maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
<maven.compiler.source>${java.version}</maven.compiler.source>

View File

@ -840,8 +840,6 @@
<scala.version>2.12.6</scala.version>
<node.version>v8.12.0</node.version>
<npm.version>6.4.1</npm.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<project.testresult.directory>${project.build.directory}/test-results</project.testresult.directory>
<maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
<maven.compiler.source>${java.version}</maven.compiler.source>

View File

@ -842,8 +842,6 @@
<scala.version>2.12.6</scala.version>
<node.version>v8.12.0</node.version>
<npm.version>6.4.1</npm.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<project.testresult.directory>${project.build.directory}/test-results</project.testresult.directory>
<maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
<maven.compiler.source>${java.version}</maven.compiler.source>

View File

@ -47,3 +47,4 @@ Available commands (assumes httpie - https://github.com/jkbrzt/httpie):
## Relevant articles:
- [Supercharge Java Authentication with JSON Web Tokens (JWTs)](https://www.baeldung.com/java-json-web-tokens-jjwt)
- [Decode a JWT Token in Java](https://www.baeldung.com/java-jwt-token-decode)

View File

@ -41,6 +41,12 @@
<artifactId>jjwt</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>

View File

@ -0,0 +1,46 @@
package io.jsonwebtoken.jjwtfun.util;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.crypto.DefaultJwtSignatureValidator;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import static io.jsonwebtoken.SignatureAlgorithm.HS256;
public class JWTDecoderUtil {
public static String decodeJWTToken(String token) {
Base64.Decoder decoder = Base64.getDecoder();
String[] chunks = token.split("\\.");
String header = new String(decoder.decode(chunks[0]));
String payload = new String(decoder.decode(chunks[1]));
return header + " " + payload;
}
public static String decodeJWTToken(String token, String secretKey) throws Exception {
Base64.Decoder decoder = Base64.getDecoder();
String[] chunks = token.split("\\.");
String header = new String(decoder.decode(chunks[0]));
String payload = new String(decoder.decode(chunks[1]));
String tokenWithoutSignature = chunks[0] + "." + chunks[1];
String signature = chunks[2];
SignatureAlgorithm sa = HS256;
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), sa.getJcaName());
DefaultJwtSignatureValidator validator = new DefaultJwtSignatureValidator(sa, secretKeySpec);
if (!validator.isValid(tokenWithoutSignature, signature)) {
throw new Exception("Could not verify JWT token integrity!");
}
return header + " " + payload;
}
}

View File

@ -0,0 +1,32 @@
package io.jsonwebtoken.jjwtfun.util;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class JWTDecoderUtilUnitTest {
private final static String SIMPLE_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkJhZWxkdW5nIFVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9";
private final static String SIGNED_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkJhZWxkdW5nIFVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9.qH7Zj_m3kY69kxhaQXTa-ivIpytKXXjZc1ZSmapZnGE";
@Test
void givenSimpleToken_whenDecoding_thenStringOfHeaderPayloadAreReturned() {
assertThat(JWTDecoderUtil.decodeJWTToken(SIMPLE_TOKEN))
.contains(SignatureAlgorithm.HS256.getValue());
}
@Test
void givenSignedToken_whenDecodingWithInvalidSecret_thenIntegrityIsNotValidated() {
assertThatThrownBy(() -> JWTDecoderUtil.decodeJWTToken(SIGNED_TOKEN, "BAD_SECRET"))
.hasMessage("Could not verify JWT token integrity!");
}
@Test
void givenSignedToken_whenDecodingWithValidSecret_thenIntegrityIsValidated() throws Exception {
assertThat(JWTDecoderUtil.decodeJWTToken(SIGNED_TOKEN, "MySecretKey"))
.contains("Baeldung User");
}
}

View File

@ -52,3 +52,4 @@ Enjoy it :)
- [Intro to Performance Testing using JMeter](https://www.baeldung.com/jmeter)
- [Configure Jenkins to Run and Show JMeter Tests](https://www.baeldung.com/jenkins-and-jmeter)
- [Write Extracted Data to a File Using JMeter](https://www.baeldung.com/jmeter-write-to-file)

View File

@ -19,12 +19,12 @@
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${openjdk.jmh.version}</version>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${openjdk.jmh.version}</version>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jol</groupId>
@ -76,7 +76,6 @@
</build>
<properties>
<openjdk.jmh.version>1.19</openjdk.jmh.version>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
<jol-core.version>0.10</jol-core.version>
<maven-assembly-plugin.version>3.2.0</maven-assembly-plugin.version>

View File

@ -0,0 +1,17 @@
# Kubernetes Java API Sample Code
This module contains sample code used to show how to use the Kubernetes client Java API.
Before running those samples, make sure that your environment is correctly configured to access
a working Kubernetes cluster.
An easy way to check that everything is working as expected is issuing any *kubectl get* command:
```shell
$ kubectl get nodes
```
If you get a valid response, then you're good to go.
### Relevant Articles:
- [Paging and Async Calls with the Kubernetes API](https://www.baeldung.com/java-kubernetes-paging-async)

View File

@ -0,0 +1,41 @@
<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>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>kubernetes-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>k8s-intro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>io.kubernetes</groupId>
<artifactId>client-java</artifactId>
<version>11.0.0</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<!-- http://maven.apache.org/plugins/maven-compiler-plugin/ -->
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,11 @@
package com.baeldung.kubernetes.intro;
import io.kubernetes.client.openapi.ApiCallback;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import okhttp3.Call;
@FunctionalInterface
public interface ApiInvoker<R> {
Call apply(CoreV1Api api, ApiCallback<R> callback) throws ApiException;
}

View File

@ -0,0 +1,74 @@
package com.baeldung.kubernetes.intro;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.function.BiFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.kubernetes.client.openapi.ApiCallback;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import okhttp3.Call;
public class AsyncHelper<R> implements ApiCallback<R> {
private static final Logger log = LoggerFactory.getLogger(AsyncHelper.class);
private CoreV1Api api;
private CompletableFuture<R> callResult;
private AsyncHelper(CoreV1Api api) {
this.api = api;
}
public static <T> CompletableFuture<T> doAsync(CoreV1Api api, ApiInvoker<T> invoker) {
AsyncHelper<T> p = new AsyncHelper<>(api);
return p.execute(invoker);
}
private CompletableFuture<R> execute( ApiInvoker<R> invoker) {
try {
callResult = new CompletableFuture<>();
log.info("[I38] Calling API...");
final Call call = invoker.apply(api,this);
log.info("[I41] API Succesfully invoked: method={}, url={}",
call.request().method(),
call.request().url());
return callResult;
}
catch(ApiException aex) {
callResult.completeExceptionally(aex);
return callResult;
}
}
@Override
public void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders) {
log.error("[E53] onFailure",e);
callResult.completeExceptionally(e);
}
@Override
public void onSuccess(R result, int statusCode, Map<String, List<String>> responseHeaders) {
log.error("[E61] onSuccess: statusCode={}",statusCode);
callResult.complete(result);
}
@Override
public void onUploadProgress(long bytesWritten, long contentLength, boolean done) {
log.info("[E61] onUploadProgress: bytesWritten={}, contentLength={}, done={}",bytesWritten,contentLength,done);
}
@Override
public void onDownloadProgress(long bytesRead, long contentLength, boolean done) {
log.info("[E75] onDownloadProgress: bytesRead={}, contentLength={}, done={}",bytesRead,contentLength,done);
}
}

View File

@ -0,0 +1,31 @@
/**
*
*/
package com.baeldung.kubernetes.intro;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1NodeList;
import io.kubernetes.client.util.Config;
/**
* @author Philippe
*
*/
public class ListNodes {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
ApiClient client = Config.defaultClient();
CoreV1Api api = new CoreV1Api(client);
V1NodeList nodeList = api.listNode(null, null, null, null, null, null, null, null, 10, false);
nodeList.getItems()
.stream()
.forEach((node) -> System.out.println(node.getMetadata()));
}
}

View File

@ -0,0 +1,50 @@
/**
*
*/
package com.baeldung.kubernetes.intro;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1NodeList;
import io.kubernetes.client.util.Config;
/**
* @author Philippe
*
*/
public class ListNodesAsync {
private static Logger log = LoggerFactory.getLogger(ListNodesAsync.class);
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// Initial setup
ApiClient client = Config.defaultClient();
CoreV1Api api = new CoreV1Api(client);
// Start async call
CompletableFuture<V1NodeList> p = AsyncHelper.doAsync(api,(capi,cb) ->
capi.listNodeAsync(null, null, null, null, null, null, null, null, 10, false, cb)
);
p.thenAcceptAsync((nodeList) -> {
log.info("[I40] Processing results...");
nodeList.getItems()
.stream()
.forEach((node) -> System.out.println(node.getMetadata()));
});
log.info("[I46] Waiting results...");
p.get(10, TimeUnit.SECONDS);
}
}

View File

@ -0,0 +1,46 @@
/**
*
*/
package com.baeldung.kubernetes.intro;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1NodeList;
import io.kubernetes.client.openapi.models.V1PodList;
import io.kubernetes.client.util.Config;
/**
* @author Philippe
*
*/
public class ListPodsPaged {
private static final Logger log = LoggerFactory.getLogger(ListPodsPaged.class);
/**
* @param args
*/
public static void main(String[] args) throws Exception {
ApiClient client = Config.defaultClient();
CoreV1Api api = new CoreV1Api(client);
String continuationToken = null;
int limit = 2; // Just for illustration purposes. Real world values would range from ~100 to ~1000/page
Long remaining = null;
do {
log.info("==========================================================================");
log.info("Retrieving data: continuationToken={}, remaining={}", continuationToken,remaining);
V1PodList items = api.listPodForAllNamespaces(null, continuationToken, null, null, limit, null, null, null, 10, false);
continuationToken = items.getMetadata().getContinue();
remaining = items.getMetadata().getRemainingItemCount();
items.getItems()
.stream()
.forEach((node) -> System.out.println(node.getMetadata()));
} while( continuationToken != null );
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.kubernetes.intro;
import org.junit.jupiter.api.Test;
class ListNodesAsyncLiveTest {
@Test
void whenListNodes_thenSuccess() throws Exception {
ListNodesAsync.main(new String[] {});
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.kubernetes.intro;
import org.junit.jupiter.api.Test;
class ListNodesLiveTest {
@Test
void whenListNodes_thenSuccess() throws Exception {
ListNodes.main(new String[] {});
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.kubernetes.intro;
import org.junit.jupiter.api.Test;
class ListPodsPagedLiveTest {
@Test
void whenListPodsPage_thenSuccess() throws Exception {
ListPodsPaged.main(new String[] {});
}
}

View File

@ -0,0 +1,11 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration>

Some files were not shown because too many files have changed in this diff Show More