Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Tarun Jain
2020-07-21 22:01:50 +05:30
503 changed files with 23318 additions and 711 deletions
@@ -1,12 +1,15 @@
package com.baeldung.modules.main;
import com.baeldung.modules.hello.HelloInterface;
import com.baeldung.modules.hello.HelloModules;
import java.util.ServiceLoader;
public class MainApp {
public static void main(String[] args) {
HelloModules.doSomething();
HelloModules module = new HelloModules();
module.sayHello();
Iterable<HelloInterface> services = ServiceLoader.load(HelloInterface.class);
HelloInterface service = services.iterator().next();
service.sayHello();
}
}
@@ -27,6 +27,11 @@
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
</dependencies>
<properties>
@@ -0,0 +1,47 @@
package com.baeldung.collections.iterators;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import com.google.common.primitives.Ints;
import org.apache.commons.lang3.ArrayUtils;
public class ConvertPrimitivesArrayToList {
public static void failConvert() {
int[] input = new int[]{1,2,3,4};
// List<Integer> inputAsList = Arrays.asList(input);
}
public static List<Integer> iterateConvert(int[] input) {
List<Integer> output = new ArrayList<Integer>();
for (int value : input) {
output.add(value);
}
return output;
}
public static List<Integer> streamConvert(int[] input) {
List<Integer> output = Arrays.stream(input).boxed().collect(Collectors.toList());
return output;
}
public static List<Integer> streamConvertIntStream(int[] input) {
List<Integer> output = IntStream.of(input).boxed().collect(Collectors.toList());
return output;
}
public static List<Integer> guavaConvert(int[] input) {
List<Integer> output = Ints.asList(input);
return output;
}
public static List<Integer> apacheCommonConvert(int[] input) {
Integer[] outputBoxed = ArrayUtils.toObject(input);
List<Integer> output = Arrays.asList(outputBoxed);
return output;
}
}
@@ -0,0 +1,38 @@
package com.baeldung.collections.iterators;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import com.google.common.primitives.Ints;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ConvertPrimitivesArrayToListUnitTest {
@Test
public void givenArrayWithPrimitives_whenIterativeConvert_thenArrayGetsConverted() {
assertEquals(Arrays.asList(1,2,3,4), ConvertPrimitivesArrayToList.iterateConvert(new int[]{1,2,3,4}));
}
@Test
public void givenArrayWithPrimitives_whenStreamConvert_thenArrayGetsConverted() {
assertEquals(Arrays.asList(1,2,3,4), ConvertPrimitivesArrayToList.streamConvert(new int[]{1,2,3,4}));
}
@Test
public void givenArrayWithPrimitives_whenIntStreamConvert_thenArrayGetsConverted() {
assertEquals(Arrays.asList(1,2,3,4), ConvertPrimitivesArrayToList.streamConvertIntStream(new int[]{1,2,3,4}));
}
@Test
public void givenArrayWithPrimitives_whenGuavaConvert_thenArrayGetsConverted() {
assertEquals(Arrays.asList(1,2,3,4), ConvertPrimitivesArrayToList.guavaConvert(new int[]{1,2,3,4}));
}
@Test
public void givenArrayWithPrimitives_whenApacheCommonConvert_thenArrayGetsConverted() {
assertEquals(Arrays.asList(1,2,3,4), ConvertPrimitivesArrayToList.apacheCommonConvert(new int[]{1,2,3,4}));
}
}
@@ -0,0 +1,10 @@
package com.baeldung.concurrent.localvariables;
public class LocalAndLambda {
public static void main(String... args) {
String text = "";
// Un-commenting the next line will break compilation, because text is no longer effectively final
// text = "675";
new Thread(() -> System.out.println(text)).start();
}
}
@@ -0,0 +1,20 @@
package com.baeldung.concurrent.localvariables;
import java.security.SecureRandom;
public class LocalVariables implements Runnable {
private int field;
public static void main(String... args) {
LocalVariables target = new LocalVariables();
new Thread(target).start();
new Thread(target).start();
}
@Override
public void run() {
field = new SecureRandom().nextInt();
int local = new SecureRandom().nextInt();
System.out.println(field + " - " + local);
}
}
@@ -1,3 +1,5 @@
### Relevant Articles:
- [Introduction to Lock Striping](https://www.baeldung.com/java-lock-stripping)
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
- [[<-- Prev]](/core-java-modules/core-java-concurrency-collections)
@@ -3,9 +3,16 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.concurrent.lock</groupId>
<artifactId>core-java-concurrency-collections-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-collections-2</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>
@@ -30,19 +37,6 @@
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<jmh.version>1.21</jmh.version>
@@ -19,7 +19,7 @@ import org.junit.FixMethodOrder;
import org.junit.Test;
@FixMethodOrder
public class TestConcurrentLinkedQueue {
public class ConcurrentLinkedQueueUnitTest {
@Test
public void givenThereIsExistingCollection_WhenAddedIntoQueue_ThenShouldContainElements() {
@@ -18,7 +18,7 @@ import org.junit.FixMethodOrder;
import org.junit.Test;
@FixMethodOrder
public class TestLinkedBlockingQueue {
public class LinkedBlockingQueueUnitTest {
@Test
public void givenThereIsExistingCollection_WhenAddedIntoQueue_ThenShouldContainElements() {
@@ -4,7 +4,11 @@ import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.util.concurrent.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TransferQueue;
import static junit.framework.TestCase.assertEquals;
@@ -10,7 +10,7 @@ This module contains articles about concurrent Java collections
- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool)
- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue)
- [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue)
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map)
- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist)
- [LinkedBlockingQueue vs ConcurrentLinkedQueue](https://www.baeldung.com/java-queue-linkedblocking-concurrentlinked)
- [[Next -->]](/core-java-modules/core-java-concurrency-collections-2)
@@ -33,7 +33,6 @@
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<commons.lang3.version>3.10</commons.lang3.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
+1 -1
View File
@@ -13,4 +13,4 @@ This module contains articles about core Java input and output (IO)
- [How to Copy a File with Java](https://www.baeldung.com/java-copy-file)
- [Create a Directory in Java](https://www.baeldung.com/java-create-directory)
- [Java IO vs NIO](https://www.baeldung.com/java-io-vs-nio)
- [[<-- Prev]](/core-java-modules/core-java-io)
- [[<-- Prev]](/core-java-modules/core-java-io)[[More -->]](/core-java-modules/core-java-io-3)
@@ -0,0 +1,7 @@
## Core Java IO
This module contains articles about core Java input and output (IO)
### Relevant Articles:
- [Java Create a File](https://www.baeldung.com/java-how-to-create-a-file)
- [[<-- Prev]](/core-java-modules/core-java-io-2)
+86
View File
@@ -0,0 +1,86 @@
<?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-io-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-io-3</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>
<!-- utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.tomakehurst/wiremock -->
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>${wiremock.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-io-3</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<assertj.version>3.6.1</assertj.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<wiremock.version>2.26.3</wiremock.version>
</properties>
</project>
@@ -0,0 +1,50 @@
package com.baeldung.createfile;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class CreateFileUnitTest {
private final String FILE_NAME = "src/test/resources/fileToCreate.txt";
@AfterEach
@BeforeEach
public void cleanUpFiles() {
File targetFile = new File(FILE_NAME);
targetFile.delete();
}
@Test
public void givenUsingNio_whenCreatingFile_thenCorrect() throws IOException {
Path newFilePath = Paths.get(FILE_NAME);
Files.createFile(newFilePath);
}
@Test
public void givenUsingFile_whenCreatingFile_thenCorrect() throws IOException {
File newFile = new File(FILE_NAME);
boolean success = newFile.createNewFile();
assertTrue(success);
}
@Test
public void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
com.google.common.io.Files.touch(new File(FILE_NAME));
}
@Test
public void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException {
FileUtils.touch(new File(FILE_NAME));
}
}
@@ -7,7 +7,6 @@ This module contains articles about core Java input/output(IO) APIs.
- [A Guide to the Java FileReader Class](https://www.baeldung.com/java-filereader)
- [The Java File Class](https://www.baeldung.com/java-io-file)
- [Java FileWriter](https://www.baeldung.com/java-filewriter)
- [Differences Between the Java WatchService API and the Apache Commons IO Monitor Library](https://www.baeldung.com/java-watchservice-vs-apache-commons-io-monitor-library)
- [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](https://www.baeldung.com/java-path)
- [Quick Use of FilenameFilter](https://www.baeldung.com/java-filename-filter)
- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
@@ -1,42 +0,0 @@
package com.baeldung.dirmonitoring;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
public class DirectoryMonitoringExample {
private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class);
private static final int POLL_INTERVAL = 500;
public static void main(String[] args) throws Exception {
FileAlterationObserver observer = new FileAlterationObserver(System.getProperty("user.home"));
FileAlterationMonitor monitor = new FileAlterationMonitor(POLL_INTERVAL);
FileAlterationListener listener = new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(File file) {
LOG.debug("File: " + file.getName() + " created");
}
@Override
public void onFileDelete(File file) {
LOG.debug("File: " + file.getName() + " deleted");
}
@Override
public void onFileChange(File file) {
LOG.debug("File: " + file.getName() + " changed");
}
};
observer.addListener(listener);
monitor.addObserver(observer);
monitor.start();
}
}
@@ -6,4 +6,6 @@ This module contains articles about core Java input/output(IO) conversions.
- [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)
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
- [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv)
- More articles: [[<-- prev]](/core-java-modules/core-java-io-conversions)
@@ -26,6 +26,12 @@
<artifactId>json</artifactId>
<version>${json.version}</version>
</dependency>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>${opencsv.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@@ -40,6 +46,7 @@
<properties>
<json.version>20200518</json.version>
<opencsv.version>4.1</opencsv.version>
</properties>
</project>
@@ -1,20 +1,11 @@
package com.baeldung.csv;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import com.opencsv.CSVReader;
import org.junit.Assert;
import org.junit.Test;
import com.opencsv.CSVReader;
import java.io.*;
import java.util.*;
public class ReadCSVInArrayUnitTest {
public static final String COMMA_DELIMITER = ",";
@@ -1,7 +1,9 @@
package com.baeldung.csv;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
@@ -10,10 +12,8 @@ import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class WriteCsvFileExampleUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(WriteCsvFileExampleUnitTest.class);
+1 -2
View File
@@ -8,10 +8,9 @@ This module contains articles about core Java input and output (IO)
- [Java Directory Size](https://www.baeldung.com/java-folder-size)
- [File Size in Java](https://www.baeldung.com/java-file-size)
- [Zipping and Unzipping in Java](https://www.baeldung.com/java-compress-and-uncompress)
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
- [How to Get the File Extension of a File in Java](https://www.baeldung.com/java-file-extension)
- [Getting a Files Mime Type in Java](https://www.baeldung.com/java-file-mime-type)
- [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv)
- [How to Avoid the Java FileNotFoundException When Loading Resources](https://www.baeldung.com/java-classpath-resource-cannot-be-opened)
- [Create a Directory in Java](https://www.baeldung.com/java-create-directory)
- [Java Rename or Move a File](https://www.baeldung.com/java-how-to-rename-or-move-a-file)
- [[More -->]](/core-java-modules/core-java-io-2)
-8
View File
@@ -29,12 +29,6 @@
<version>${hsqldb.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>${opencsv.version}</version>
<scope>test</scope>
</dependency>
<!-- Mime Type Resolution Libraries -->
<dependency>
<groupId>org.apache.tika</groupId>
@@ -142,8 +136,6 @@
</profiles>
<properties>
<!-- util -->
<opencsv.version>4.1</opencsv.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<!-- maven plugins -->
@@ -0,0 +1,64 @@
package com.baeldung.rename;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class RenameFileUnitTest {
private final String FILE_TO_MOVE = "src/test/resources/originalFileToMove.txt";
private final String TARGET_FILE = "src/test/resources/targetFileToMove.txt";
@BeforeEach
public void createFileToMove() throws IOException {
File fileToMove = new File(FILE_TO_MOVE);
fileToMove.createNewFile();
}
@AfterEach
public void cleanUpFiles() {
File targetFile = new File(TARGET_FILE);
targetFile.delete();
}
@Test
public void givenUsingNio_whenMovingFile_thenCorrect() throws IOException {
Path fileToMovePath = Paths.get(FILE_TO_MOVE);
Path targetPath = Paths.get(TARGET_FILE);
Files.move(fileToMovePath, targetPath);
}
@Test
public void givenUsingFileClass_whenMovingFile_thenCorrect() throws IOException {
File fileToMove = new File(FILE_TO_MOVE);
boolean isMoved = fileToMove.renameTo(new File(TARGET_FILE));
if (!isMoved) {
throw new FileSystemException(TARGET_FILE);
}
}
@Test
public void givenUsingGuava_whenMovingFile_thenCorrect()
throws IOException {
File fileToMove = new File(FILE_TO_MOVE);
File targetFile = new File(TARGET_FILE);
com.google.common.io.Files.move(fileToMove, targetFile);
}
@Test
public void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
FileUtils.moveFile(
FileUtils.getFile(FILE_TO_MOVE),
FileUtils.getFile(TARGET_FILE));
}
}
+7 -1
View File
@@ -2,4 +2,10 @@
This module contains articles about working with the Java Virtual Machine (JVM).
### Relevant Articles:
### Relevant Articles:
- [Memory Layout of Objects in Java](https://www.baeldung.com/java-memory-layout)
- [Measuring Object Sizes in the JVM](https://www.baeldung.com/jvm-measuring-object-sizes)
- [Adding Shutdown Hooks for JVM Applications](https://www.baeldung.com/jvm-shutdown-hooks)
- [boolean and boolean[] Memory Layout in the JVM](https://www.baeldung.com/jvm-boolean-memory-layout)
- More articles: [[<-- prev]](/core-java-modules/core-java-jvm)
@@ -0,0 +1,24 @@
package com.baeldung.memaddress;
import org.junit.Test;
import org.openjdk.jol.vm.VM;
public class MemoryAddressUnitTest {
@Test
public void printTheMemoryAddress() {
String answer = "42";
System.out.println("The memory address is " + VM.current().addressOf(answer));
}
@Test
public void identityHashCodeAndMemoryAddress() {
Object obj = new Object();
System.out.println("Memory address: " + VM.current().addressOf(obj));
System.out.println("hashCode: " + obj.hashCode());
System.out.println("hashCode: " + System.identityHashCode(obj));
System.out.println("toString: " + obj);
}
}
@@ -0,0 +1,10 @@
package com.baeldung.objectsize;
public class Course {
private String name;
public Course(String name) {
this.name = name;
}
}
@@ -0,0 +1,11 @@
package com.baeldung.objectsize;
public class InstrumentedSize {
public static void main(String[] args) {
String ds = "Data Structures";
Course course = new Course(ds);
System.out.println(ObjectSizeCalculator.sizeOf(course));
}
}
@@ -0,0 +1 @@
Premain-Class: com.baeldung.objectsize.ObjectSizeCalculator
@@ -0,0 +1,16 @@
package com.baeldung.objectsize;
import java.lang.instrument.Instrumentation;
public class ObjectSizeCalculator {
private static Instrumentation instrumentation;
public static void premain(String args, Instrumentation inst) {
instrumentation = inst;
}
public static long sizeOf(Object o) {
return instrumentation.getObjectSize(o);
}
}
@@ -0,0 +1,40 @@
package com.baeldung.objectsize;
import org.junit.Test;
import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.info.GraphLayout;
import org.openjdk.jol.vm.VM;
public class ObjectSizeUnitTest {
@Test
public void printingTheVMDetails() {
System.out.println(VM.current().details());
}
@Test
public void printingTheProfClassLayout() {
System.out.println(ClassLayout.parseClass(Professor.class).toPrintable());
}
@Test
public void printingTheCourseClassLayout() {
System.out.println(ClassLayout.parseClass(Course.class).toPrintable());
}
@Test
public void printingACourseInstanceLayout() {
String ds = "Data Structures";
Course course = new Course(ds);
System.out.println("The shallow size is :" + VM.current().sizeOf(course));
System.out.println(ClassLayout.parseInstance(course).toPrintable());
System.out.println(ClassLayout.parseInstance(ds).toPrintable());
System.out.println(ClassLayout.parseInstance(ds.toCharArray()).toPrintable());
System.out.println(GraphLayout.parseInstance(course).totalSize());
System.out.println(GraphLayout.parseInstance(course).toFootprint());
System.out.println(GraphLayout.parseInstance(course).toPrintable());
}
}
@@ -0,0 +1,24 @@
package com.baeldung.objectsize;
import java.time.LocalDate;
import java.util.List;
public class Professor {
private String name;
private boolean tenured;
private List<Course> courses;
private int level;
private LocalDate birthDay;
private double lastEvaluation;
public Professor(String name, boolean tenured, List<Course> courses,
int level, LocalDate birthDay, double lastEvaluation) {
this.name = name;
this.tenured = tenured;
this.courses = courses;
this.level = level;
this.birthDay = birthDay;
this.lastEvaluation = lastEvaluation;
}
}
+1 -2
View File
@@ -11,8 +11,7 @@ This module contains articles about working with the Java Virtual Machine (JVM).
- [A Guide to System.exit()](https://www.baeldung.com/java-system-exit)
- [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)
- [What Causes java.lang.OutOfMemoryError: unable to create new native thread](https://www.baeldung.com/java-outofmemoryerror-unable-to-create-new-native-thread)
- [View Bytecode of a Class File in Java](https://www.baeldung.com/java-class-view-bytecode)
- [boolean and boolean[] Memory Layout in the JVM](https://www.baeldung.com/jvm-boolean-memory-layout)
- More articles: [[next -->]](/core-java-modules/core-java-jvm-2)
+1 -1
View File
@@ -13,4 +13,4 @@ This module contains articles about core features in the Java language
- [Comparing Long Values in Java](https://www.baeldung.com/java-compare-long-values)
- [Comparing Objects in Java](https://www.baeldung.com/java-comparing-objects)
- [Casting int to Enum in Java](https://www.baeldung.com/java-cast-int-to-enum)
- [[<-- Prev]](/core-java-modules/core-java-lang)
[[ <-- Prev]](/core-java-modules/core-java-lang)[[Next --> ]](/core-java-modules/core-java-lang-3)
@@ -0,0 +1,5 @@
## Core Java Lang (Part 3)
This module contains articles about core features in the Java language
- [[<-- Prev]](/core-java-modules/core-java-lang-2)
@@ -0,0 +1,42 @@
<?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-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-lang-3</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.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-lang-3</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<assertj.version>3.12.2</assertj.version>
</properties>
</project>
@@ -0,0 +1,23 @@
package com.baeldung.staticvariables;
public class StaticVariableDemo {
public static int i;
public static int j = 20;
public static int z;
static {
z = 30;
a = 40;
}
public static int a = 50;
public static final int b = 100;
public StaticVariableDemo() {
}
static class Nested {
public static String nestedClassStaticVariable = "test";
}
}
@@ -0,0 +1,113 @@
package com.baeldung.staticvariables;
import static org.assertj.core.api.Assertions.assertThat;
import java.lang.reflect.Field;
import org.junit.jupiter.api.Test;
public class StaticVariableUnitTest {
@Test
public void initializeStaticVariable_checkAssignedValues() {
try {
Class<?> staticVariableDemo = this.getClass()
.getClassLoader()
.loadClass("com.baeldung.staticvariables.StaticVariableDemo");
Field field1 = staticVariableDemo.getField("i");
assertThat(field1.getInt(staticVariableDemo)).isEqualTo(0);
Field field2 = staticVariableDemo.getField("j");
assertThat(field2.getInt(staticVariableDemo)).isEqualTo(20);
} catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@Test
public void initializeStaticVariable_checkStaticBlock() {
try {
Class<?> staticVariableDemo = this.getClass()
.getClassLoader()
.loadClass("com.baeldung.staticvariables.StaticVariableDemo");
Field field1 = staticVariableDemo.getField("z");
assertThat(field1.getInt(staticVariableDemo)).isEqualTo(30);
Field field2 = staticVariableDemo.getField("a");
assertThat(field2.getInt(staticVariableDemo)).isEqualTo(50);
} catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@Test
public void initializeStaticVariable_checkFinalValues() {
try {
Class<?> staticVariableDemo = this.getClass()
.getClassLoader()
.loadClass("com.baeldung.staticvariables.StaticVariableDemo");
Field field1 = staticVariableDemo.getField("b");
assertThat(field1.getInt(staticVariableDemo)).isEqualTo(100);
} catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@Test
public void initializeStaticVariable_checkInnerClassValues() {
try {
Class<?> staticVariableDemo = this.getClass()
.getClassLoader()
.loadClass("com.baeldung.staticvariables.StaticVariableDemo");
Class<?>[] nestedClasses = staticVariableDemo.getClasses();
for (Class<?> nestedClass : nestedClasses) {
if (nestedClass.getName()
.equals("Nested")) {
Field field1 = nestedClass.getField("nestedClassStaticVariable");
assertThat(field1.get(nestedClass)).isEqualTo("test");
}
}
} catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,30 @@
package com.baeldung.stringtoboolean;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class StringToBooleanUnitTest {
@Test
public void givenStringTrue_whenUsingParseBoolean_thenTrue() {
assertThat(Boolean.parseBoolean("true")).isTrue();
}
@Test
public void givenStringTrue_whenUsingValueOf_thenTrue() {
assertThat(Boolean.valueOf("true")).isTrue();
}
@Test
public void givenStringTrue_whenUsingGetBoolean_thenFalse() {
assertThat(Boolean.getBoolean("true")).isFalse();
}
@Test
public void givenSystemProperty_whenUsingGetBoolean_thenTrue() {
System.setProperty("CODING_IS_FUN", "true");
assertThat(Boolean.getBoolean("CODING_IS_FUN")).isTrue();
}
}
+2 -1
View File
@@ -13,4 +13,5 @@ This module contains articles about core features in the Java language
- [Retrieving a Class Name in Java](https://www.baeldung.com/java-class-name)
- [The Java continue and break Keywords](https://www.baeldung.com/java-continue-and-break)
- [Infinite Loops in Java](https://www.baeldung.com/infinite-loops-java)
- [[More --> ]](/core-java-modules/core-java-lang-2)
[[Next --> ]](/core-java-modules/core-java-lang-2)
@@ -0,0 +1,44 @@
<?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-reflection-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-reflection-2</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-reflection-2</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${source.version}</source>
<target>${target.version}</target>
<compilerArgument>-parameters</compilerArgument>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven-compiler-plugin.version>3.8.0</maven-compiler-plugin.version>
<source.version>1.8</source.version>
<target.version>1.8</target.version>
</properties>
</project>
@@ -0,0 +1,87 @@
package com.baeldung.reflection.access.privatefields;
public class Person {
private String name = "John";
private byte age = 30;
private short uidNumber = 5555;
private int pinCode = 452002;
private long contactNumber = 123456789L;
private float height = 6.1242f;
private double weight = 75.2564;
private char gender = 'M';
private boolean active = true;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte getAge() {
return age;
}
public void setAge(byte age) {
this.age = age;
}
public short getUidNumber() {
return uidNumber;
}
public void setUidNumber(short uidNumber) {
this.uidNumber = uidNumber;
}
public int getPinCode() {
return pinCode;
}
public void setPinCode(int pinCode) {
this.pinCode = pinCode;
}
public long getContactNumber() {
return contactNumber;
}
public void setContactNumber(long contactNumber) {
this.contactNumber = contactNumber;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
}
@@ -0,0 +1,168 @@
package com.baeldung.reflection.access.privatefields;
import java.lang.reflect.Field;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class AccessPrivateFieldsUnitTest {
@Test
public void whenGetIntegerFields_thenSuccess() throws Exception {
Person person = new Person();
Field ageField = person.getClass()
.getDeclaredField("age");
ageField.setAccessible(true);
byte age = ageField.getByte(person);
Assertions.assertEquals(30, age);
Field uidNumberField = person.getClass()
.getDeclaredField("uidNumber");
uidNumberField.setAccessible(true);
short uidNumber = uidNumberField.getShort(person);
Assertions.assertEquals(5555, uidNumber);
Field pinCodeField = person.getClass()
.getDeclaredField("pinCode");
pinCodeField.setAccessible(true);
int pinCode = pinCodeField.getInt(person);
Assertions.assertEquals(452002, pinCode);
Field contactNumberField = person.getClass()
.getDeclaredField("contactNumber");
contactNumberField.setAccessible(true);
long contactNumber = contactNumberField.getLong(person);
Assertions.assertEquals(123456789L, contactNumber);
}
@Test
public void whenDoAutoboxing_thenSuccess() throws Exception {
Person person = new Person();
Field pinCodeField = person.getClass()
.getDeclaredField("pinCode");
pinCodeField.setAccessible(true);
Integer pinCode = pinCodeField.getInt(person);
Assertions.assertEquals(452002, pinCode);
}
@Test
public void whenDoWidening_thenSuccess() throws Exception {
Person person = new Person();
Field pinCodeField = person.getClass()
.getDeclaredField("pinCode");
pinCodeField.setAccessible(true);
Long pinCode = pinCodeField.getLong(person);
Assertions.assertEquals(452002L, pinCode);
}
@Test
public void whenGetFloatingTypeFields_thenSuccess() throws Exception {
Person person = new Person();
Field heightField = person.getClass()
.getDeclaredField("height");
heightField.setAccessible(true);
float height = heightField.getFloat(person);
Assertions.assertEquals(6.1242f, height);
Field weightField = person.getClass()
.getDeclaredField("weight");
weightField.setAccessible(true);
double weight = weightField.getDouble(person);
Assertions.assertEquals(75.2564, weight);
}
@Test
public void whenGetCharacterFields_thenSuccess() throws Exception {
Person person = new Person();
Field genderField = person.getClass()
.getDeclaredField("gender");
genderField.setAccessible(true);
char gender = genderField.getChar(person);
Assertions.assertEquals('M', gender);
}
@Test
public void whenGetBooleanFields_thenSuccess() throws Exception {
Person person = new Person();
Field activeField = person.getClass()
.getDeclaredField("active");
activeField.setAccessible(true);
boolean active = activeField.getBoolean(person);
Assertions.assertTrue(active);
}
@Test
public void whenGetObjectFields_thenSuccess() throws Exception {
Person person = new Person();
Field nameField = person.getClass()
.getDeclaredField("name");
nameField.setAccessible(true);
String name = (String) nameField.get(person);
Assertions.assertEquals("John", name);
}
@Test
public void givenInt_whenGetStringField_thenIllegalArgumentException() throws Exception {
Person person = new Person();
Field nameField = person.getClass()
.getDeclaredField("name");
nameField.setAccessible(true);
Assertions.assertThrows(IllegalArgumentException.class, () -> nameField.getInt(person));
}
@Test
public void givenInt_whenGetLongField_thenIllegalArgumentException() throws Exception {
Person person = new Person();
Field contactNumberField = person.getClass()
.getDeclaredField("contactNumber");
contactNumberField.setAccessible(true);
Assertions.assertThrows(IllegalArgumentException.class, () -> contactNumberField.getInt(person));
}
@Test
public void whenFieldNotSetAccessible_thenIllegalAccessException() throws Exception {
Person person = new Person();
Field nameField = person.getClass()
.getDeclaredField("name");
Assertions.assertThrows(IllegalAccessException.class, () -> nameField.get(person));
}
@Test
public void whenAccessingWrongProperty_thenNoSuchFieldException() throws Exception {
Person person = new Person();
Assertions.assertThrows(NoSuchFieldException.class, () -> person.getClass()
.getDeclaredField("firstName"));
}
@Test
public void whenAccessingNullProperty_thenNullPointerException() throws Exception {
Person person = new Person();
Assertions.assertThrows(NullPointerException.class, () -> person.getClass()
.getDeclaredField(null));
}
}
@@ -0,0 +1,48 @@
package com.baeldung.pem;
import org.apache.commons.codec.binary.Base64;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class JavaSecurityPemUtils {
public static RSAPrivateKey readPKCS8PrivateKey(File file) throws GeneralSecurityException, IOException {
String key = new String(Files.readAllBytes(file.toPath()), Charset.defaultCharset());
String privateKeyPEM = key
.replace("-----BEGIN PRIVATE KEY-----", "")
.replaceAll(System.lineSeparator(), "")
.replace("-----END PRIVATE KEY-----", "");
byte[] encoded = Base64.decodeBase64(privateKeyPEM);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
}
public static RSAPublicKey readX509PublicKey(File file) throws GeneralSecurityException, IOException {
String key = new String(Files.readAllBytes(file.toPath()), Charset.defaultCharset());
String publicKeyPEM = key
.replace("-----BEGIN PUBLIC KEY-----", "")
.replaceAll(System.lineSeparator(), "")
.replace("-----END PUBLIC KEY-----", "");
byte[] encoded = Base64.decodeBase64(publicKeyPEM);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encoded);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
}
}
@@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCyO0YiTxLEP44S
IGk/b9MlQAXS6nC4oYyTrAfxHCi/zxW/MmtWbY0K2JxOTkVSD5QbmvwkCutXi0k9
EdDK+orAXg2KSy686O/cfIh/iho6FmNPyEOd7UF+/5wWpknrUaTQyMA2H9Pmr2/E
RH/tN1Q0cqmhFX41WUo3lsRT81DkVCNVeJx+zDGHpjp+XY8gWpPYJ+MP4WQE9TWJ
P2rIlgcDfwhG/A21yK0WAJ5nB0Y+jGI8+HVYdjxXGlRUG//YmxS2sH+sAhsapmjE
Aha+KMk972jVNjdWU7OT0BJnUB5q286Kv6INUnk6kqYufNzjpCAY9SyMjKjpKN71
3Gka2gZBAgMBAAECggEAFlPam12wiik0EQ1CYhIOL3JvyFZaPKbwR2ebrxbJ/A1j
OgqE69TZgGxWWHDxui/9a9/kildb2CG40Q+0SllMnICrzZFRj5TWx5ZKOz//vRsk
4c/CuLwKInC/Cw9V30bhEM61VZJzJ0j/BWVXaU4vHEro+ScKIoDHDWOzwJiQn6m9
C+Ti5lFpax3hx8ZrgPqmBCFYNvErrWkOr7mCYl0jS+E22c68yn8+LjdlF1LWUa6N
zutk3MPj5UwEyR0h7EZReCeGkPTMQNyOBhDcmAtlEno4fjtZzUDHRjh8/QpG1Mz/
alavvrkjswc1DmRUOdgiYu+Waxan5noBhxEAvd/hyQKBgQDjYJD0n+m0tUrpNtX0
+mdzHstClHrpx5oNxs4sIBjCoCwEXaSpeY8+JxCdnZ6n29mLZLq/wPXxZ3EJcOSZ
PYUvZJfV/IUvoLPFbtT3ILzDTcAAeHj2GAOpzYP8J1JSFsc78ZjKMF1XeNjXcq8T
XNXoWfY7N/fShoycVeG42JJCFwKBgQDIqvHL0QfJ8r6yM8Efj7Zq6Wa4C9okORes
8UVWfBoO6UOWvpK+D9IjnaEisJcnEalwNi8/eKudR9hfvmzATV+t3YJIgktto3TT
BWLsEyniNU4vSTl7GPBrV2xabWogbChlt7TXUfw6YogaBKm43snYXBbJFc+NcpQH
ONB5igppZwKBgGDyYHvc3wGsttb/CXTde1RLUfD+a/XXpCixlmCcAtKhBoOKBdY4
vUmL0HrTpLz/cR8NAM8XkAWwzDJxTxbDc1EEu/SCKatoAp5wph8Ed1dyhCXvN+v9
yzoQJXFStrfHfIVjenji7DmKjjI2dM11rMLX8LPJJkI+Gh/iQk7VEG9bAoGAH/aS
sztleTZwR6RUw7k5fkgVM4W3xoNNkR+RQthbsjpXqMBMUXflqgSmsQbd3LxEd/o5
hmurMk9KWN3VJsBsWB5rbS9L4nfh2OcHvcDDsCN7g66vODtduEthl/nLqMRxnton
NRD7EzW0pihN/IOINS1d98PAnrA8gfX7xxBE3ksCgYBvoljHGjvy3bPJ++vDGKJK
y6JuEeRVzgdPXEb60uU+BR7kdh+MMsZLmgfFTgza3R+/xeZcC/cuOPsbzeooRQi/
9NpKwSCXjVNk9nglUWBoPRh4uYqrArWn+HoR7MI/BxeRJm5e1+ii8P19Y9joX5s0
Q3OLn8GeH56ClJmNiWDhsA==
-----END PRIVATE KEY-----
@@ -0,0 +1,9 @@
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsjtGIk8SxD+OEiBpP2/T
JUAF0upwuKGMk6wH8Rwov88VvzJrVm2NCticTk5FUg+UG5r8JArrV4tJPRHQyvqK
wF4NiksuvOjv3HyIf4oaOhZjT8hDne1Bfv+cFqZJ61Gk0MjANh/T5q9vxER/7TdU
NHKpoRV+NVlKN5bEU/NQ5FQjVXicfswxh6Y6fl2PIFqT2CfjD+FkBPU1iT9qyJYH
A38IRvwNtcitFgCeZwdGPoxiPPh1WHY8VxpUVBv/2JsUtrB/rAIbGqZoxAIWvijJ
Pe9o1TY3VlOzk9ASZ1AeatvOir+iDVJ5OpKmLnzc46QgGPUsjIyo6Sje9dxpGtoG
QQIDAQAB
-----END PUBLIC KEY-----
@@ -0,0 +1,33 @@
package com.baeldung.pem;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class JavaSecurityPemUtilsUnitTest {
@Test
public void whenReadPublicKeyFromPEMFile_thenSuccess() throws Exception {
File pemFile = new File(JavaSecurityPemUtilsUnitTest.class.getResource("/pem/public-key.pem").getFile());
RSAPublicKey publicKey = JavaSecurityPemUtils.readX509PublicKey(pemFile);
assertEquals("X.509", publicKey.getFormat());
assertEquals("RSA", publicKey.getAlgorithm());
}
@Test
public void whenReadPrivateKeyFromPEMFile_thenSuccess() throws Exception {
File pemFile = new File(JavaSecurityPemUtilsUnitTest.class.getResource("/pem/private-key-pkcs8.pem").getFile());
RSAPrivateKey privateKey = JavaSecurityPemUtils.readPKCS8PrivateKey(pemFile);
assertEquals("PKCS#8", privateKey.getFormat());
assertEquals("RSA", privateKey.getAlgorithm());
}
}
@@ -9,7 +9,6 @@ This module contains articles about the Stream API in Java.
- [Iterable to Stream in Java](https://www.baeldung.com/java-iterable-to-stream)
- [How to Iterate Over a Stream With Indices](https://www.baeldung.com/java-stream-indices)
- [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering)
- [Introduction to Protonpack](https://www.baeldung.com/java-protonpack)
- [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda)
- [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count)
- [Summing Numbers with Java Streams](https://www.baeldung.com/java-stream-sum)
@@ -1,202 +0,0 @@
package com.baeldung.protonpack;
import com.codepoetics.protonpack.Indexed;
import com.codepoetics.protonpack.StreamUtils;
import com.codepoetics.protonpack.collectors.CollectorUtils;
import com.codepoetics.protonpack.collectors.NonUniqueValueException;
import com.codepoetics.protonpack.selectors.Selectors;
import org.junit.Test;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static java.util.Arrays.stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
public class ProtonpackUnitTest {
@Test
public void whenTakeWhile_thenTakenWhile() {
Stream<Integer> streamOfInt = Stream.iterate(1, i -> i + 1);
List<Integer> result = StreamUtils.takeWhile(streamOfInt, i -> i < 5).collect(Collectors.toList());
assertThat(result).contains(1, 2, 3, 4);
}
@Test
public void whenTakeUntil_thenTakenUntil() {
Stream<Integer> streamOfInt = Stream.iterate(1, i -> i + 1);
List<Integer> result = StreamUtils.takeUntil(streamOfInt, i -> i > 50).collect(Collectors.toList());
assertThat(result).contains(10, 20, 30, 40);
}
@Test
public void givenMultipleStream_whenZipped_thenZipped() {
String[] clubs = {"Juventus", "Barcelona", "Liverpool", "PSG"};
String[] players = {"Ronaldo", "Messi", "Salah"};
Set<String> zippedFrom2Sources = StreamUtils
.zip(stream(clubs), stream(players), (club, player) -> club + " " + player)
.collect(Collectors.toSet());
assertThat(zippedFrom2Sources).contains("Juventus Ronaldo", "Barcelona Messi", "Liverpool Salah");
String[] leagues = {"Serie A", "La Liga", "Premier League"};
Set<String> zippedFrom3Sources = StreamUtils.zip(stream(clubs), stream(players), stream(leagues),
(club, player, league) -> club + " " + player + " " + league).collect(Collectors.toSet());
assertThat(zippedFrom3Sources).contains("Juventus Ronaldo Serie A", "Barcelona Messi La Liga",
"Liverpool Salah Premier League");
}
@Test
public void whenZippedWithIndex_thenZippedWithIndex() {
Stream<String> streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool");
Set<Indexed<String>> zipsWithIndex = StreamUtils.zipWithIndex(streamOfClubs).collect(Collectors.toSet());
assertThat(zipsWithIndex).contains(Indexed.index(0, "Juventus"), Indexed.index(1, "Barcelona"),
Indexed.index(2, "Liverpool"));
}
@Test
public void givenMultipleStream_whenMerged_thenMerged() {
Stream<String> streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool", "PSG");
Stream<String> streamOfPlayers = Stream.of("Ronaldo", "Messi", "Salah");
Stream<String> streamOfLeagues = Stream.of("Serie A", "La Liga", "Premier League");
Set<String> merged = StreamUtils.merge(() -> "", (valOne, valTwo) -> valOne + " " + valTwo, streamOfClubs,
streamOfPlayers, streamOfLeagues).collect(Collectors.toSet());
assertThat(merged)
.contains(" Juventus Ronaldo Serie A", " Barcelona Messi La Liga", " Liverpool Salah Premier League",
" PSG");
}
@Test
public void givenMultipleStream_whenMergedToList_thenMergedToList() {
Stream<String> streamOfClubs = Stream.of("Juventus", "Barcelona", "PSG");
Stream<String> streamOfPlayers = Stream.of("Ronaldo", "Messi");
List<List<String>> mergedListOfList = StreamUtils.mergeToList(streamOfClubs, streamOfPlayers)
.collect(Collectors.toList());
assertThat(mergedListOfList.get(0)).isInstanceOf(List.class);
assertThat(mergedListOfList.get(0)).containsExactly("Juventus", "Ronaldo");
assertThat(mergedListOfList.get(1)).containsExactly("Barcelona", "Messi");
assertThat(mergedListOfList.get(2)).containsExactly("PSG");
}
@Test
public void givenMultipleStream_whenInterleaved_thenInterleaved() {
Stream<String> streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool");
Stream<String> streamOfPlayers = Stream.of("Ronaldo", "Messi");
Stream<String> streamOfLeagues = Stream.of("Serie A", "La Liga");
List<String> interleavedList = StreamUtils
.interleave(Selectors.roundRobin(), streamOfClubs, streamOfPlayers, streamOfLeagues)
.collect(Collectors.toList());
assertThat(interleavedList)
.hasSize(7)
.containsExactly("Juventus", "Ronaldo", "Serie A", "Barcelona", "Messi", "La Liga", "Liverpool");
}
@Test
public void whenSkippedUntil_thenSkippedUntil() {
Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
List<Integer> skippedUntilGreaterThan5 = StreamUtils.skipUntil(stream(numbers), i -> i > 5)
.collect(Collectors.toList());
assertThat(skippedUntilGreaterThan5).containsExactly(6, 7, 8, 9, 10);
List<Integer> skippedUntilLessThanEquals5 = StreamUtils.skipUntil(stream(numbers), i -> i <= 5)
.collect(Collectors.toList());
assertThat(skippedUntilLessThanEquals5).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
@Test
public void whenSkippedWhile_thenSkippedWhile() {
Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
List<Integer> skippedWhileLessThanEquals5 = StreamUtils.skipWhile(stream(numbers), i -> i <= 5)
.collect(Collectors.toList());
assertThat(skippedWhileLessThanEquals5).containsExactly(6, 7, 8, 9, 10);
List<Integer> skippedWhileGreaterThan5 = StreamUtils.skipWhile(stream(numbers), i -> i > 5)
.collect(Collectors.toList());
assertThat(skippedWhileGreaterThan5).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
@Test
public void givenFibonacciGenerator_whenUnfolded_thenUnfolded() {
Stream<Integer> unfolded = StreamUtils.unfold(2, i -> (i < 100) ? Optional.of(i * i) : Optional.empty());
assertThat(unfolded.collect(Collectors.toList())).containsExactly(2, 4, 16, 256);
}
@Test
public void whenWindowed_thenWindowed() {
Integer[] numbers = {1, 2, 3, 4, 5, 6, 7};
List<List<Integer>> windowedWithSkip1 = StreamUtils.windowed(stream(numbers), 3, 1)
.collect(Collectors.toList());
assertThat(windowedWithSkip1)
.containsExactly(asList(1, 2, 3), asList(2, 3, 4), asList(3, 4, 5), asList(4, 5, 6),
asList(5, 6, 7));
List<List<Integer>> windowedWithSkip2 = StreamUtils.windowed(stream(numbers), 3, 2)
.collect(Collectors.toList());
assertThat(windowedWithSkip2).containsExactly(asList(1, 2, 3), asList(3, 4, 5), asList(5, 6, 7));
}
@Test
public void whenAggregated_thenAggregated() {
Integer[] numbers = {1, 2, 2, 3, 4, 4, 4, 5};
List<List<Integer>> aggregated = StreamUtils
.aggregate(stream(numbers), (int1, int2) -> int1.compareTo(int2) == 0)
.collect(Collectors.toList());
assertThat(aggregated).containsExactly(asList(1), asList(2, 2), asList(3), asList(4, 4, 4), asList(5));
List<List<Integer>> aggregatedFixSize = StreamUtils.aggregate(stream(numbers), 5).collect(Collectors.toList());
assertThat(aggregatedFixSize).containsExactly(asList(1, 2, 2, 3, 4), asList(4, 4, 5));
}
@Test
public void whenGroupedRun_thenGroupedRun() {
Integer[] numbers = {1, 1, 2, 3, 4, 4, 5};
List<List<Integer>> grouped = StreamUtils.groupRuns(stream(numbers)).collect(Collectors.toList());
assertThat(grouped).containsExactly(asList(1, 1), asList(2), asList(3), asList(4, 4), asList(5));
Integer[] numbers2 = {1, 2, 3, 1};
List<List<Integer>> grouped2 = StreamUtils.groupRuns(stream(numbers2)).collect(Collectors.toList());
assertThat(grouped2).containsExactly(asList(1), asList(2), asList(3), asList(1));
}
@Test
public void whenAggregatedOnListCondition_thenAggregatedOnListCondition() {
Integer[] numbers = {1, 1, 2, 3, 4, 4, 5};
Stream<List<Integer>> aggregated = StreamUtils.aggregateOnListCondition(stream(numbers),
(currentList, nextInt) -> currentList.stream().mapToInt(Integer::intValue).sum() + nextInt <= 5);
assertThat(aggregated).containsExactly(asList(1, 1, 2), asList(3), asList(4), asList(4), asList(5));
}
@Test
public void givenProjectionFunction_whenMaxedBy_thenMaxedBy() {
Stream<String> clubs = Stream.of("Juventus", "Barcelona", "PSG");
Optional<String> longestName = clubs.collect(CollectorUtils.maxBy(String::length));
assertThat(longestName).contains("Barcelona");
}
@Test
public void givenStreamOfMultipleElem_whenUniqueCollector_thenValueReturned() {
Stream<Integer> singleElement = Stream.of(1);
Optional<Integer> unique = singleElement.collect(CollectorUtils.unique());
assertThat(unique).contains(1);
}
@Test
public void givenStreamOfMultipleElem_whenUniqueCollector_thenExceptionThrown() {
Stream<Integer> multipleElement = Stream.of(1, 2, 3);
assertThatExceptionOfType(NonUniqueValueException.class).isThrownBy(() -> {
multipleElement.collect(CollectorUtils.unique());
});
}
}
@@ -10,7 +10,6 @@ This module contains articles about string operations.
- [Java String equalsIgnoreCase()](https://www.baeldung.com/java-string-equalsignorecase)
- [Case-Insensitive String Matching in Java](https://www.baeldung.com/java-case-insensitive-string-matching)
- [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
@@ -1,86 +0,0 @@
package com.baeldung.pdf.base64;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.junit.BeforeClass;
import org.junit.Test;
public class EncodeDecodeUnitTest {
private static final String IN_FILE = "src/test/resources/input.pdf";
private static final String OUT_FILE = "src/test/resources/output.pdf";
private static byte[] inFileBytes;
@BeforeClass
public static void fileToByteArray() throws IOException {
inFileBytes = Files.readAllBytes(Paths.get(IN_FILE));
}
@Test
public void givenJavaBase64_whenEncoded_thenDecodedOK() throws IOException {
byte[] encoded = java.util.Base64.getEncoder().encode(inFileBytes);
byte[] decoded = java.util.Base64.getDecoder().decode(encoded);
writeToFile(OUT_FILE, decoded);
assertNotEquals(encoded.length, decoded.length);
assertEquals(inFileBytes.length, decoded.length);
assertArrayEquals(decoded, inFileBytes);
}
@Test
public void givenJavaBase64_whenEncodedStream_thenDecodedStreamOK() throws IOException {
try (OutputStream os = java.util.Base64.getEncoder().wrap(new FileOutputStream(OUT_FILE));
FileInputStream fis = new FileInputStream(IN_FILE)) {
byte[] bytes = new byte[1024];
int read;
while ((read = fis.read(bytes)) > -1) {
os.write(bytes, 0, read);
}
}
byte[] encoded = java.util.Base64.getEncoder().encode(inFileBytes);
byte[] encodedOnDisk = Files.readAllBytes(Paths.get(OUT_FILE));
assertArrayEquals(encoded, encodedOnDisk);
byte[] decoded = java.util.Base64.getDecoder().decode(encoded);
byte[] decodedOnDisk = java.util.Base64.getDecoder().decode(encodedOnDisk);
assertArrayEquals(decoded, decodedOnDisk);
}
@Test
public void givenApacheCommons_givenJavaBase64_whenEncoded_thenDecodedOK() throws IOException {
byte[] encoded = org.apache.commons.codec.binary.Base64.encodeBase64(inFileBytes);
byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(encoded);
writeToFile(OUT_FILE, decoded);
assertNotEquals(encoded.length, decoded.length);
assertEquals(inFileBytes.length, decoded.length);
assertArrayEquals(decoded, inFileBytes);
}
private void writeToFile(String fileName, byte[] bytes) throws IOException {
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(bytes);
fos.flush();
fos.close();
}
}
@@ -0,0 +1,61 @@
<?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-string-operations-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-string-operations-3</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.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-artifact</artifactId>
<version>${maven-artifact.version}</version>
</dependency>
<dependency>
<groupId>org.gradle</groupId>
<artifactId>gradle-core</artifactId>
<version>${gradle-core.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson-core.version}</version>
</dependency>
<dependency>
<groupId>com.vdurmont</groupId>
<artifactId>semver4j</artifactId>
<version>${semver4j.version}</version>
</dependency>
</dependencies>
<properties>
<assertj.version>3.6.1</assertj.version>
<maven-artifact.version>3.6.3</maven-artifact.version>
<gradle-core.version>6.1.1</gradle-core.version>
<jackson-core.version>2.11.1</jackson-core.version>
<semver4j.version>3.1.0</semver4j.version>
</properties>
<repositories>
<repository>
<id>gradle-repo</id>
<url>https://repo.gradle.org/gradle/libs-releases-local/</url>
</repository>
</repositories>
</project>
@@ -0,0 +1,25 @@
package com.baeldung.versioncomparison;
public class VersionCompare {
public static int compareVersions(String version1, String version2) {
int comparisonResult = 0;
String[] version1Splits = version1.split("\\.");
String[] version2Splits = version2.split("\\.");
int maxLengthOfVersionSplits = Math.max(version1Splits.length, version2Splits.length);
for (int i = 0; i < maxLengthOfVersionSplits; i++){
Integer v1 = i < version1Splits.length ? Integer.parseInt(version1Splits[i]) : 0;
Integer v2 = i < version2Splits.length ? Integer.parseInt(version2Splits[i]) : 0;
int compare = v1.compareTo(v2);
if (compare != 0) {
comparisonResult = compare;
break;
}
}
return comparisonResult;
}
}
@@ -0,0 +1,136 @@
package com.baeldung.versioncomparison;
import org.junit.Test;
import com.fasterxml.jackson.core.Version;
import com.vdurmont.semver4j.Semver;
import com.vdurmont.semver4j.Semver.VersionDiff;
import org.apache.maven.artifact.versioning.ComparableVersion;
import org.gradle.util.VersionNumber;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class VersionComparisonUnitTest {
@Test
public void givenVersionStrings_whenUsingMavenArtifact_thenCompareVersions() {
ComparableVersion version1_1 = new ComparableVersion("1.1");
ComparableVersion version1_2 = new ComparableVersion("1.2");
ComparableVersion version1_3 = new ComparableVersion("1.3");
assertTrue(version1_1.compareTo(version1_2) < 0);
assertTrue(version1_3.compareTo(version1_2) > 0);
ComparableVersion version1_1_0 = new ComparableVersion("1.1.0");
assertEquals(0, version1_1.compareTo(version1_1_0));
ComparableVersion version1_1_alpha = new ComparableVersion("1.1-alpha");
assertTrue(version1_1.compareTo(version1_1_alpha) > 0);
ComparableVersion version1_1_beta = new ComparableVersion("1.1-beta");
ComparableVersion version1_1_milestone = new ComparableVersion("1.1-milestone");
ComparableVersion version1_1_rc = new ComparableVersion("1.1-rc");
ComparableVersion version1_1_snapshot = new ComparableVersion("1.1-snapshot");
assertTrue(version1_1_alpha.compareTo(version1_1_beta) < 0);
assertTrue(version1_1_beta.compareTo(version1_1_milestone) < 0);
assertTrue(version1_1_rc.compareTo(version1_1_snapshot) < 0);
assertTrue(version1_1_snapshot.compareTo(version1_1) < 0);
ComparableVersion version1_1_c = new ComparableVersion("1.1-c");
ComparableVersion version1_1_z = new ComparableVersion("1.1-z");
ComparableVersion version1_1_1 = new ComparableVersion("1.1.1");
assertTrue(version1_1_c.compareTo(version1_1_z) < 0);
assertTrue(version1_1_z.compareTo(version1_1_1) < 0);
}
@Test
public void givenVersionStrings_whenUsingGradle_thenCompareVersions() {
VersionNumber version1_1 = VersionNumber.parse("1.1");
VersionNumber version1_2 = VersionNumber.parse("1.2");
VersionNumber version1_3 = VersionNumber.parse("1.3");
assertTrue(version1_1.compareTo(version1_2) < 0);
assertTrue(version1_3.compareTo(version1_2) > 0);
VersionNumber version1_1_0 = VersionNumber.parse("1.1.0");
assertEquals(0, version1_1.compareTo(version1_1_0));
VersionNumber version1_1_1_1_alpha = VersionNumber.parse("1.1.1.1-alpha");
assertTrue(version1_1.compareTo(version1_1_1_1_alpha) < 0);
VersionNumber version1_1_beta = VersionNumber.parse("1.1.0.0-beta");
assertTrue(version1_1_beta.compareTo(version1_1_1_1_alpha) < 0);
VersionNumber version1_1_1_snapshot = VersionNumber.parse("1.1.1-snapshot");
assertTrue(version1_1_1_1_alpha.compareTo(version1_1_1_snapshot) < 0);
}
@Test
public void givenVersionStrings_whenUsingJackson_thenCompareVersions() {
Version version1_1 = new Version(1, 1, 0, null, null, null);
Version version1_2 = new Version(1, 2, 0, null, null, null);
Version version1_3 = new Version(1, 3, 0, null, null, null);
assertTrue(version1_1.compareTo(version1_2) < 0);
assertTrue(version1_3.compareTo(version1_2) > 0);
Version version1_1_1 = new Version(1, 1, 1, null, null, null);
assertTrue(version1_1.compareTo(version1_1_1) < 0);
Version version1_1_maven = new Version(1, 1, 0, null, "org.apache.maven", null);
Version version1_1_gradle = new Version(1, 1, 0, null, "org.gradle", null);
assertTrue(version1_1_maven.compareTo(version1_1_gradle) < 0);
Version version1_1_snapshot = new Version(1, 1, 0, "snapshot", null, null);
assertEquals(0, version1_1.compareTo(version1_1_snapshot));
assertTrue(version1_1_snapshot.isSnapshot());
}
@Test
public void givenVersionStrings_whenUsingSemver_thenCompareVersions() {
Semver version1_1 = new Semver("1.1.0");
Semver version1_2 = new Semver("1.2.0");
Semver version1_3 = new Semver("1.3.0");
assertTrue(version1_1.compareTo(version1_2) < 0);
assertTrue(version1_3.compareTo(version1_2) > 0);
Semver version1_1_alpha = new Semver("1.1.0-alpha");
assertTrue(version1_1.isGreaterThan(version1_1_alpha));
Semver version1_1_beta = new Semver("1.1.0-beta");
Semver version1_1_milestone = new Semver("1.1.0-milestone");
Semver version1_1_rc = new Semver("1.1.0-rc");
Semver version1_1_snapshot = new Semver("1.1.0-snapshot");
assertTrue(version1_1_alpha.isLowerThan(version1_1_beta));
assertTrue(version1_1_beta.compareTo(version1_1_milestone) < 0);
assertTrue(version1_1_rc.compareTo(version1_1_snapshot) < 0);
assertTrue(version1_1_snapshot.compareTo(version1_1) < 0);
assertTrue(version1_1.isEqualTo("1.1.0"));
assertEquals(VersionDiff.MAJOR, version1_1.diff("2.1.0"));
assertEquals(VersionDiff.MINOR, version1_1.diff("1.2.3"));
assertEquals(VersionDiff.PATCH, version1_1.diff("1.1.1"));
assertTrue(version1_1.isStable());
assertFalse(version1_1_alpha.isStable());
}
@Test
public void givenVersionStrings_whenUsingCustomVersionCompare_thenCompareVersions() {
assertTrue(VersionCompare.compareVersions("1.0.1", "1.1.2") < 0);
assertTrue(VersionCompare.compareVersions("1.0.1", "1.10") < 0);
assertTrue(VersionCompare.compareVersions("1.1.2", "1.0.1") > 0);
assertTrue(VersionCompare.compareVersions("1.1.2", "1.2") < 0);
assertEquals(0, VersionCompare.compareVersions("1.3.0", "1.3"));
}
}
+4
View File
@@ -72,6 +72,7 @@
<module>core-java-io</module>
<module>core-java-io-2</module>
<module>core-java-io-3</module>
<module>core-java-io-apis</module>
<module>core-java-io-conversions</module>
<module>core-java-io-conversions-2</module>
@@ -85,6 +86,7 @@
<module>core-java-lambdas</module>
<module>core-java-lang</module>
<module>core-java-lang-2</module>
<module>core-java-lang-3</module>
<module>core-java-lang-math</module>
<module>core-java-lang-math-2</module>
<module>core-java-lang-oop-constructors</module>
@@ -110,6 +112,7 @@
<module>core-java-perf</module>
<module>core-java-reflection</module>
<module>core-java-reflection-2</module>
<module>core-java-security</module>
<module>core-java-security-2</module>
@@ -124,6 +127,7 @@
<module>core-java-string-conversions-2</module>
<module>core-java-string-operations</module>
<module>core-java-string-operations-2</module>
<module>core-java-string-operations-3</module>
<module>core-java-strings</module>
<module>core-java-sun</module>