Merge pull request #1 from eugenp/master

update
This commit is contained in:
Hamid Reza Sharifi
2021-03-20 19:34:01 +03:30
committed by GitHub
126 changed files with 2546 additions and 124 deletions
+1
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)
+1
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)
@@ -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());
}
}
@@ -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)
@@ -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() {
@@ -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)
@@ -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
@@ -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);
}
-1
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>
@@ -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)
@@ -0,0 +1,47 @@
<?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.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.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>
<properties>
<jmh.version>1.28</jmh.version>
</properties>
</project>
@@ -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;
}
}
@@ -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");
}
}
}
@@ -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");
}
}
}
@@ -0,0 +1,131 @@
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() {
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() {
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() {
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 {
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;
}
}
@@ -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"));
}
}
@@ -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)
@@ -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>
@@ -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;
}
}
@@ -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.");
}
}
@@ -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)
+1
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>
@@ -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;
}
@@ -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);
}
@@ -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();
+1
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 HashMap’s Performance](https://www.baeldung.com/java-hashmap-optimize-performance)
@@ -20,7 +20,7 @@ public class JavaRMIIntegrationTest {
MessengerServiceImpl server = new MessengerServiceImpl();
server.createStubAndBind();
} catch (RemoteException e) {
fail("Exception Occurred");
fail("Exception Occurred: " + e);
}
}
@@ -34,11 +34,9 @@ public class JavaRMIIntegrationTest {
String expectedMessage = "Server Message";
assertEquals(responseMessage, expectedMessage);
} catch (RemoteException e) {
fail("Exception Occurred");
} catch (NotBoundException nb) {
fail("Exception Occurred");
}
} catch (RemoteException | NotBoundException e) {
fail("Exception Occurred: " + e);
};
}
}
+1
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)
+6
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>
@@ -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;
}
}

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