Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
@@ -4,19 +4,19 @@ import java.util.Objects;
|
||||
|
||||
public record Person (String name, String address) {
|
||||
|
||||
public static String UNKWOWN_ADDRESS = "Unknown";
|
||||
public static String UNNAMED = "Unnamed";
|
||||
public static String UNKNOWN_ADDRESS = "Unknown";
|
||||
public static String UNNAMED = "Unnamed";
|
||||
|
||||
public Person {
|
||||
Objects.requireNonNull(name);
|
||||
Objects.requireNonNull(address);
|
||||
}
|
||||
public Person {
|
||||
Objects.requireNonNull(name);
|
||||
Objects.requireNonNull(address);
|
||||
}
|
||||
|
||||
public Person(String name) {
|
||||
this(name, UNKWOWN_ADDRESS);
|
||||
}
|
||||
public Person(String name) {
|
||||
this(name, UNKNOWN_ADDRESS);
|
||||
}
|
||||
|
||||
public static Person unnamed(String address) {
|
||||
return new Person(UNNAMED, address);
|
||||
}
|
||||
}
|
||||
public static Person unnamed(String address) {
|
||||
return new Person(UNNAMED, address);
|
||||
}
|
||||
}
|
||||
@@ -134,7 +134,7 @@ public class PersonTest {
|
||||
Person person = new Person(name);
|
||||
|
||||
assertEquals(name, person.name());
|
||||
assertEquals(Person.UNKWOWN_ADDRESS, person.address());
|
||||
assertEquals(Person.UNKNOWN_ADDRESS, person.address());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -147,4 +147,4 @@ public class PersonTest {
|
||||
assertEquals(Person.UNNAMED, person.name());
|
||||
assertEquals(address, person.address());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
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-8-datetime</artifactId>
|
||||
<artifactId>core-java-8-datetime-2</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-8-datetime</name>
|
||||
<packaging>jar</packaging>
|
||||
@@ -41,7 +41,6 @@
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-datetime-java8</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
|
||||
@@ -12,3 +12,4 @@ This module contains articles about core Java features that have been introduced
|
||||
- [Introduction to Java 9 StackWalking API](https://www.baeldung.com/java-9-stackwalking-api)
|
||||
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
|
||||
- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams)
|
||||
- [Multi-Release JAR Files with Maven](https://www.baeldung.com/maven-multi-release-jars)
|
||||
|
||||
@@ -28,8 +28,104 @@
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<version>${awaitility.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>incubator-features</id>
|
||||
<build>
|
||||
<finalName>core-java-9-new-features</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
<compilerArgument>--add-modules=jdk.incubator.httpclient</compilerArgument>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<argLine>--add-modules=jdk.incubator.httpclient</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>mrjar-generation</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>compile-java-8</id>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<compileSourceRoots>
|
||||
<compileSourceRoot>${project.basedir}/src/main/java8</compileSourceRoot>
|
||||
</compileSourceRoots>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>compile-java-9</id>
|
||||
<phase>compile</phase>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<release>9</release>
|
||||
<compileSourceRoots>
|
||||
<compileSourceRoot>${project.basedir}/src/main/java9</compileSourceRoot>
|
||||
</compileSourceRoots>
|
||||
<outputDirectory>${project.build.outputDirectory}/META-INF/versions/9</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>default-testCompile</id>
|
||||
<phase>test-compile</phase>
|
||||
<goals>
|
||||
<goal>testCompile</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>${maven-jar-plugin.version}</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifestEntries>
|
||||
<Multi-Release>true</Multi-Release>
|
||||
</manifestEntries>
|
||||
<manifest>
|
||||
<mainClass>com.baeldung.multireleaseapp.App</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
<build>
|
||||
<finalName>core-java-9-new-features</finalName>
|
||||
<plugins>
|
||||
@@ -56,8 +152,10 @@
|
||||
<!-- testing -->
|
||||
<assertj.version>3.10.0</assertj.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<awaitility.version>4.0.2</awaitility.version>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
<maven-jar-plugin.version>3.2.0</maven-jar-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.multireleaseapp;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class App {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(App.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
logger.info(String.format("Running on %s", new DefaultVersion().version()));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.multireleaseapp;
|
||||
|
||||
public class DefaultVersion implements Version {
|
||||
|
||||
@Override
|
||||
public String version() {
|
||||
return System.getProperty("java.version");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.multireleaseapp;
|
||||
|
||||
interface Version {
|
||||
public String version();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.multireleaseapp;
|
||||
|
||||
public class DefaultVersion implements Version {
|
||||
|
||||
@Override
|
||||
public String version() {
|
||||
return Runtime.version().toString();
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ import static org.junit.Assert.assertThat;
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
public class HttpClientTest {
|
||||
public class HttpClientIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
|
||||
@@ -55,7 +55,7 @@ public class HttpClientTest {
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
|
||||
assertThat(response.body(), containsString("https://stackoverflow.com/"));
|
||||
assertThat(response.body(), containsString(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -22,7 +22,7 @@ import static org.junit.Assert.assertThat;
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
public class HttpRequestTest {
|
||||
public class HttpRequestIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
|
||||
@@ -18,7 +18,7 @@ import static org.junit.Assert.assertThat;
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
public class HttpResponseTest {
|
||||
public class HttpResponseIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
|
||||
@@ -5,10 +5,12 @@ import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.SubmissionPublisher;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.assertj.core.api.Java6Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
|
||||
public class ReactiveStreamsTest {
|
||||
public class ReactiveStreamsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenPublisher_whenSubscribeToIt_thenShouldConsumeAllElements() throws InterruptedException {
|
||||
@@ -25,7 +27,7 @@ public class ReactiveStreamsTest {
|
||||
|
||||
//then
|
||||
|
||||
await().atMost(1000, TimeUnit.MILLISECONDS).until(
|
||||
await().atMost(1000, TimeUnit.MILLISECONDS).untilAsserted(
|
||||
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(items)
|
||||
);
|
||||
}
|
||||
@@ -46,7 +48,7 @@ public class ReactiveStreamsTest {
|
||||
publisher.close();
|
||||
|
||||
//then
|
||||
await().atMost(1000, TimeUnit.MILLISECONDS).until(
|
||||
await().atMost(1000, TimeUnit.MILLISECONDS).untilAsserted(
|
||||
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(expectedResult)
|
||||
);
|
||||
}
|
||||
@@ -66,7 +68,7 @@ public class ReactiveStreamsTest {
|
||||
publisher.close();
|
||||
|
||||
//then
|
||||
await().atMost(1000, TimeUnit.MILLISECONDS).until(
|
||||
await().atMost(1000, TimeUnit.MILLISECONDS).untilAsserted(
|
||||
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(expected)
|
||||
);
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
package com.baeldung.java9.varhandles;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.VarHandle;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class VariableHandlesTest {
|
||||
|
||||
public int publicTestVariable = 1;
|
||||
private int privateTestVariable = 1;
|
||||
public int variableToSet = 1;
|
||||
public int variableToCompareAndSet = 1;
|
||||
public int variableToGetAndAdd = 0;
|
||||
public byte variableToBitwiseOr = 0;
|
||||
|
||||
@Test
|
||||
public void whenVariableHandleForPublicVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle publicIntHandle = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesTest.class)
|
||||
.findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class);
|
||||
|
||||
assertThat(publicIntHandle.coordinateTypes().size() == 1);
|
||||
assertThat(publicIntHandle.coordinateTypes().get(0) == VariableHandles.class);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVariableHandleForPrivateVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle privateIntHandle = MethodHandles
|
||||
.privateLookupIn(VariableHandlesTest.class, MethodHandles.lookup())
|
||||
.findVarHandle(VariableHandlesTest.class, "privateTestVariable", int.class);
|
||||
|
||||
assertThat(privateIntHandle.coordinateTypes().size() == 1);
|
||||
assertThat(privateIntHandle.coordinateTypes().get(0) == VariableHandlesTest.class);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVariableHandleForArrayVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle arrayVarHandle = MethodHandles
|
||||
.arrayElementVarHandle(int[].class);
|
||||
|
||||
assertThat(arrayVarHandle.coordinateTypes().size() == 2);
|
||||
assertThat(arrayVarHandle.coordinateTypes().get(0) == int[].class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenGetIsInvoked_ThenValueOfVariableIsReturned() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle publicIntHandle = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesTest.class)
|
||||
.findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class);
|
||||
|
||||
assertThat((int) publicIntHandle.get(this) == 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle publicIntHandle = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesTest.class)
|
||||
.findVarHandle(VariableHandlesTest.class, "variableToSet", int.class);
|
||||
publicIntHandle.set(this, 15);
|
||||
|
||||
assertThat((int) publicIntHandle.get(this) == 15);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenCompareAndSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle publicIntHandle = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesTest.class)
|
||||
.findVarHandle(VariableHandlesTest.class, "variableToCompareAndSet", int.class);
|
||||
publicIntHandle.compareAndSet(this, 1, 100);
|
||||
|
||||
assertThat((int) publicIntHandle.get(this) == 100);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenGetAndAddIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle publicIntHandle = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesTest.class)
|
||||
.findVarHandle(VariableHandlesTest.class, "variableToGetAndAdd", int.class);
|
||||
int before = (int) publicIntHandle.getAndAdd(this, 200);
|
||||
|
||||
assertThat(before == 0);
|
||||
assertThat((int) publicIntHandle.get(this) == 200);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenGetAndBitwiseOrIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle publicIntHandle = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesTest.class)
|
||||
.findVarHandle(VariableHandlesTest.class, "variableToBitwiseOr", byte.class);
|
||||
byte before = (byte) publicIntHandle.getAndBitwiseOr(this, (byte) 127);
|
||||
|
||||
assertThat(before == 0);
|
||||
assertThat(variableToBitwiseOr == 127);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.baeldung.java9.varhandles;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.VarHandle;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class VariableHandlesUnitTest {
|
||||
|
||||
public int publicTestVariable = 1;
|
||||
private int privateTestVariable = 1;
|
||||
public int variableToSet = 1;
|
||||
public int variableToCompareAndSet = 1;
|
||||
public int variableToGetAndAdd = 0;
|
||||
public byte variableToBitwiseOr = 0;
|
||||
|
||||
@Test
|
||||
public void whenVariableHandleForPublicVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle PUBLIC_TEST_VARIABLE = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesUnitTest.class)
|
||||
.findVarHandle(VariableHandlesUnitTest.class, "publicTestVariable", int.class);
|
||||
|
||||
assertEquals(1, PUBLIC_TEST_VARIABLE.coordinateTypes().size());
|
||||
assertEquals(VariableHandlesUnitTest.class, PUBLIC_TEST_VARIABLE.coordinateTypes().get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVariableHandleForPrivateVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle PRIVATE_TEST_VARIABLE = MethodHandles
|
||||
.privateLookupIn(VariableHandlesUnitTest.class, MethodHandles.lookup())
|
||||
.findVarHandle(VariableHandlesUnitTest.class, "privateTestVariable", int.class);
|
||||
|
||||
assertEquals(1, PRIVATE_TEST_VARIABLE.coordinateTypes().size());
|
||||
assertEquals(VariableHandlesUnitTest.class, PRIVATE_TEST_VARIABLE.coordinateTypes().get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVariableHandleForArrayVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle arrayVarHandle = MethodHandles
|
||||
.arrayElementVarHandle(int[].class);
|
||||
|
||||
assertEquals(2, arrayVarHandle.coordinateTypes().size());
|
||||
assertEquals(int[].class, arrayVarHandle.coordinateTypes().get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenGetIsInvoked_ThenValueOfVariableIsReturned() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle PUBLIC_TEST_VARIABLE = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesUnitTest.class)
|
||||
.findVarHandle(VariableHandlesUnitTest.class, "publicTestVariable", int.class);
|
||||
|
||||
assertEquals(1, (int) PUBLIC_TEST_VARIABLE.get(this));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle VARIABLE_TO_SET = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesUnitTest.class)
|
||||
.findVarHandle(VariableHandlesUnitTest.class, "variableToSet", int.class);
|
||||
|
||||
VARIABLE_TO_SET.set(this, 15);
|
||||
assertEquals(15, (int) VARIABLE_TO_SET.get(this));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenCompareAndSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle VARIABLE_TO_COMPARE_AND_SET = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesUnitTest.class)
|
||||
.findVarHandle(VariableHandlesUnitTest.class, "variableToCompareAndSet", int.class);
|
||||
|
||||
VARIABLE_TO_COMPARE_AND_SET.compareAndSet(this, 1, 100);
|
||||
assertEquals(100, (int) VARIABLE_TO_COMPARE_AND_SET.get(this));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenGetAndAddIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle VARIABLE_TO_GET_AND_ADD = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesUnitTest.class)
|
||||
.findVarHandle(VariableHandlesUnitTest.class, "variableToGetAndAdd", int.class);
|
||||
|
||||
int before = (int) VARIABLE_TO_GET_AND_ADD.getAndAdd(this, 200);
|
||||
|
||||
assertEquals(0, before);
|
||||
assertEquals(200, (int) VARIABLE_TO_GET_AND_ADD.get(this));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenGetAndBitwiseOrIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle VARIABLE_TO_BITWISE_OR = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesUnitTest.class)
|
||||
.findVarHandle(VariableHandlesUnitTest.class, "variableToBitwiseOr", byte.class);
|
||||
byte before = (byte) VARIABLE_TO_BITWISE_OR.getAndBitwiseOr(this, (byte) 127);
|
||||
|
||||
assertEquals(0, before);
|
||||
assertEquals(127, (byte) VARIABLE_TO_BITWISE_OR.get(this));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.arrays;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class JavaArraysToStringUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenInstanceOfArray_whenTryingToConvertToString_thenNameOfClassIsShown() {
|
||||
Object[] arrayOfObjects = { "John", 2, true };
|
||||
assertTrue(arrayOfObjects.toString().startsWith("[Ljava.lang.Object;"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInstanceOfArray_whenUsingArraysToStringToConvert_thenValueOfObjectsAreShown() {
|
||||
Object[] arrayOfObjects = { "John", 2, true };
|
||||
assertEquals(Arrays.toString(arrayOfObjects), "[John, 2, true]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInstanceOfDeepArray_whenUsingArraysDeepToStringToConvert_thenValueOfInnerObjectsAreShown() {
|
||||
Object[] innerArray = { "We", "Are", "Inside" };
|
||||
Object[] arrayOfObjects = { "John", 2, innerArray };
|
||||
assertEquals(Arrays.deepToString(arrayOfObjects), "[John, 2, [We, Are, Inside]]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInstanceOfDeepArray_whenUsingStreamsToConvert_thenValueOfObjectsAreShown() {
|
||||
Object[] arrayOfObjects = { "John", 2, true };
|
||||
List<String> listOfString = Stream.of(arrayOfObjects)
|
||||
.map(Object::toString)
|
||||
.collect(Collectors.toList());
|
||||
assertEquals(listOfString.toString(), "[John, 2, true]");
|
||||
}
|
||||
}
|
||||
@@ -9,3 +9,4 @@
|
||||
- [Differences Between Collection.clear() and Collection.removeAll()](https://www.baeldung.com/java-collection-clear-vs-removeall)
|
||||
- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
|
||||
- [Fail-Safe Iterator vs Fail-Fast Iterator](https://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
|
||||
- [Quick Guide to the Java Stack](https://www.baeldung.com/java-stack)
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.baeldung.abaproblem;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class Account {
|
||||
|
||||
private AtomicInteger balance;
|
||||
private AtomicInteger transactionCount;
|
||||
private ThreadLocal<Integer> currentThreadCASFailureCount;
|
||||
|
||||
public Account() {
|
||||
this.balance = new AtomicInteger(0);
|
||||
this.transactionCount = new AtomicInteger(0);
|
||||
this.currentThreadCASFailureCount = new ThreadLocal<>();
|
||||
this.currentThreadCASFailureCount.set(0);
|
||||
}
|
||||
|
||||
public int getBalance() {
|
||||
return balance.get();
|
||||
}
|
||||
|
||||
public int getTransactionCount() {
|
||||
return transactionCount.get();
|
||||
}
|
||||
|
||||
public int getCurrentThreadCASFailureCount() {
|
||||
return currentThreadCASFailureCount.get();
|
||||
}
|
||||
|
||||
public boolean withdraw(int amount) {
|
||||
int current = getBalance();
|
||||
maybeWait();
|
||||
boolean result = balance.compareAndSet(current, current - amount);
|
||||
if (result) {
|
||||
transactionCount.incrementAndGet();
|
||||
} else {
|
||||
int currentCASFailureCount = currentThreadCASFailureCount.get();
|
||||
currentThreadCASFailureCount.set(currentCASFailureCount + 1);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private void maybeWait() {
|
||||
if ("thread1".equals(Thread.currentThread().getName())) {
|
||||
try {
|
||||
TimeUnit.SECONDS.sleep(2);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean deposit(int amount) {
|
||||
int current = balance.get();
|
||||
boolean result = balance.compareAndSet(current, current + amount);
|
||||
if (result) {
|
||||
transactionCount.incrementAndGet();
|
||||
} else {
|
||||
int currentCASFailureCount = currentThreadCASFailureCount.get();
|
||||
currentThreadCASFailureCount.set(currentCASFailureCount + 1);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -9,13 +9,11 @@ public class StampedAccount {
|
||||
private AtomicStampedReference<Integer> account = new AtomicStampedReference<>(0, 0);
|
||||
|
||||
public int getBalance() {
|
||||
return this.account.get(new int[1]);
|
||||
return account.getReference();
|
||||
}
|
||||
|
||||
public int getStamp() {
|
||||
int[] stamps = new int[1];
|
||||
this.account.get(stamps);
|
||||
return stamps[0];
|
||||
return account.getStamp();
|
||||
}
|
||||
|
||||
public boolean deposit(int funds) {
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.baeldung.abaproblem;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class AccountUnitTest {
|
||||
|
||||
private Account account;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
account = new Account();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void zeroBalanceInitializationTest() {
|
||||
assertEquals(0, account.getBalance());
|
||||
assertEquals(0, account.getTransactionCount());
|
||||
assertEquals(0, account.getCurrentThreadCASFailureCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void depositTest() {
|
||||
final int moneyToDeposit = 50;
|
||||
|
||||
assertTrue(account.deposit(moneyToDeposit));
|
||||
|
||||
assertEquals(moneyToDeposit, account.getBalance());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void withdrawTest() throws InterruptedException {
|
||||
final int defaultBalance = 50;
|
||||
final int moneyToWithdraw = 20;
|
||||
|
||||
account.deposit(defaultBalance);
|
||||
|
||||
assertTrue(account.withdraw(moneyToWithdraw));
|
||||
|
||||
assertEquals(defaultBalance - moneyToWithdraw, account.getBalance());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void abaProblemTest() throws InterruptedException {
|
||||
final int defaultBalance = 50;
|
||||
|
||||
final int amountToWithdrawByThread1 = 20;
|
||||
final int amountToWithdrawByThread2 = 10;
|
||||
final int amountToDepositByThread2 = 10;
|
||||
|
||||
assertEquals(0, account.getTransactionCount());
|
||||
assertEquals(0, account.getCurrentThreadCASFailureCount());
|
||||
account.deposit(defaultBalance);
|
||||
assertEquals(1, account.getTransactionCount());
|
||||
|
||||
Thread thread1 = new Thread(() -> {
|
||||
|
||||
// this will take longer due to the name of the thread
|
||||
assertTrue(account.withdraw(amountToWithdrawByThread1));
|
||||
|
||||
// thread 1 fails to capture ABA problem
|
||||
assertNotEquals(1, account.getCurrentThreadCASFailureCount());
|
||||
|
||||
}, "thread1");
|
||||
|
||||
Thread thread2 = new Thread(() -> {
|
||||
|
||||
assertTrue(account.deposit(amountToDepositByThread2));
|
||||
assertEquals(defaultBalance + amountToDepositByThread2, account.getBalance());
|
||||
|
||||
// this will be fast due to the name of the thread
|
||||
assertTrue(account.withdraw(amountToWithdrawByThread2));
|
||||
|
||||
// thread 1 didn't finish yet, so the original value will be in place for it
|
||||
assertEquals(defaultBalance, account.getBalance());
|
||||
|
||||
assertEquals(0, account.getCurrentThreadCASFailureCount());
|
||||
}, "thread2");
|
||||
|
||||
thread1.start();
|
||||
thread2.start();
|
||||
thread1.join();
|
||||
thread2.join();
|
||||
|
||||
// compareAndSet operation succeeds for thread 1
|
||||
assertEquals(defaultBalance - amountToWithdrawByThread1, account.getBalance());
|
||||
|
||||
//but there are other transactions
|
||||
assertNotEquals(2, account.getTransactionCount());
|
||||
|
||||
// thread 2 did two modifications as well
|
||||
assertEquals(4, account.getTransactionCount());
|
||||
}
|
||||
}
|
||||
5
core-java-modules/core-java-console/README.md
Normal file
5
core-java-modules/core-java-console/README.md
Normal file
@@ -0,0 +1,5 @@
|
||||
#Core Java Console
|
||||
|
||||
[Read and Write User Input in Java](http://www.baeldung.com/java-console-input-output)
|
||||
[Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf)
|
||||
[ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
|
||||
142
core-java-modules/core-java-console/pom.xml
Normal file
142
core-java-modules/core-java-console/pom.xml
Normal file
@@ -0,0 +1,142 @@
|
||||
<?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-console</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-console</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>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-console</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
<configuration>
|
||||
<executable>java</executable>
|
||||
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
|
||||
<arguments>
|
||||
<argument>-Xmx300m</argument>
|
||||
<argument>-XX:+UseParallelGC</argument>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>${maven-javadoc-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${source.version}</source>
|
||||
<target>${target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>integration</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
<includes>
|
||||
<include>**/*IntegrationTest.java</include>
|
||||
<include>**/*IntTest.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<test.mime>json</test.mime>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>run-benchmarks</id>
|
||||
<!-- <phase>integration-test</phase> -->
|
||||
<phase>none</phase>
|
||||
<goals>
|
||||
<goal>exec</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classpathScope>test</classpathScope>
|
||||
<executable>java</executable>
|
||||
<arguments>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<argument>org.openjdk.jmh.Main</argument>
|
||||
<argument>.*</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
||||
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
|
||||
<source.version>1.8</source.version>
|
||||
<target.version>1.8</target.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -1,10 +1,9 @@
|
||||
package com.baeldung.asciiart;
|
||||
|
||||
import java.awt.Font;
|
||||
|
||||
import com.baeldung.asciiart.AsciiArt.Settings;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.asciiart.AsciiArt.Settings;
|
||||
import java.awt.*;
|
||||
|
||||
public class AsciiArtIntegrationTest {
|
||||
|
||||
@@ -16,5 +15,4 @@ public class AsciiArtIntegrationTest {
|
||||
|
||||
asciiArt.drawString(text, "*", settings);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -8,4 +8,5 @@ This module contains articles about date operations in Java.
|
||||
- [Converting Java Date to OffsetDateTime](https://www.baeldung.com/java-convert-date-to-offsetdatetime)
|
||||
- [How to Set the JVM Time Zone](https://www.baeldung.com/java-jvm-time-zone)
|
||||
- [How to determine day of week by passing specific date in Java?](https://www.baeldung.com/java-get-day-of-week)
|
||||
- [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-date-operations-1)
|
||||
|
||||
@@ -5,4 +5,5 @@ This module contains articles about core Java input/output(IO) conversions.
|
||||
### Relevant Articles:
|
||||
- [Java InputStream to String](https://www.baeldung.com/convert-input-stream-to-string)
|
||||
- [Java – Write an InputStream to a File](https://www.baeldung.com/convert-input-stream-to-a-file)
|
||||
- [Converting a BufferedReader to a JSONObject](https://www.baeldung.com/java-bufferedreader-to-jsonobject)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-io-conversions)
|
||||
|
||||
@@ -21,6 +21,11 @@
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.json</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
<version>20200518</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.bufferedreadertojsonobject;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import org.json.JSONObject;
|
||||
import org.json.JSONTokener;
|
||||
import org.junit.Test;
|
||||
|
||||
public class JavaBufferedReaderToJSONObjectUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenValidJson_whenUsingBufferedReader_thenJSONTokenerConverts() {
|
||||
byte[] b = "{ \"name\" : \"John\", \"age\" : 18 }".getBytes(StandardCharsets.UTF_8);
|
||||
InputStream is = new ByteArrayInputStream(b);
|
||||
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
|
||||
JSONTokener tokener = new JSONTokener(bufferedReader);
|
||||
JSONObject json = new JSONObject(tokener);
|
||||
|
||||
assertNotNull(json);
|
||||
assertEquals("John", json.get("name"));
|
||||
assertEquals(18, json.get("age"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidJson_whenUsingString_thenJSONObjectConverts() throws IOException {
|
||||
byte[] b = "{ \"name\" : \"John\", \"age\" : 18 }".getBytes(StandardCharsets.UTF_8);
|
||||
InputStream is = new ByteArrayInputStream(b);
|
||||
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String line;
|
||||
while ((line = bufferedReader.readLine()) != null) {
|
||||
sb.append(line);
|
||||
}
|
||||
JSONObject json = new JSONObject(sb.toString());
|
||||
|
||||
assertNotNull(json);
|
||||
assertEquals("John", json.get("name"));
|
||||
assertEquals(18, json.get("age"));
|
||||
}
|
||||
}
|
||||
@@ -12,3 +12,4 @@ This module contains articles about working with the Java Virtual Machine (JVM).
|
||||
- [Guide to System.gc()](https://www.baeldung.com/java-system-gc)
|
||||
- [Runtime.getRuntime().halt() vs System.exit() in Java](https://www.baeldung.com/java-runtime-halt-vs-system-exit)
|
||||
- [Adding Shutdown Hooks for JVM Applications](https://www.baeldung.com/jvm-shutdown-hooks)
|
||||
- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object)
|
||||
|
||||
@@ -51,14 +51,31 @@
|
||||
<scope>system</scope>
|
||||
<systemPath>${java.home}/../lib/tools.jar</systemPath>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.ow2.asm</groupId>
|
||||
<artifactId>asm</artifactId>
|
||||
<version>${asm.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.ow2.asm</groupId>
|
||||
<artifactId>asm-util</artifactId>
|
||||
<version>${asm.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.bcel</groupId>
|
||||
<artifactId>bcel</artifactId>
|
||||
<version>${bcel.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<!-- instrumentation -->
|
||||
<javaassist.version>3.21.0-GA</javaassist.version>
|
||||
<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>
|
||||
<asm.version>8.0.1</asm.version>
|
||||
<bcel.version>6.5.0</bcel.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.bytecode;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
|
||||
import org.apache.bcel.Repository;
|
||||
import org.apache.bcel.classfile.JavaClass;
|
||||
import org.junit.Test;
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.util.TraceClassVisitor;
|
||||
import javassist.ClassPool;
|
||||
import javassist.NotFoundException;
|
||||
import javassist.bytecode.ClassFile;
|
||||
|
||||
public class ViewBytecodeUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingASM_thenReadBytecode() throws IOException {
|
||||
ClassReader reader = new ClassReader("java.lang.Object");
|
||||
StringWriter sw = new StringWriter();
|
||||
TraceClassVisitor tcv = new TraceClassVisitor(new PrintWriter(sw));
|
||||
reader.accept(tcv, 0);
|
||||
|
||||
assertTrue(sw.toString().contains("public class java/lang/Object"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingBCEL_thenReadBytecode() throws ClassNotFoundException {
|
||||
JavaClass objectClazz = Repository.lookupClass("java.lang.Object");
|
||||
|
||||
assertEquals(objectClazz.getClassName(), "java.lang.Object");
|
||||
assertEquals(objectClazz.getMethods().length, 14);
|
||||
assertTrue(objectClazz.toString().contains("public class java.lang.Object"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingJavassist_thenReadBytecode() throws NotFoundException {
|
||||
ClassPool cp = ClassPool.getDefault();
|
||||
ClassFile cf = cp.get("java.lang.Object").getClassFile();
|
||||
|
||||
assertEquals(cf.getName(), "java.lang.Object");
|
||||
assertEquals(cf.getMethods().size(), 14);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.error.oom;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ExecutorServiceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAnExecutorService_WhenMoreTasksSubmitted_ThenAdditionalTasksWait() {
|
||||
|
||||
// Given
|
||||
int noOfThreads = 5;
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(noOfThreads);
|
||||
|
||||
Runnable runnableTask = () -> {
|
||||
try {
|
||||
TimeUnit.HOURS.sleep(1);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
};
|
||||
|
||||
// When
|
||||
IntStream.rangeClosed(1, 10)
|
||||
.forEach(i -> executorService.submit(runnableTask));
|
||||
|
||||
// Then
|
||||
assertThat(((ThreadPoolExecutor) executorService).getQueue()
|
||||
.size(), is(equalTo(5)));
|
||||
}
|
||||
}
|
||||
@@ -7,3 +7,6 @@ This module contains articles about types in Java
|
||||
- [Guide to the this Java Keyword](https://www.baeldung.com/java-this)
|
||||
- [Nested Classes in Java](https://www.baeldung.com/java-nested-classes)
|
||||
- [Marker Interfaces in Java](https://www.baeldung.com/java-marker-interfaces)
|
||||
- [Iterating Over Enum Values in Java](https://www.baeldung.com/java-enum-iteration)
|
||||
- [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values)
|
||||
- [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums)
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.varargs;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class HeapPollutionUnitTest {
|
||||
|
||||
@Test(expected = ClassCastException.class)
|
||||
public void givenGenericVararg_whenUsedUnsafe_shouldThrowClassCastException() {
|
||||
String one = firstOfFirst(Arrays.asList("one", "two"), Collections.emptyList());
|
||||
|
||||
assertEquals("one", one);
|
||||
}
|
||||
|
||||
@Test(expected = ClassCastException.class)
|
||||
public void givenGenericVararg_whenRefEscapes_mayCauseSubtleBugs() {
|
||||
String[] args = returnAsIs("One", "Two");
|
||||
}
|
||||
|
||||
private static String firstOfFirst(List<String>... strings) {
|
||||
List<Integer> ints = Collections.singletonList(42);
|
||||
Object[] objects = strings;
|
||||
objects[0] = ints;
|
||||
|
||||
return strings[0].get(0);
|
||||
}
|
||||
|
||||
private static <T> T[] toArray(T... arguments) {
|
||||
return arguments;
|
||||
}
|
||||
|
||||
private static <T> T[] returnAsIs(T a, T b) {
|
||||
return toArray(a, b);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ This module contains articles about core features in the Java language
|
||||
|
||||
### Relevant Articles:
|
||||
- [Generate equals() and hashCode() with Eclipse](https://www.baeldung.com/java-eclipse-equals-and-hashcode)
|
||||
- [Iterating Over Enum Values in Java](https://www.baeldung.com/java-enum-iteration)
|
||||
- [Comparator and Comparable in Java](https://www.baeldung.com/java-comparator-comparable)
|
||||
- [Recursion In Java](https://www.baeldung.com/java-recursion)
|
||||
- [A Guide to the finalize Method in Java](https://www.baeldung.com/java-finalize)
|
||||
@@ -12,8 +11,6 @@ This module contains articles about core features in the Java language
|
||||
- [Using Java Assertions](https://www.baeldung.com/java-assert)
|
||||
- [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic)
|
||||
- [Retrieving a Class Name in Java](https://www.baeldung.com/java-class-name)
|
||||
- [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values)
|
||||
- [The Java continue and break Keywords](https://www.baeldung.com/java-continue-and-break)
|
||||
- [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums)
|
||||
- [Infinite Loops in Java](https://www.baeldung.com/infinite-loops-java)
|
||||
- [[More --> ]](/core-java-modules/core-java-lang-2)
|
||||
|
||||
@@ -8,3 +8,5 @@
|
||||
- [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params)
|
||||
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
|
||||
- [What Causes java.lang.reflect.InvocationTargetException?](https://www.baeldung.com/java-lang-reflect-invocationtargetexception)
|
||||
- [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null)
|
||||
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)
|
||||
|
||||
@@ -200,7 +200,7 @@ public class ReflectionUnitTest {
|
||||
@Test
|
||||
public void givenClassField_whenSetsAndGetsValue_thenCorrect() throws Exception {
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||
final Bird bird = (Bird) birdClass.newInstance();
|
||||
final Bird bird = (Bird) birdClass.getConstructor().newInstance();
|
||||
final Field field = birdClass.getDeclaredField("walks");
|
||||
field.setAccessible(true);
|
||||
|
||||
@@ -266,7 +266,7 @@ public class ReflectionUnitTest {
|
||||
@Test
|
||||
public void givenMethod_whenInvokes_thenCorrect() throws Exception {
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||
final Bird bird = (Bird) birdClass.newInstance();
|
||||
final Bird bird = (Bird) birdClass.getConstructor().newInstance();
|
||||
final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
|
||||
final Method walksMethod = birdClass.getDeclaredMethod("walks");
|
||||
final boolean walks = (boolean) walksMethod.invoke(bird);
|
||||
|
||||
@@ -26,6 +26,17 @@ public class StringToIntOrIntegerUnitTest {
|
||||
assertThat(result).isEqualTo(new Integer(42));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenCallingValueOf_shouldCacheSomeValues() {
|
||||
for (int i = -128; i <= 127; i++) {
|
||||
String value = i + "";
|
||||
Integer first = Integer.valueOf(value);
|
||||
Integer second = Integer.valueOf(value);
|
||||
|
||||
assertThat(first).isSameAs(second);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenCallingIntegerConstructor_shouldConvertToInt() {
|
||||
String givenString = "42";
|
||||
|
||||
@@ -12,4 +12,6 @@ This module contains articles about string operations.
|
||||
- [L-Trim and R-Trim Alternatives in Java](https://www.baeldung.com/java-trim-alternatives)
|
||||
- [Java Convert PDF to Base64](https://www.baeldung.com/java-convert-pdf-to-base64)
|
||||
- [Encode a String to UTF-8 in Java](https://www.baeldung.com/java-string-encode-utf-8)
|
||||
- [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding)
|
||||
- [Convert Hex to ASCII in Java](https://www.baeldung.com/java-convert-hex-to-ascii) #remove additional readme file
|
||||
- More articles: [[<-- prev]](../core-java-string-operations)
|
||||
|
||||
Binary file not shown.
@@ -6,3 +6,4 @@ This module contains articles about the measurement of time in Java.
|
||||
- [Guide to the Java Clock Class](http://www.baeldung.com/java-clock)
|
||||
- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time)
|
||||
- [Overriding System Time for Testing in Java](https://www.baeldung.com/java-override-system-time)
|
||||
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.clock;
|
||||
package com.baeldung.clock;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
@@ -1,35 +1,13 @@
|
||||
## Core Java Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
|
||||
- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
|
||||
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
|
||||
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
|
||||
- [JVM Log Forging](http://www.baeldung.com/jvm-log-forging)
|
||||
- [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null)
|
||||
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)
|
||||
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
|
||||
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
|
||||
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
|
||||
- [Quick Guide to the Java Stack](https://www.baeldung.com/java-stack)
|
||||
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
|
||||
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
|
||||
- [Guide to the Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
|
||||
- [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
|
||||
- [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid)
|
||||
- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
|
||||
- [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler)
|
||||
- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object)
|
||||
- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions)
|
||||
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
|
||||
- [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources)
|
||||
- [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding)
|
||||
- [Graphs in Java](https://www.baeldung.com/java-graphs)
|
||||
- [Read and Write User Input in Java](http://www.baeldung.com/java-console-input-output)
|
||||
- [Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf)
|
||||
- [Retrieve Fields from a Java Class Using Reflection](https://www.baeldung.com/java-reflection-class-fields)
|
||||
- [Using Curl in Java](https://www.baeldung.com/java-curl)
|
||||
- [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year)
|
||||
- [Making a JSON POST Request With HttpURLConnection](https://www.baeldung.com/httpurlconnection-post)
|
||||
- [How to Find an Exception’s Root Cause in Java](https://www.baeldung.com/java-exception-root-cause)
|
||||
- [Convert Hex to ASCII in Java](https://www.baeldung.com/java-convert-hex-to-ascii)
|
||||
[Getting Started with Java Properties](http://www.baeldung.com/java-properties)
|
||||
[Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
|
||||
[Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
|
||||
[Guide to UUID in Java](http://www.baeldung.com/java-uuid)
|
||||
[Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
|
||||
[Introduction to Javadoc](http://www.baeldung.com/javadoc)
|
||||
[Guide to the Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
|
||||
[What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid)
|
||||
[A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
|
||||
[Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
package com.baeldung.graph;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class Graph {
|
||||
private Map<Vertex, List<Vertex>> adjVertices;
|
||||
|
||||
Graph() {
|
||||
this.adjVertices = new HashMap<Vertex, List<Vertex>>();
|
||||
}
|
||||
|
||||
void addVertex(String label) {
|
||||
adjVertices.putIfAbsent(new Vertex(label), new ArrayList<>());
|
||||
}
|
||||
|
||||
void removeVertex(String label) {
|
||||
Vertex v = new Vertex(label);
|
||||
adjVertices.values().stream().forEach(e -> e.remove(v));
|
||||
adjVertices.remove(new Vertex(label));
|
||||
}
|
||||
|
||||
void addEdge(String label1, String label2) {
|
||||
Vertex v1 = new Vertex(label1);
|
||||
Vertex v2 = new Vertex(label2);
|
||||
adjVertices.get(v1).add(v2);
|
||||
adjVertices.get(v2).add(v1);
|
||||
}
|
||||
|
||||
void removeEdge(String label1, String label2) {
|
||||
Vertex v1 = new Vertex(label1);
|
||||
Vertex v2 = new Vertex(label2);
|
||||
List<Vertex> eV1 = adjVertices.get(v1);
|
||||
List<Vertex> eV2 = adjVertices.get(v2);
|
||||
if (eV1 != null)
|
||||
eV1.remove(v2);
|
||||
if (eV2 != null)
|
||||
eV2.remove(v1);
|
||||
}
|
||||
|
||||
List<Vertex> getAdjVertices(String label) {
|
||||
return adjVertices.get(new Vertex(label));
|
||||
}
|
||||
|
||||
String printGraph() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for(Vertex v : adjVertices.keySet()) {
|
||||
sb.append(v);
|
||||
sb.append(adjVertices.get(v));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
class Vertex {
|
||||
String label;
|
||||
Vertex(String label) {
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + getOuterType().hashCode();
|
||||
result = prime * result + ((label == null) ? 0 : label.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Vertex other = (Vertex) obj;
|
||||
if (!getOuterType().equals(other.getOuterType()))
|
||||
return false;
|
||||
if (label == null) {
|
||||
if (other.label != null)
|
||||
return false;
|
||||
} else if (!label.equals(other.label))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return label;
|
||||
}
|
||||
|
||||
|
||||
private Graph getOuterType() {
|
||||
return Graph.this;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.baeldung.graph;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
import java.util.Set;
|
||||
import java.util.Stack;
|
||||
|
||||
import com.baeldung.graph.Graph.Vertex;
|
||||
|
||||
public class GraphTraversal {
|
||||
static Set<String> depthFirstTraversal(Graph graph, String root) {
|
||||
Set<String> visited = new LinkedHashSet<String>();
|
||||
Stack<String> stack = new Stack<String>();
|
||||
stack.push(root);
|
||||
while (!stack.isEmpty()) {
|
||||
String vertex = stack.pop();
|
||||
if (!visited.contains(vertex)) {
|
||||
visited.add(vertex);
|
||||
for (Vertex v : graph.getAdjVertices(vertex)) {
|
||||
stack.push(v.label);
|
||||
}
|
||||
}
|
||||
}
|
||||
return visited;
|
||||
}
|
||||
|
||||
static Set<String> breadthFirstTraversal(Graph graph, String root) {
|
||||
Set<String> visited = new LinkedHashSet<String>();
|
||||
Queue<String> queue = new LinkedList<String>();
|
||||
queue.add(root);
|
||||
visited.add(root);
|
||||
while (!queue.isEmpty()) {
|
||||
String vertex = queue.poll();
|
||||
for (Vertex v : graph.getAdjVertices(vertex)) {
|
||||
if (!visited.contains(v.label)) {
|
||||
visited.add(v.label);
|
||||
queue.add(v.label);
|
||||
}
|
||||
}
|
||||
}
|
||||
return visited;
|
||||
}
|
||||
}
|
||||
@@ -3,30 +3,57 @@ package com.baeldung.uuid;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
|
||||
public class UUIDGenerator {
|
||||
|
||||
/**
|
||||
* These are predefined UUID for name spaces
|
||||
*/
|
||||
private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
|
||||
private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
|
||||
private static final String NAMESPACE_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8";
|
||||
private static final String NAMESPACE_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8";
|
||||
|
||||
private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
System.out.println("Type 3 : " + generateType3UUID(NAMESPACE_DNS, "google.com"));
|
||||
System.out.println("Type 4 : " + generateType4UUID());
|
||||
System.out.println("Type 5 : " + generateType5UUID(NAMESPACE_URL, "google.com"));
|
||||
System.out.println("Unique key : " + generateUniqueKeysWithUUIDAndMessageDigest());
|
||||
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
/**
|
||||
* Type 1 UUID Generation
|
||||
*/
|
||||
public static UUID generateType1UUID() {
|
||||
|
||||
long most64SigBits = get64MostSignificantBitsForVersion1();
|
||||
long least64SigBits = get64LeastSignificantBitsForVersion1();
|
||||
|
||||
return new UUID(most64SigBits, least64SigBits);
|
||||
}
|
||||
|
||||
private static long get64LeastSignificantBitsForVersion1() {
|
||||
Random random = new Random();
|
||||
long random63BitLong = random.nextLong() & 0x3FFFFFFFFFFFFFFFL;
|
||||
long variant3BitFlag = 0x8000000000000000L;
|
||||
return random63BitLong + variant3BitFlag;
|
||||
}
|
||||
|
||||
private static long get64MostSignificantBitsForVersion1() {
|
||||
LocalDateTime start = LocalDateTime.of(1582, 10, 15, 0, 0, 0);
|
||||
Duration duration = Duration.between(start, LocalDateTime.now());
|
||||
long seconds = duration.getSeconds();
|
||||
long nanos = duration.getNano();
|
||||
long timeForUuidIn100Nanos = seconds * 10000000 + nanos * 100;
|
||||
long least12SignificatBitOfTime = (timeForUuidIn100Nanos & 0x000000000000FFFFL) >> 4;
|
||||
long version = 1 << 12;
|
||||
return (timeForUuidIn100Nanos & 0xFFFFFFFFFFFF0000L) + version + least12SignificatBitOfTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Type 3 UUID Generation
|
||||
*
|
||||
* @throws UnsupportedEncodingException
|
||||
*/
|
||||
public static UUID generateType3UUID(String namespace, String name) throws UnsupportedEncodingException {
|
||||
|
||||
byte[] nameSpaceBytes = bytesFromUUID(namespace);
|
||||
byte[] nameBytes = name.getBytes("UTF-8");
|
||||
byte[] result = joinBytes(nameSpaceBytes, nameBytes);
|
||||
|
||||
return UUID.nameUUIDFromBytes(result);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -37,28 +64,18 @@ public class UUIDGenerator {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Type 3 UUID Generation
|
||||
*
|
||||
* @throws UnsupportedEncodingException
|
||||
*/
|
||||
public static UUID generateType3UUID(String namespace, String name) throws UnsupportedEncodingException {
|
||||
String source = namespace + name;
|
||||
byte[] bytes = source.getBytes("UTF-8");
|
||||
UUID uuid = UUID.nameUUIDFromBytes(bytes);
|
||||
return uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Type 5 UUID Generation
|
||||
*
|
||||
* @throws UnsupportedEncodingException
|
||||
*
|
||||
* @throws UnsupportedEncodingException
|
||||
*/
|
||||
public static UUID generateType5UUID(String namespace, String name) throws UnsupportedEncodingException {
|
||||
String source = namespace + name;
|
||||
byte[] bytes = source.getBytes("UTF-8");
|
||||
UUID uuid = type5UUIDFromBytes(bytes);
|
||||
return uuid;
|
||||
|
||||
byte[] nameSpaceBytes = bytesFromUUID(namespace);
|
||||
byte[] nameBytes = name.getBytes("UTF-8");
|
||||
byte[] result = joinBytes(nameSpaceBytes, nameBytes);
|
||||
|
||||
return type5UUIDFromBytes(result);
|
||||
}
|
||||
|
||||
public static UUID type5UUIDFromBytes(byte[] name) {
|
||||
@@ -91,20 +108,20 @@ public class UUIDGenerator {
|
||||
|
||||
/**
|
||||
* Unique Keys Generation Using Message Digest and Type 4 UUID
|
||||
*
|
||||
* @throws NoSuchAlgorithmException
|
||||
* @throws UnsupportedEncodingException
|
||||
*
|
||||
* @throws NoSuchAlgorithmException
|
||||
* @throws UnsupportedEncodingException
|
||||
*/
|
||||
public static String generateUniqueKeysWithUUIDAndMessageDigest() throws NoSuchAlgorithmException, UnsupportedEncodingException {
|
||||
MessageDigest salt = MessageDigest.getInstance("SHA-256");
|
||||
salt.update(UUID.randomUUID()
|
||||
.toString()
|
||||
.getBytes("UTF-8"));
|
||||
.toString()
|
||||
.getBytes("UTF-8"));
|
||||
String digest = bytesToHex(salt.digest());
|
||||
return digest;
|
||||
}
|
||||
|
||||
public static String bytesToHex(byte[] bytes) {
|
||||
private static String bytesToHex(byte[] bytes) {
|
||||
char[] hexChars = new char[bytes.length * 2];
|
||||
for (int j = 0; j < bytes.length; j++) {
|
||||
int v = bytes[j] & 0xFF;
|
||||
@@ -114,4 +131,37 @@ public class UUIDGenerator {
|
||||
return new String(hexChars);
|
||||
}
|
||||
|
||||
}
|
||||
private static byte[] bytesFromUUID(String uuidHexString) {
|
||||
String normalizedUUIDHexString = uuidHexString.replace("-","");
|
||||
|
||||
assert normalizedUUIDHexString.length() == 32;
|
||||
|
||||
byte[] bytes = new byte[16];
|
||||
for (int i = 0; i < 16; i++) {
|
||||
byte b = hexToByte(normalizedUUIDHexString.substring(i*2, i*2+2));
|
||||
bytes[i] = b;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
public static byte hexToByte(String hexString) {
|
||||
int firstDigit = Character.digit(hexString.charAt(0),16);
|
||||
int secondDigit = Character.digit(hexString.charAt(1),16);
|
||||
return (byte) ((firstDigit << 4) + secondDigit);
|
||||
}
|
||||
|
||||
public static byte[] joinBytes(byte[] byteArray1, byte[] byteArray2) {
|
||||
int finalLength = byteArray1.length + byteArray2.length;
|
||||
byte[] result = new byte[finalLength];
|
||||
|
||||
for(int i = 0; i < byteArray1.length; i++) {
|
||||
result[i] = byteArray1[i];
|
||||
}
|
||||
|
||||
for(int i = 0; i < byteArray2.length; i++) {
|
||||
result[byteArray1.length+i] = byteArray2[i];
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
var first = {
|
||||
name: "Whiskey",
|
||||
age: 5
|
||||
};
|
||||
|
||||
var second = {
|
||||
volume: 100
|
||||
};
|
||||
|
||||
Object.bindProperties(first, second);
|
||||
|
||||
print(first.volume);
|
||||
|
||||
second.volume = 1000;
|
||||
print(first.volume);
|
||||
@@ -1 +0,0 @@
|
||||
print(__FILE__, __LINE__, __DIR__);
|
||||
@@ -1,19 +0,0 @@
|
||||
var math = {
|
||||
increment: function (num) {
|
||||
return ++num;
|
||||
},
|
||||
|
||||
failFunc: function () {
|
||||
try {
|
||||
throw "BOOM";
|
||||
} catch (e if typeof e === 'string') {
|
||||
print("String thrown: " + e);
|
||||
}
|
||||
catch (e) {
|
||||
print("this shouldn't happen!");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
math;
|
||||
@@ -1,11 +0,0 @@
|
||||
var demo = {
|
||||
__noSuchProperty__: function (propName) {
|
||||
print("Accessed non-existing property: " + propName);
|
||||
},
|
||||
|
||||
__noSuchMethod__: function (methodName) {
|
||||
print("Invoked non-existing method: " + methodName);
|
||||
}
|
||||
};
|
||||
|
||||
demo;
|
||||
@@ -1 +0,0 @@
|
||||
function increment(num) ++num;
|
||||
@@ -1,2 +0,0 @@
|
||||
print(" hello world".trimLeft());
|
||||
print("hello world ".trimRight());
|
||||
@@ -1,9 +0,0 @@
|
||||
function arrays(arr) {
|
||||
|
||||
var javaIntArray = Java.to(arr, "int[]");
|
||||
print(javaIntArray[0]);
|
||||
print(javaIntArray[1]);
|
||||
print(javaIntArray[2]);
|
||||
}
|
||||
|
||||
arrays([100, "1654", true]);
|
||||
@@ -1,47 +0,0 @@
|
||||
package com.baeldung.graph;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GraphUnitTest {
|
||||
@Test
|
||||
public void givenAGraph_whenTraversingDepthFirst_thenExpectedResult() {
|
||||
Graph graph = createGraph();
|
||||
assertEquals("[Bob, Rob, Maria, Alice, Mark]",
|
||||
GraphTraversal.depthFirstTraversal(graph, "Bob").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAGraph_whenTraversingBreadthFirst_thenExpectedResult() {
|
||||
Graph graph = createGraph();
|
||||
assertEquals("[Bob, Alice, Rob, Mark, Maria]",
|
||||
GraphTraversal.breadthFirstTraversal(graph, "Bob").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAGraph_whenRemoveVertex_thenVertedNotFound() {
|
||||
Graph graph = createGraph();
|
||||
assertEquals("[Bob, Alice, Rob, Mark, Maria]",
|
||||
GraphTraversal.breadthFirstTraversal(graph, "Bob").toString());
|
||||
|
||||
graph.removeVertex("Maria");
|
||||
assertEquals("[Bob, Alice, Rob, Mark]",
|
||||
GraphTraversal.breadthFirstTraversal(graph, "Bob").toString());
|
||||
}
|
||||
|
||||
Graph createGraph() {
|
||||
Graph graph = new Graph();
|
||||
graph.addVertex("Bob");
|
||||
graph.addVertex("Alice");
|
||||
graph.addVertex("Mark");
|
||||
graph.addVertex("Rob");
|
||||
graph.addVertex("Maria");
|
||||
graph.addEdge("Bob", "Alice");
|
||||
graph.addEdge("Bob", "Rob");
|
||||
graph.addEdge("Alice", "Mark");
|
||||
graph.addEdge("Rob", "Mark");
|
||||
graph.addEdge("Alice", "Maria");
|
||||
graph.addEdge("Rob", "Maria");
|
||||
return graph;
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
package com.baeldung.scripting;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.script.Bindings;
|
||||
import javax.script.Invocable;
|
||||
import javax.script.ScriptEngine;
|
||||
import javax.script.ScriptEngineManager;
|
||||
import javax.script.ScriptException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class NashornUnitTest {
|
||||
|
||||
private ScriptEngine engine;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
engine = new ScriptEngineManager().getEngineByName("nashorn");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void trim() throws ScriptException {
|
||||
engine.eval(new InputStreamReader(NashornUnitTest.class.getResourceAsStream("/js/trim.js")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void locations() throws ScriptException {
|
||||
engine.eval(new InputStreamReader(NashornUnitTest.class.getResourceAsStream("/js/locations.js")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bindProperties() throws ScriptException {
|
||||
engine.eval(new InputStreamReader(NashornUnitTest.class.getResourceAsStream("/js/bind.js")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void magicMethods() throws ScriptException {
|
||||
engine.eval("var demo = load('classpath:js/no_such.js');" + "var tmp = demo.doesNotExist;" + "var none = demo.callNonExistingMethod()");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void typedArrays() throws ScriptException {
|
||||
engine.eval(new InputStreamReader(NashornUnitTest.class.getResourceAsStream("/js/typed_arrays.js")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void basicUsage() throws ScriptException {
|
||||
Object result = engine.eval("var greeting='hello world';" + "print(greeting);" + "greeting");
|
||||
|
||||
Assert.assertEquals("hello world", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void jsonObjectExample() throws ScriptException {
|
||||
Object obj = engine.eval("Java.asJSONCompatible({ number: 42, greet: 'hello', primes: [2,3,5,7,11,13] })");
|
||||
Map<String, Object> map = (Map<String, Object>) obj;
|
||||
|
||||
Assert.assertEquals("hello", map.get("greet"));
|
||||
Assert.assertTrue(List.class.isAssignableFrom(map.get("primes").getClass()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void tryCatchGuard() throws ScriptException {
|
||||
engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.failFunc();");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extensionsExamples() throws ScriptException {
|
||||
String script = "var list = [1, 2, 3, 4, 5];" + "var result = '';" + "for each (var i in list) {" + "result+=i+'-';" + "};" + "print(result);";
|
||||
engine.eval(script);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bindingsExamples() throws ScriptException {
|
||||
Bindings bindings = engine.createBindings();
|
||||
bindings.put("count", 3);
|
||||
bindings.put("name", "baeldung");
|
||||
|
||||
String script = "var greeting='Hello ';" + "for(var i=count;i>0;i--) { " + "greeting+=name + ' '" + "}" + "greeting";
|
||||
|
||||
Object bindingsResult = engine.eval(script, bindings);
|
||||
Assert.assertEquals("Hello baeldung baeldung baeldung ", bindingsResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void jvmBoundaryExamples() throws ScriptException, NoSuchMethodException {
|
||||
engine.eval("function composeGreeting(name) {" + "return 'Hello ' + name" + "}");
|
||||
|
||||
Invocable invocable = (Invocable) engine;
|
||||
|
||||
Object funcResult = invocable.invokeFunction("composeGreeting", "baeldung");
|
||||
Assert.assertEquals("Hello baeldung", funcResult);
|
||||
|
||||
Object map = engine.eval("var HashMap = Java.type('java.util.HashMap');" + "var map = new HashMap();" + "map.put('hello', 'world');" + "map");
|
||||
|
||||
Assert.assertTrue(Map.class.isAssignableFrom(map.getClass()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadExamples() throws ScriptException {
|
||||
Object loadResult = engine.eval("load('classpath:js/script.js');" + "increment(5)");
|
||||
|
||||
Assert.assertEquals(6, ((Double) loadResult).intValue());
|
||||
|
||||
Object math = engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.increment(5);");
|
||||
|
||||
Assert.assertEquals(6.0, math);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.uuid;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class UUIDGeneratorUnitTest {
|
||||
|
||||
private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
|
||||
private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
|
||||
|
||||
@Test
|
||||
public void version_1_UUID_is_generated_with_correct_length_version_and_variant() {
|
||||
|
||||
UUID uuid = UUIDGenerator.generateType1UUID();
|
||||
|
||||
assertEquals(36, uuid.toString().length());
|
||||
assertEquals(1, uuid.version());
|
||||
assertEquals(2, uuid.variant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void version_3_UUID_is_correctly_generated_for_domain_baeldung_com() throws UnsupportedEncodingException {
|
||||
|
||||
UUID uuid = UUIDGenerator.generateType3UUID(NAMESPACE_DNS, "baeldung.com");
|
||||
|
||||
assertEquals("23785b78-0132-3ac6-aff6-cfd5be162139", uuid.toString());
|
||||
assertEquals(3, uuid.version());
|
||||
assertEquals(2, uuid.variant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void version_3_UUID_is_correctly_generated_for_domain_d() throws UnsupportedEncodingException {
|
||||
|
||||
UUID uuid = UUIDGenerator.generateType3UUID(NAMESPACE_DNS, "d");
|
||||
|
||||
assertEquals("dbd41ecb-f466-33de-b309-1468addfc63b", uuid.toString());
|
||||
assertEquals(3, uuid.version());
|
||||
assertEquals(2, uuid.variant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void version_4_UUID_is_generated_with_correct_length_version_and_variant() {
|
||||
|
||||
UUID uuid = UUIDGenerator.generateType4UUID();
|
||||
|
||||
assertEquals(36, uuid.toString().length());
|
||||
assertEquals(4, uuid.version());
|
||||
assertEquals(2, uuid.variant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void version_5_UUID_is_correctly_generated_for_domain_baeldung_com() throws UnsupportedEncodingException {
|
||||
|
||||
UUID uuid = UUIDGenerator.generateType5UUID(NAMESPACE_URL, "baeldung.com");
|
||||
|
||||
assertEquals("aeff44a5-8a61-52b6-bcbe-c8e5bd7d0300", uuid.toString());
|
||||
assertEquals(5, uuid.version());
|
||||
assertEquals(2, uuid.variant());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user