Merge branch 'master' into bael-16656

This commit is contained in:
Josh Cummings
2019-10-26 15:37:05 -06:00
committed by GitHub
parent db85c8f275
commit 0be2175c89
20539 changed files with 1643630 additions and 0 deletions
+25
View File
@@ -0,0 +1,25 @@
*.class
0.*
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
.resourceCache
# Packaged files #
*.jar
*.war
*.ear
# Files generated by integration tests
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea/
*.iml
+44
View File
@@ -0,0 +1,44 @@
## Core Java Cookbooks and Examples
### Relevant Articles:
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java)
- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
- [How to Add a Single Element to a Stream](http://www.baeldung.com/java-stream-append-prepend)
- [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)
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
- [Quick Guide to Java Stack](http://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)
- [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class)
- [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)
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
- [Java Try with Resources](https://www.baeldung.com/java-try-with-resources)
- [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class)
- [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding)
- [Graphs in Java](https://www.baeldung.com/java-graphs)
- [Console I/O 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)
- [Introduction to Basic Syntax in Java](https://www.baeldung.com/java-syntax)
- [Using Curl in Java](https://www.baeldung.com/java-curl)
- [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year)
- [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators)
- [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar)
- [Making a JSON POST Request With HttpURLConnection](https://www.baeldung.com/httpurlconnection-post)
- [How to Find an Exceptions 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)
+95
View File
@@ -0,0 +1,95 @@
<?xml version="1.0"?>
<webRowSet xmlns="http://java.sun.com/xml/ns/jdbc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/jdbc http://java.sun.com/xml/ns/jdbc/webrowset.xsd">
<properties>
<command>SELECT * FROM customers</command>
<concurrency>1008</concurrency>
<datasource><null/></datasource>
<escape-processing>true</escape-processing>
<fetch-direction>1000</fetch-direction>
<fetch-size>0</fetch-size>
<isolation-level>2</isolation-level>
<key-columns>
</key-columns>
<map>
</map>
<max-field-size>0</max-field-size>
<max-rows>0</max-rows>
<query-timeout>0</query-timeout>
<read-only>true</read-only>
<rowset-type>ResultSet.TYPE_SCROLL_INSENSITIVE</rowset-type>
<show-deleted>false</show-deleted>
<table-name>customers</table-name>
<url>jdbc:h2:mem:testdb</url>
<sync-provider>
<sync-provider-name>com.sun.rowset.providers.RIOptimisticProvider</sync-provider-name>
<sync-provider-vendor>Oracle Corporation</sync-provider-vendor>
<sync-provider-version>1.0</sync-provider-version>
<sync-provider-grade>2</sync-provider-grade>
<data-source-lock>1</data-source-lock>
</sync-provider>
</properties>
<metadata>
<column-count>2</column-count>
<column-definition>
<column-index>1</column-index>
<auto-increment>false</auto-increment>
<case-sensitive>true</case-sensitive>
<currency>false</currency>
<nullable>0</nullable>
<signed>true</signed>
<searchable>true</searchable>
<column-display-size>11</column-display-size>
<column-label>ID</column-label>
<column-name>ID</column-name>
<schema-name>PUBLIC</schema-name>
<column-precision>10</column-precision>
<column-scale>0</column-scale>
<table-name>CUSTOMERS</table-name>
<catalog-name>TESTDB</catalog-name>
<column-type>4</column-type>
<column-type-name>INTEGER</column-type-name>
</column-definition>
<column-definition>
<column-index>2</column-index>
<auto-increment>false</auto-increment>
<case-sensitive>true</case-sensitive>
<currency>false</currency>
<nullable>0</nullable>
<signed>true</signed>
<searchable>true</searchable>
<column-display-size>50</column-display-size>
<column-label>NAME</column-label>
<column-name>NAME</column-name>
<schema-name>PUBLIC</schema-name>
<column-precision>50</column-precision>
<column-scale>0</column-scale>
<table-name>CUSTOMERS</table-name>
<catalog-name>TESTDB</catalog-name>
<column-type>12</column-type>
<column-type-name>VARCHAR</column-type-name>
</column-definition>
</metadata>
<data>
<currentRow>
<columnValue>1</columnValue>
<columnValue>Customer1</columnValue>
</currentRow>
<currentRow>
<columnValue>2</columnValue>
<columnValue>Customer2</columnValue>
</currentRow>
<currentRow>
<columnValue>3</columnValue>
<columnValue>Customer3</columnValue>
</currentRow>
<currentRow>
<columnValue>4</columnValue>
<columnValue>Customer4</columnValue>
</currentRow>
<currentRow>
<columnValue>5</columnValue>
<columnValue>Customer5</columnValue>
</currentRow>
</data>
</webRowSet>
Binary file not shown.
+400
View File
@@ -0,0 +1,400 @@
<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</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.unix4j</groupId>
<artifactId>unix4j-command</artifactId>
<version>${unix4j.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.grep4j</groupId>
<artifactId>grep4j</artifactId>
<version>${grep4j.version}</version>
</dependency>
<!-- web -->
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.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>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>${javamoney.moneta.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java</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.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<archive>
<manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<version>${onejar-maven-plugin.version}</version>
<executions>
<execution>
<configuration>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<attachToBuild>true</attachToBuild>
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
</configuration>
<goals>
<goal>one-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot-maven-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</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>1.8</source>
<target>1.8</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>
<!-- java instrumentation profiles to build jars -->
<profile>
<id>buildAgentLoader</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>agentLoader</classifier>
<classesDirectory>target/classes</classesDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
<includes>
<include>com/baeldung/instrumentation/application/AgentLoader.class</include>
<include>com/baeldung/instrumentation/application/Launcher.class</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>buildApplication</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>application</classifier>
<classesDirectory>target/classes</classesDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
<includes>
<include>com/baeldung/instrumentation/application/MyAtm.class</include>
<include>com/baeldung/instrumentation/application/MyAtmApplication.class</include>
<include>com/baeldung/instrumentation/application/Launcher.class</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>buildAgent</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>agent</classifier>
<classesDirectory>target/classes</classesDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
<includes>
<include>com/baeldung/instrumentation/agent/AtmTransformer.class</include>
<include>com/baeldung/instrumentation/agent/MyInstrumentationAgent.class</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- util -->
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
<!-- maven plugins -->
<javamoney.moneta.version>1.1</javamoney.moneta.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
<onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version>
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
<spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version>
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
</properties>
</project>
@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear
@@ -0,0 +1,29 @@
package com.baeldung.abstractclasses.application;
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
import com.baeldung.abstractclasses.filereaders.LowercaseFileReader;
import com.baeldung.abstractclasses.filereaders.UppercaseFileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Application {
public static void main(String[] args) throws IOException, URISyntaxException {
Application application = new Application();
Path path = application.getPathFromResourcesFile("files/test.txt");
BaseFileReader lowercaseFileReader = new LowercaseFileReader(path);
lowercaseFileReader.readFile().forEach(line -> System.out.println(line));
BaseFileReader uppercaseFileReader = new UppercaseFileReader(path);
uppercaseFileReader.readFile().forEach(line -> System.out.println(line));
}
private Path getPathFromResourcesFile(String filePath) throws URISyntaxException {
return Paths.get(getClass().getClassLoader().getResource(filePath).toURI());
}
}
@@ -0,0 +1,27 @@
package com.baeldung.abstractclasses.filereaders;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;
public abstract class BaseFileReader {
protected Path filePath;
protected BaseFileReader(Path filePath) {
this.filePath = filePath;
}
public Path getFilePath() {
return filePath;
}
public List<String> readFile() throws IOException {
return Files.lines(filePath)
.map(this::mapFileLine).collect(Collectors.toList());
}
protected abstract String mapFileLine(String line);
}
@@ -0,0 +1,15 @@
package com.baeldung.abstractclasses.filereaders;
import java.nio.file.Path;
public class LowercaseFileReader extends BaseFileReader {
public LowercaseFileReader(Path filePath) {
super(filePath);
}
@Override
public String mapFileLine(String line) {
return line.toLowerCase();
}
}
@@ -0,0 +1,15 @@
package com.baeldung.abstractclasses.filereaders;
import java.nio.file.Path;
public class UppercaseFileReader extends BaseFileReader {
public UppercaseFileReader(Path filePath) {
super(filePath);
}
@Override
public String mapFileLine(String line) {
return line.toUpperCase();
}
}
@@ -0,0 +1,62 @@
package com.baeldung.asciiart;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
public class AsciiArt {
public AsciiArt() {
}
public void drawString(String text, String artChar, Settings settings) {
BufferedImage image = getImageIntegerMode(settings.width, settings.height);
Graphics2D graphics2D = getGraphics2D(image.getGraphics(), settings);
graphics2D.drawString(text, 6, ((int) (settings.height * 0.67)));
for (int y = 0; y < settings.height; y++) {
StringBuilder stringBuilder = new StringBuilder();
for (int x = 0; x < settings.width; x++) {
stringBuilder.append(image.getRGB(x, y) == -16777216 ? " " : artChar);
}
if (stringBuilder.toString()
.trim()
.isEmpty()) {
continue;
}
System.out.println(stringBuilder);
}
}
private BufferedImage getImageIntegerMode(int width, int height) {
return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
}
private Graphics2D getGraphics2D(Graphics graphics, Settings settings) {
graphics.setFont(settings.font);
Graphics2D graphics2D = (Graphics2D) graphics;
graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
return graphics2D;
}
public class Settings {
public Font font;
public int width;
public int height;
public Settings(Font font, int width, int height) {
this.font = font;
this.width = width;
this.height = height;
}
}
}
@@ -0,0 +1,11 @@
package com.baeldung.basicsyntax;
public class SimpleAddition {
public static void main(String[] args) {
int a = 10;
int b = 5;
double c = a + b;
System.out.println( a + " + " + b + " = " + c);
}
}
@@ -0,0 +1,26 @@
package com.baeldung.console;
import java.io.Console;
public class ConsoleConsoleClass {
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
System.out.print("No console available");
return;
}
String progLanguauge = console.readLine("Enter your favourite programming language: ");
console.printf(progLanguauge + " is very interesting!");
char[] pass = console.readPassword("To finish, enter password: ");
if ("BAELDUNG".equals(pass.toString().toUpperCase()))
console.printf("Good! Regards!");
else
console.printf("Nice try. Regards.");
}
}
@@ -0,0 +1,76 @@
package com.baeldung.console;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.regex.Pattern;
public class ConsoleScannerClass {
public static void main(String[] args) {
System.out.println("Please enter your name and surname: ");
Scanner scanner = new Scanner(System.in);
String nameSurname = scanner.nextLine();
System.out.println("Please enter your gender: ");
char gender = scanner.next().charAt(0);
System.out.println("Please enter your age: ");
int age = scanner.nextInt();
System.out.println("Please enter your height in meters: ");
double height = scanner.nextDouble();
System.out.println(nameSurname + ", " + age + ", is a great " + (gender == 'm' ? "guy" : "girl") + " with " + height + " meters height" + " and " + (gender == 'm' ? "he" : "she") + " reads Baeldung.");
System.out.print("Have a good");
System.out.print(" one!");
System.out.println("\nPlease enter number of years of experience as a developer: ");
BufferedReader buffReader = new BufferedReader(new InputStreamReader(System.in));
int i = 0;
try {
i = Integer.parseInt(buffReader.readLine());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("You are a " + (i > 5 ? "great" : "good") + " developer!");
int sum = 0, count = 0;
System.out.println("Please enter your college degrees. To finish, enter baeldung website url");
while (scanner.hasNextInt()) {
int nmbr = scanner.nextInt();
sum += nmbr;
count++;
}
int mean = sum / count;
System.out.println("Your average degree is " + mean);
if (scanner.hasNext(Pattern.compile("www.baeldung.com")))
System.out.println("Correct!");
else
System.out.println("Baeldung website url is www.baeldung.com");
if (scanner != null)
scanner.close();
}
}
@@ -0,0 +1,30 @@
package com.baeldung.deserialization;
import java.io.Serializable;
public class AppleProduct implements Serializable {
private static final long serialVersionUID = 1234567L; // user-defined (i.e. not default or generated)
// private static final long serialVersionUID = 7654321L; // user-defined (i.e. not default or generated)
public String headphonePort;
public String thunderboltPort;
public String lightningPort;
public String getHeadphonePort() {
return headphonePort;
}
public String getThunderboltPort() {
return thunderboltPort;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public String getLightningPort() {
return lightningPort;
}
}
@@ -0,0 +1,28 @@
package com.baeldung.deserialization;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Base64;
public class DeserializationUtility {
public static void main(String[] args) throws ClassNotFoundException, IOException {
String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADWxpZ2h0bmluZ1BvcnRxAH4AAUwAD3RodW5kZXJib2x0UG9ydHEAfgABeHB0ABFoZWFkcGhvbmVQb3J0MjAyMHQAEWxpZ2h0bmluZ1BvcnQyMDIwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
System.out.println("Deserializing AppleProduct...");
AppleProduct deserializedObj = (AppleProduct) deSerializeObjectFromString(serializedObj);
System.out.println("Headphone port of AppleProduct:" + deserializedObj.getHeadphonePort());
System.out.println("Thunderbolt port of AppleProduct:" + deserializedObj.getThunderboltPort());
System.out.println("LightningPort port of AppleProduct:" + deserializedObj.getLightningPort());
}
public static Object deSerializeObjectFromString(String s) throws IOException, ClassNotFoundException {
byte[] data = Base64.getDecoder().decode(s);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
Object o = ois.readObject();
ois.close();
return o;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.deserialization;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Base64;
public class SerializationUtility {
public static void main(String[] args) throws ClassNotFoundException, IOException {
AppleProduct macBook = new AppleProduct();
macBook.headphonePort = "headphonePort2020";
macBook.thunderboltPort = "thunderboltPort2020";
macBook.lightningPort = "lightningPort2020";
String serializedObj = serializeObjectToString(macBook);
System.out.println("Serialized AppleProduct object to string:");
System.out.println(serializedObj);
}
public static String serializeObjectToString(Serializable o) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
return Base64.getEncoder().encodeToString(baos.toByteArray());
}
}
@@ -0,0 +1,45 @@
package com.baeldung.encoding;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
public class CharacterEncodingExamples {
static String readFile(String filePath, String encoding) throws IOException {
File file = new File(filePath);
StringBuffer buffer = new StringBuffer();
try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), encoding)) {
int data;
while ((data = isr.read()) != -1) {
buffer.append((char) data);
}
}
return buffer.toString();
}
static String convertToBinary(String input, String encoding) throws UnsupportedEncodingException {
byte[] bytes = input.getBytes(encoding);
StringBuffer buffer = new StringBuffer();
for (int b : bytes) {
buffer.append(Integer.toBinaryString((b + 256) % 256));
buffer.append(" ");
}
return buffer.toString();
}
static String decodeText(String input, Charset charset, CodingErrorAction codingErrorAction) throws IOException {
CharsetDecoder charsetDecoder = charset.newDecoder();
charsetDecoder.onMalformedInput(codingErrorAction);
return new BufferedReader(
new InputStreamReader(
new ByteArrayInputStream(input.getBytes()), charsetDecoder)).readLine();
}
}
@@ -0,0 +1,11 @@
package com.baeldung.executable;
import javax.swing.JOptionPane;
public class ExecutableMavenJar {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1);
}
}
@@ -0,0 +1,23 @@
package com.baeldung.externalizable;
import java.io.*;
public class Community implements Serializable {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Community{" +
"id=" + id +
'}';
}
}
@@ -0,0 +1,62 @@
package com.baeldung.externalizable;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
public class Country implements Externalizable {
private static final long serialVersionUID = 1L;
private String name;
private String capital;
private int code;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCapital() {
return capital;
}
public void setCapital(String capital) {
this.capital = capital;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(name);
out.writeUTF(capital);
out.writeInt(code);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.name = in.readUTF();
this.capital = in.readUTF();
this.code = in.readInt();
}
@Override
public String toString() {
return "Country{" +
"name='" + name + '\'' +
", capital='" + capital + '\'' +
", code=" + code +
'}';
}
}
@@ -0,0 +1,57 @@
package com.baeldung.externalizable;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
public class Region extends Country implements Externalizable {
private static final long serialVersionUID = 1L;
private String climate;
private Double population;
private Community community;
public String getClimate() {
return climate;
}
public void setClimate(String climate) {
this.climate = climate;
}
public Double getPopulation() {
return population;
}
public void setPopulation(Double population) {
this.population = population;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal(out);
out.writeUTF(climate);
community = new Community();
community.setId(5);
out.writeObject(community);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
this.climate = in.readUTF();
community = (Community) in.readObject();
}
@Override
public String toString() {
return "Region = {" +
"country='" + super.toString() + '\'' +
"community='" + community.toString() + '\'' +
"climate='" + climate + '\'' +
", population=" + population +
'}';
}
}
@@ -0,0 +1,24 @@
package com.baeldung.fileparser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class BufferedReaderExample {
protected static ArrayList<String> generateArrayListFromFile(String filename) throws IOException {
ArrayList<String> result = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
while (br.ready()) {
result.add(br.readLine());
}
return result;
}
}
}
@@ -0,0 +1,31 @@
package com.baeldung.fileparser;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class FileReaderExample {
protected static ArrayList<String> generateArrayListFromFile(String filename) throws IOException {
ArrayList<String> result = new ArrayList<>();
try (FileReader f = new FileReader(filename)) {
StringBuffer sb = new StringBuffer();
while (f.ready()) {
char c = (char) f.read();
if (c == '\n') {
result.add(sb.toString());
sb = new StringBuffer();
} else {
sb.append(c);
}
}
if (sb.length() > 0) {
result.add(sb.toString());
}
}
return result;
}
}
@@ -0,0 +1,18 @@
package com.baeldung.fileparser;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class FilesReadLinesExample {
protected static ArrayList<String> generateArrayListFromFile(String filename) throws IOException {
List<String> result = Files.readAllLines(Paths.get(filename));
return (ArrayList<String>) result;
}
}
@@ -0,0 +1,24 @@
package com.baeldung.fileparser;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class ScannerIntExample {
protected static ArrayList<Integer> generateArrayListFromFile(String filename) throws IOException {
ArrayList<Integer> result = new ArrayList<>();
try (Scanner s = new Scanner(new FileReader(filename))) {
while (s.hasNext()) {
result.add(s.nextInt());
}
return result;
}
}
}
@@ -0,0 +1,24 @@
package com.baeldung.fileparser;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class ScannerStringExample {
protected static ArrayList<String> generateArrayListFromFile(String filename) throws IOException {
ArrayList<String> result = new ArrayList<>();
try (Scanner s = new Scanner(new FileReader(filename))) {
while (s.hasNext()) {
result.add(s.nextLine());
}
return result;
}
}
}
@@ -0,0 +1,42 @@
package com.baeldung.filesystem.jndi;
import java.io.File;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class LookupFSJNDI {
private InitialContext ctx = null;
public LookupFSJNDI() throws NamingException {
super();
init();
}
private void init() throws NamingException {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
// URI to namespace (actual directory)
env.put(Context.PROVIDER_URL, "file:./src/test/resources");
ctx = new InitialContext(env);
}
public InitialContext getCtx() {
return ctx;
}
public File getFile(String fileName) {
File file;
try {
file = (File) getCtx().lookup(fileName);
} catch (NamingException e) {
file = null;
}
return file;
}
}
@@ -0,0 +1,101 @@
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;
}
}
}
@@ -0,0 +1,44 @@
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;
}
}
@@ -0,0 +1,9 @@
package com.baeldung.jar;
public class JarExample {
public static void main(String[] args) {
System.out.println("Hello Baeldung Reader!");
}
}
@@ -0,0 +1 @@
Main-Class: com.baeldung.jar.JarExample
@@ -0,0 +1,16 @@
package com.baeldung.javac;
import java.util.ArrayList;
import java.util.List;
public class Data {
List<String> textList = new ArrayList();
public void addText(String text) {
textList.add(text);
}
public List getTextList() {
return this.textList;
}
}
@@ -0,0 +1,22 @@
package com.baeldung.javadoc;
public class Person {
/**
* This is a first name
*/
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
@@ -0,0 +1,70 @@
package com.baeldung.javadoc;
/**
* Hero is the main entity we will be using to . . .
* @author Captain America
*
*/
public class SuperHero extends Person {
/**
* The public name of a hero that is common knowledge
*/
private String heroName;
private String uniquePower;
private int health;
private int defense;
/**
* <p>This is a simple description of the method. . .
* <a href="http://www.supermanisthegreatest.com">Superman!</a>
* </p>
* @param incomingDamage the amount of incoming damage
* @return the amount of health hero has after attack
* @see <a href="http://www.link_to_jira/HERO-402">HERO-402</a>
* @since 1.0
* @deprecated As of version 1.1, use . . . instead
* @version 1.2
* @throws IllegalArgumentException if incomingDamage is negative
*/
public int successfullyAttacked(int incomingDamage, String damageType) throws Exception {
// do things
if (incomingDamage < 0) {
throw new IllegalArgumentException ("Cannot cause negative damage");
}
return 0;
}
public String getHeroName() {
return heroName;
}
public void setHeroName(String heroName) {
this.heroName = heroName;
}
public String getUniquePower() {
return uniquePower;
}
public void setUniquePower(String uniquePower) {
this.uniquePower = uniquePower;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public int getDefense() {
return defense;
}
public void setDefense(int defense) {
this.defense = defense;
}
}
@@ -0,0 +1,46 @@
package com.baeldung.jsonposturlconnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostJSONWithHttpURLConnection {
public static void main (String []args) throws IOException{
//Change the URL with any other publicly accessible POST resource, which accepts JSON request body
URL url = new URL ("https://reqres.in/api/users");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
//JSON String need to be constructed for the specific resource.
//We may construct complex JSON using any third-party JSON libraries such as jackson or org.json
String jsonInputString = "{\"name\": \"Upendra\", \"job\": \"Programmer\"}";
try(OutputStream os = con.getOutputStream()){
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
int code = con.getResponseCode();
System.out.println(code);
try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))){
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
}
}
@@ -0,0 +1,8 @@
package com.baeldung.manifest;
public class AppExample {
public static void main(String[] args){
System.out.println("AppExample executed!");
}
}
@@ -0,0 +1,83 @@
package com.baeldung.manifest;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class ExecuteJarFile {
private static final String DELIMITER = " ";
private static final String WORK_PATH = "src/main/java/com/baeldung/manifest";
private static final String MANIFEST_MF_PATH = WORK_PATH + "/MANIFEST.MF";
private static final String MAIN_MANIFEST_ATTRIBUTE = "Main-Class: com.baeldung.manifest.AppExample";
private static final String COMPILE_COMMAND = "javac -d . AppExample.java";
private static final String CREATE_JAR_WITHOUT_MF_ATT_COMMAND = "jar cvf example.jar com/baeldung/manifest/AppExample.class";
private static final String CREATE_JAR_WITH_MF_ATT_COMMAND = "jar cvmf MANIFEST.MF example.jar com/baeldung/manifest/AppExample.class";
private static final String EXECUTE_JAR_COMMAND = "java -jar example.jar";
public static void main(String[] args) {
System.out.println(executeJarWithoutManifestAttribute());
System.out.println(executeJarWithManifestAttribute());
}
public static String executeJarWithoutManifestAttribute() {
return executeJar(CREATE_JAR_WITHOUT_MF_ATT_COMMAND);
}
public static String executeJarWithManifestAttribute() {
createManifestFile();
return executeJar(CREATE_JAR_WITH_MF_ATT_COMMAND);
}
private static void createManifestFile() {
BufferedWriter writer;
try {
writer = new BufferedWriter(new FileWriter(MANIFEST_MF_PATH));
writer.write(MAIN_MANIFEST_ATTRIBUTE);
writer.newLine();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String executeJar(String createJarCommand) {
executeCommand(COMPILE_COMMAND);
executeCommand(createJarCommand);
return executeCommand(EXECUTE_JAR_COMMAND);
}
private static String executeCommand(String command) {
String output = null;
try {
output = collectOutput(runProcess(command));
} catch (Exception ex) {
System.out.println(ex);
}
return output;
}
private static String collectOutput(Process process) throws IOException {
StringBuffer output = new StringBuffer();
BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = outputReader.readLine()) != null) {
output.append(line + "\n");
}
return output.toString();
}
private static Process runProcess(String command) throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder(command.split(DELIMITER));
builder.directory(new File(WORK_PATH).getAbsoluteFile());
builder.redirectErrorStream(true);
Process process = builder.start();
process.waitFor();
return process;
}
}
@@ -0,0 +1 @@
Main-Class: com.baeldung.manifest.AppExample
@@ -0,0 +1,151 @@
package com.baeldung.money;
import java.util.Locale;
import java.util.logging.Logger;
import javax.money.CurrencyUnit;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.money.UnknownCurrencyException;
import javax.money.convert.ConversionQueryBuilder;
import javax.money.convert.CurrencyConversion;
import javax.money.convert.MonetaryConversions;
import javax.money.format.AmountFormatQueryBuilder;
import javax.money.format.MonetaryAmountFormat;
import javax.money.format.MonetaryFormats;
import org.javamoney.moneta.FastMoney;
import org.javamoney.moneta.Money;
import org.javamoney.moneta.format.CurrencyStyle;
public class JavaMoney {
final static Logger LOGGER = Logger.getLogger(JavaMoney.class.getName());
CurrencyUnit USD;
MonetaryAmount fstAmtUSD;
MonetaryAmount fstAmtEUR;
MonetaryAmount oneDolar;
MonetaryAmount moneyof;
MonetaryAmount fastmoneyof;
MonetaryAmount roundEUR;
MonetaryAmount calcAmtUSD;
MonetaryAmount[] monetaryAmounts;
MonetaryAmount sumAmtCHF;
MonetaryAmount calcMoneyFastMoney;
MonetaryAmount convertedAmountEURtoUSD;
MonetaryAmount convertedAmountEURtoUSD2;
MonetaryAmount convertedAmountUSDtoEUR;
MonetaryAmount convertedAmountUSDtoEUR2;
MonetaryAmount multiplyAmount;
MonetaryAmount divideAmount;
MonetaryAmount oneDivThree;
CurrencyConversion convEUR;
CurrencyConversion convUSD;
CurrencyConversion conversionUSD;
CurrencyConversion conversionEUR;
MonetaryAmount oneEuro;
MonetaryAmountFormat formatUSD;
MonetaryAmountFormat customFormat;
String usFormatted;
String customFormatted;
public JavaMoney() {
USD = Monetary.getCurrency("USD");
fstAmtUSD = Monetary.getDefaultAmountFactory().setCurrency(USD).setNumber(200.50).create();
fstAmtEUR = Monetary.getDefaultAmountFactory().setCurrency("EUR").setNumber(1.30473908).create();
oneDolar = Monetary.getDefaultAmountFactory().setCurrency("USD").setNumber(1).create();
moneyof = Money.of(12, USD);
fastmoneyof = FastMoney.of(2, USD);
LOGGER.info("First Amount in USD : " + fstAmtUSD);
LOGGER.info("First Amount in EUR : " + fstAmtEUR);
LOGGER.info("One Dolar : " + oneDolar);
LOGGER.info("MoneyOf : " + moneyof);
LOGGER.info("FastMoneyOf : " + fastmoneyof);
try{
@SuppressWarnings("unused")
CurrencyUnit AAA = Monetary.getCurrency("AAA");
} catch (UnknownCurrencyException e) {
LOGGER.severe("Unknown Currency");
}
roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding());
LOGGER.info("Rounded EUR : " + roundEUR);
calcAmtUSD = Money.of(1, "USD").subtract(fstAmtUSD);
LOGGER.info("Substracting amounts : " + calcAmtUSD);
calcMoneyFastMoney = moneyof.subtract(fastmoneyof);
LOGGER.info("Money & FastMoney operations : " + calcMoneyFastMoney);
monetaryAmounts =
new MonetaryAmount[] {
Money.of(100, "CHF"),
Money.of(10.20, "CHF"),
Money.of(1.15, "CHF"), };
sumAmtCHF = Money.of(0, "CHF");
for (MonetaryAmount monetaryAmount : monetaryAmounts) {
sumAmtCHF = sumAmtCHF.add(monetaryAmount);
}
LOGGER.info("Adding amounts : " + sumAmtCHF);
multiplyAmount = oneDolar.multiply(0.25);
LOGGER.info("Multiply Amount : " + multiplyAmount);
divideAmount = oneDolar.divide(0.25);
LOGGER.info("Divide Amount : " + divideAmount);
try{
oneDivThree = oneDolar.divide(3);
}catch (ArithmeticException e) {
LOGGER.severe("One divide by Three is an infinite number");
}
convEUR = MonetaryConversions.getConversion(ConversionQueryBuilder.of().setTermCurrency("EUR").build());
convUSD = MonetaryConversions.getConversion(ConversionQueryBuilder.of().setTermCurrency(USD).build());
conversionUSD = MonetaryConversions.getConversion("USD");
conversionEUR = MonetaryConversions.getConversion("EUR");
convertedAmountEURtoUSD = fstAmtEUR.with(conversionUSD);
convertedAmountEURtoUSD2 = fstAmtEUR.with(convUSD);
convertedAmountUSDtoEUR = oneDolar.with(conversionEUR);
convertedAmountUSDtoEUR2 = oneDolar.with(convEUR);
LOGGER.info("C1 - " + convertedAmountEURtoUSD);
LOGGER.info("C2 - " + convertedAmountEURtoUSD2);
LOGGER.info("One Euro -> " + convertedAmountUSDtoEUR);
LOGGER.info("One Euro2 -> " + convertedAmountUSDtoEUR2);
oneEuro = Money.of(1, "EUR");
if (oneEuro.equals(FastMoney.of(1, "EUR"))) {
LOGGER.info("Money == FastMoney");
} else {
LOGGER.info("Money != FastMoney");
}
if (oneDolar.equals(Money.of(1, "USD"))) {
LOGGER.info("Factory == Money");
} else {
LOGGER.info("Factory != Money");
}
formatUSD = MonetaryFormats.getAmountFormat(Locale.US);
usFormatted = formatUSD.format(oneDolar);
LOGGER.info("One dolar standard formatted : " + usFormatted);
customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder.of(Locale.US).set(CurrencyStyle.NAME).set("pattern", "00000.00 ¤").build());
customFormatted = customFormat.format(oneDolar);
LOGGER.info("One dolar custom formatted : " + customFormatted);
}
public static void main(String[] args) {
@SuppressWarnings("unused")
JavaMoney java9Money = new JavaMoney();
}
}
@@ -0,0 +1,18 @@
package com.baeldung.objectsize;
import java.lang.instrument.Instrumentation;
public class InstrumentationAgent {
private static volatile Instrumentation globalInstrumentation;
public static void premain(final String agentArgs, final Instrumentation inst) {
globalInstrumentation = inst;
}
public static long getObjectSize(final Object object) {
if (globalInstrumentation == null) {
throw new IllegalStateException("Agent not initialized.");
}
return globalInstrumentation.getObjectSize(object);
}
}
@@ -0,0 +1,59 @@
package com.baeldung.objectsize;
import java.util.ArrayList;
import java.util.List;
public class InstrumentationExample {
public static void printObjectSize(Object object) {
System.out.println("Object type: " + object.getClass() + ", size: " + InstrumentationAgent.getObjectSize(object) + " bytes");
}
public static void main(String[] arguments) {
String emptyString = "";
String string = "Estimating Object Size Using Instrumentation";
String[] stringArray = { emptyString, string, "com.baeldung" };
String[] anotherStringArray = new String[100];
List<String> stringList = new ArrayList<>();
StringBuilder stringBuilder = new StringBuilder(100);
int maxIntPrimitive = Integer.MAX_VALUE;
int minIntPrimitive = Integer.MIN_VALUE;
Integer maxInteger = Integer.MAX_VALUE;
Integer minInteger = Integer.MIN_VALUE;
long zeroLong = 0L;
double zeroDouble = 0.0;
boolean falseBoolean = false;
Object object = new Object();
class EmptyClass {
}
EmptyClass emptyClass = new EmptyClass();
class StringClass {
public String s;
}
StringClass stringClass = new StringClass();
printObjectSize(emptyString);
printObjectSize(string);
printObjectSize(stringArray);
printObjectSize(anotherStringArray);
printObjectSize(stringList);
printObjectSize(stringBuilder);
printObjectSize(maxIntPrimitive);
printObjectSize(minIntPrimitive);
printObjectSize(maxInteger);
printObjectSize(minInteger);
printObjectSize(zeroLong);
printObjectSize(zeroDouble);
printObjectSize(falseBoolean);
printObjectSize(Day.TUESDAY);
printObjectSize(object);
printObjectSize(emptyClass);
printObjectSize(stringClass);
}
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
}
@@ -0,0 +1 @@
Premain-class: com.baeldung.objectsize.InstrumentationAgent
@@ -0,0 +1,61 @@
package com.baeldung.printf;
import java.util.Date;
import java.util.Locale;
public class PrintfExamples {
public static void main(String[] args) {
printfNewLine();
printfChar();
printfString();
printfNumber();
printfDateTime();
printfBoolean();
}
private static void printfNewLine() {
System.out.printf("baeldung%nline%nterminator");
}
private static void printfString() {
System.out.printf("'%s' %n", "baeldung");
System.out.printf("'%S' %n", "baeldung");
System.out.printf("'%15s' %n", "baeldung");
System.out.printf("'%-10s' %n", "baeldung");
}
private static void printfChar() {
System.out.printf("%c%n", 's');
System.out.printf("%C%n", 's');
}
private static void printfNumber() {
System.out.printf("simple integer: %d%n", 10000L);
System.out.printf(Locale.US, "%,d %n", 10000);
System.out.printf(Locale.ITALY, "%,d %n", 10000);
System.out.printf("%f%n", 5.1473);
System.out.printf("'%5.2f'%n", 5.1473);
System.out.printf("'%5.2e'%n", 5.1473);
}
private static void printfBoolean() {
System.out.printf("%b%n", null);
System.out.printf("%B%n", false);
System.out.printf("%B%n", 5.3);
System.out.printf("%b%n", "random text");
}
private static void printfDateTime() {
Date date = new Date();
System.out.printf("%tT%n", date);
System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date, date);
System.out.printf("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n", date);
System.out.printf("%1$tA %1$tB %1$tY %n", date);
System.out.printf("%1$td.%1$tm.%1$ty %n", date);
}
}
@@ -0,0 +1,15 @@
package com.baeldung.resourcebundle;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
public class ExampleControl extends ResourceBundle.Control {
@Override
public List<Locale> getCandidateLocales(String s, Locale locale) {
return Arrays.asList(new Locale("pl", "PL"));
}
}
@@ -0,0 +1,14 @@
package com.baeldung.resourcebundle;
import java.util.ListResourceBundle;
public class ExampleResource extends ListResourceBundle {
@Override
protected Object[][] getContents() {
return new Object[][] {
{ "greeting", "hello" }
};
}
}
@@ -0,0 +1,15 @@
package com.baeldung.resourcebundle;
import java.util.ListResourceBundle;
public class ExampleResource_pl extends ListResourceBundle {
@Override
protected Object[][] getContents() {
return new Object[][] {
{ "greeting", "cześć" },
{ "language", "polish" },
};
}
}
@@ -0,0 +1,17 @@
package com.baeldung.resourcebundle;
import java.math.BigDecimal;
import java.util.ListResourceBundle;
public class ExampleResource_pl_PL extends ListResourceBundle {
@Override
protected Object[][] getContents() {
return new Object[][] {
{ "currency", "polish zloty" },
{ "toUsdRate", new BigDecimal("3.401") },
{ "cities", new String[] { "Warsaw", "Cracow" } }
};
}
}
@@ -0,0 +1,15 @@
package com.baeldung.serialization;
public class Address {
private int houseNumber;
public int getHouseNumber() {
return houseNumber;
}
public void setHouseNumber(int houseNumber) {
this.houseNumber = houseNumber;
}
}
@@ -0,0 +1,44 @@
package com.baeldung.serialization;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private transient Address address; // not an serializable object
private Person person;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.defaultWriteObject();
oos.writeObject(address.getHouseNumber());
}
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
ois.defaultReadObject();
Integer houseNumber = (Integer) ois.readObject();
Address a = new Address();
a.setHouseNumber(houseNumber);
this.setAddress(a);
}
}
@@ -0,0 +1,30 @@
package com.baeldung.serialization;
import java.io.Serializable;
public class Person implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,33 @@
package com.baeldung.staticclass;
public class Pizza {
private static String cookedCount;
private boolean isThinCrust;
// Accessible globally
public static class PizzaSalesCounter {
private static String orderedCount;
public static String deliveredCount;
PizzaSalesCounter() {
System.out.println("Static field of enclosing class is "
+ Pizza.cookedCount);
System.out.println("Non-static field of enclosing class is "
+ new Pizza().isThinCrust);
}
}
Pizza() {
System.out.println("Non private static field of static class is "
+ PizzaSalesCounter.deliveredCount);
System.out.println("Private static field of static class is "
+ PizzaSalesCounter.orderedCount);
}
public static void main(String[] a) {
// Create instance of the static class without an instance of enclosing class
new Pizza.PizzaSalesCounter();
}
}
@@ -0,0 +1,19 @@
package com.baeldung.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesLoader {
public static Properties loadProperties(String resourceFileName) throws IOException {
Properties configuration = new Properties();
InputStream inputStream = PropertiesLoader.class
.getClassLoader()
.getResourceAsStream(resourceFileName);
configuration.load(inputStream);
inputStream.close();
return configuration;
}
}
@@ -0,0 +1,117 @@
package com.baeldung.uuid;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
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 4 UUID Generation
*/
public static UUID generateType4UUID() {
UUID uuid = UUID.randomUUID();
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
*/
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;
}
public static UUID type5UUIDFromBytes(byte[] name) {
MessageDigest md;
try {
md = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException nsae) {
throw new InternalError("SHA-1 not supported", nsae);
}
byte[] bytes = Arrays.copyOfRange(md.digest(name), 0, 16);
bytes[6] &= 0x0f; /* clear version */
bytes[6] |= 0x50; /* set to version 5 */
bytes[8] &= 0x3f; /* clear variant */
bytes[8] |= 0x80; /* set to IETF variant */
return constructType5UUID(bytes);
}
private static UUID constructType5UUID(byte[] data) {
long msb = 0;
long lsb = 0;
assert data.length == 16 : "data must be 16 bytes in length";
for (int i = 0; i < 8; i++)
msb = (msb << 8) | (data[i] & 0xff);
for (int i = 8; i < 16; i++)
lsb = (lsb << 8) | (data[i] & 0xff);
return new UUID(msb, lsb);
}
/**
* Unique Keys Generation Using Message Digest and Type 4 UUID
*
* @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"));
String digest = bytesToHex(salt.digest());
return digest;
}
public 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;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
}
@@ -0,0 +1,2 @@
-d javac-target -verbose
com/baeldung/javac/Data.java
@@ -0,0 +1,2 @@
-d javac-target
-verbose
@@ -0,0 +1 @@
com/baeldung/javac/Data.java
@@ -0,0 +1,3 @@
-d javac-target
-Xlint:rawtypes,unchecked,static,cast,serial,fallthrough
com/baeldung/javac/Data.java
@@ -0,0 +1,9 @@
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
@@ -0,0 +1,10 @@
package org.baeldung.executable;
import javax.swing.*;
public class ExecutableMavenJar {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1);
}
}
@@ -0,0 +1,5 @@
Agent-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent
Can-Redefine-Classes: true
Can-Retransform-Classes: true
Premain-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent
Main-Class: com.baeldung.instrumentation.application.Launcher
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd" version="2.1">
<!-- JDO tutorial "unit" -->
<persistence-unit name="Tutorial">
<exclude-unlisted-classes/>
<properties>
<property name="javax.jdo.PersistenceManagerFactoryClass" value="org.datanucleus.api.jdo.JDOPersistenceManagerFactory"/>
<property name="javax.jdo.option.ConnectionURL" value="jdbc:h2:mem:mypersistence"/>
<property name="javax.jdo.option.ConnectionDriverName" value="org.h2.Driver"/>
<property name="javax.jdo.option.ConnectionUserName" value="sa"/>
<property name="javax.jdo.option.ConnectionPassword" value=""/>
<property name="datanucleus.schema.autoCreateAll" value="true"/>
</properties>
</persistence-unit>
</persistence>
@@ -0,0 +1,3 @@
UK
US
Germany
@@ -0,0 +1,6 @@
dataSourceClassName=//TBD
dataSource.user=//TBD
dataSource.password=//TBD
dataSource.databaseName=//TBD
dataSource.portNumber=//TBD
dataSource.serverName=//TBD
@@ -0,0 +1,10 @@
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
This is line 10
@@ -0,0 +1,15 @@
var first = {
name: "Whiskey",
age: 5
};
var second = {
volume: 100
};
Object.bindProperties(first, second);
print(first.volume);
second.volume = 1000;
print(first.volume);
@@ -0,0 +1 @@
print(__FILE__, __LINE__, __DIR__);
@@ -0,0 +1,19 @@
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;
@@ -0,0 +1,11 @@
var demo = {
__noSuchProperty__: function (propName) {
print("Accessed non-existing property: " + propName);
},
__noSuchMethod__: function (methodName) {
print("Invoked non-existing method: " + methodName);
}
};
demo;
@@ -0,0 +1 @@
function increment(num) ++num;
@@ -0,0 +1,2 @@
print(" hello world".trimLeft());
print("hello world ".trimRight());
@@ -0,0 +1,9 @@
function arrays(arr) {
var javaIntArray = Java.to(arr, "int[]");
print(javaIntArray[0]);
print(javaIntArray[1]);
print(javaIntArray[2]);
}
arrays([100, "1654", true]);
@@ -0,0 +1,6 @@
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
@@ -0,0 +1,9 @@
# Root logger
log4j.rootLogger=INFO, file, stdout
# Write to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

@@ -0,0 +1,6 @@
# Buttons
cancelButton=cancel
continueButton continue
! Labels
helloLabel:hello
@@ -0,0 +1 @@
deleteButton=delete
@@ -0,0 +1,3 @@
backButton=cofnij
helloLabel=cze\u015b\u0107
helloLabelNoEncoding=cześć
@@ -0,0 +1,20 @@
package com.baeldung.abstractclasses.test;
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
import com.baeldung.abstractclasses.filereaders.LowercaseFileReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class LowercaseFileReaderUnitTest {
@Test
public void givenLowercaseFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
Path path = Paths.get(getClass().getClassLoader().getResource("files/test.txt").toURI());
BaseFileReader lowercaseFileReader = new LowercaseFileReader(path);
assertThat(lowercaseFileReader.readFile()).isInstanceOf(List.class);
}
}
@@ -0,0 +1,20 @@
package com.baeldung.abstractclasses.test;
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
import com.baeldung.abstractclasses.filereaders.UppercaseFileReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class UppercaseFileReaderUnitTest {
@Test
public void givenUppercaseFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
Path path = Paths.get(getClass().getClassLoader().getResource("files/test.txt").toURI());
BaseFileReader uppercaseFileReader = new UppercaseFileReader(path);
assertThat(uppercaseFileReader.readFile()).isInstanceOf(List.class);
}
}
@@ -0,0 +1,20 @@
package com.baeldung.asciiart;
import java.awt.Font;
import org.junit.Test;
import com.baeldung.asciiart.AsciiArt.Settings;
public class AsciiArtIntegrationTest {
@Test
public void givenTextWithAsciiCharacterAndSettings_shouldPrintAsciiArt() {
AsciiArt asciiArt = new AsciiArt();
String text = "BAELDUNG";
Settings settings = asciiArt.new Settings(new Font("SansSerif", Font.BOLD, 24), text.length() * 30, 30); // 30 pixel width per character
asciiArt.drawString(text, "*", settings);
}
}
@@ -0,0 +1,81 @@
package com.baeldung.bitwiseoperator.test;
import static org.junit.Assert.assertEquals;
import org.junit.jupiter.api.Test;
public class BitwiseOperatorUnitTest {
@Test
public void givenTwoIntegers_whenAndOperator_thenNewDecimalNumber() {
int value1 = 6;
int value2 = 5;
int result = value1 & value2;
assertEquals(4, result);
}
@Test
public void givenTwoIntegers_whenOrOperator_thenNewDecimalNumber() {
int value1 = 6;
int value2 = 5;
int result = value1 | value2;
assertEquals(7, result);
}
@Test
public void givenTwoIntegers_whenXorOperator_thenNewDecimalNumber() {
int value1 = 6;
int value2 = 5;
int result = value1 ^ value2;
assertEquals(3, result);
}
@Test
public void givenOneInteger_whenNotOperator_thenNewDecimalNumber() {
int value1 = 6;
int result = ~value1;
assertEquals(result, -7);
}
@Test
public void givenOnePositiveInteger_whenSignedRightShiftOperator_thenNewDecimalNumber() {
int value = 12;
int rightShift = value >> 2;
assertEquals(3, rightShift);
}
@Test
public void givenOneNegativeInteger_whenSignedRightShiftOperator_thenNewDecimalNumber() {
int value = -12;
int rightShift = value >> 2;
assertEquals(-3, rightShift);
}
@Test
public void givenOnePositiveInteger_whenLeftShiftOperator_thenNewDecimalNumber() {
int value = 12;
int leftShift = value << 2;
assertEquals(48, leftShift);
}
@Test
public void givenOneNegativeInteger_whenLeftShiftOperator_thenNewDecimalNumber() {
int value = -12;
int leftShift = value << 2;
assertEquals(-48, leftShift);
}
@Test
public void givenOnePositiveInteger_whenUnsignedRightShiftOperator_thenNewDecimalNumber() {
int value = 12;
int unsignedRightShift = value >>> 2;
assertEquals(3, unsignedRightShift);
}
@Test
public void givenOneNegativeInteger_whenUnsignedRightShiftOperator_thenNewDecimalNumber() {
int value = -12;
int unsignedRightShift = value >>> 2;
assertEquals(1073741821, unsignedRightShift);
}
}
@@ -0,0 +1,68 @@
package com.baeldung.deserialization;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.InvalidClassException;
import org.junit.Ignore;
import org.junit.Test;
public class DeserializationUnitTest {
private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAdMuxAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADWxpZ2h0bmluZ1BvcnRxAH4AAUwAD3RodW5kZXJib2x0UG9ydHEAfgABeHB0ABFoZWFkcGhvbmVQb3J0MjAyMHQAEWxpZ2h0bmluZ1BvcnQyMDIwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA";
private static long userDefinedSerialVersionUID = 1234567L;
/**
* Tests the deserialization of the original "AppleProduct" (no exceptions are thrown)
* @throws ClassNotFoundException
* @throws IOException
*/
@Test
public void testDeserializeObj_compatible() throws IOException, ClassNotFoundException {
assertEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
AppleProduct macBook = new AppleProduct();
macBook.headphonePort = "headphonePort2020";
macBook.thunderboltPort = "thunderboltPort2020";
macBook.lightningPort = "lightningPort2020";
// serializes the "AppleProduct" object
String serializedProduct = SerializationUtility.serializeObjectToString(macBook);
// deserializes the "AppleProduct" object
AppleProduct deserializedProduct = (AppleProduct) DeserializationUtility.deSerializeObjectFromString(serializedProduct);
assertTrue(deserializedProduct.headphonePort.equalsIgnoreCase(macBook.headphonePort));
assertTrue(deserializedProduct.thunderboltPort.equalsIgnoreCase(macBook.thunderboltPort));
assertTrue(deserializedProduct.lightningPort.equalsIgnoreCase(macBook.lightningPort));
}
/**
* Tests the deserialization of the modified (non-compatible) "AppleProduct".
* The test should result in an InvalidClassException being thrown.
*
* Note: to run this test:
* 1. Modify the value of the serialVersionUID identifier in AppleProduct.java
* 2. Remove the @Ignore annotation
* 3. Run the test individually (do not run the entire set of tests)
* 4. Revert the changes made in 1 & 2 (so that you're able to re-run the tests successfully)
*
* @throws ClassNotFoundException
* @throws IOException
*/
@Ignore
@Test(expected = InvalidClassException.class)
public void testDeserializeObj_incompatible() throws ClassNotFoundException, IOException {
assertNotEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
// attempts to deserialize the "AppleProduct" object
DeserializationUtility.deSerializeObjectFromString(serializedObj);
}
}
@@ -0,0 +1,124 @@
package com.baeldung.encoding;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
public class CharacterEncodingExamplesUnitTest {
@Test
public void givenTextFile_whenCalledWithEncodingASCII_thenProduceIncorrectResult() throws IOException {
Assert.assertEquals(
CharacterEncodingExamples.readFile(
"src/test/resources/encoding.txt", "US-ASCII"),
"The faade pattern is a software-design pattern commonly used with object-oriented programming.");
}
@Test
public void givenTextFile_whenCalledWithEncodingUTF8_thenProduceCorrectResult() throws IOException {
Assert.assertEquals(
CharacterEncodingExamples.readFile(
"src/test/resources/encoding.txt", "UTF-8"),
"The façade pattern is a software-design pattern commonly used with object-oriented programming.");
}
@Test
public void givenCharacterA_whenConvertedtoBinaryWithEncodingASCII_thenProduceResult() throws IOException {
Assert.assertEquals(
CharacterEncodingExamples.convertToBinary("A", "US-ASCII"),
"1000001 ");
}
@Test
public void givenCharacterA_whenConvertedtoBinaryWithEncodingUTF8_thenProduceResult() throws IOException {
Assert.assertEquals(
CharacterEncodingExamples.convertToBinary("A", "UTF-8"),
"1000001 ");
}
@Test
public void givenCharacterCh_whenConvertedtoBinaryWithEncodingBig5_thenProduceResult() throws IOException {
Assert.assertEquals(
CharacterEncodingExamples.convertToBinary("", "Big5"),
"10111011 1111001 ");
}
@Test
public void givenCharacterCh_whenConvertedtoBinaryWithEncodingUTF8_thenProduceResult() throws IOException {
Assert.assertEquals(
CharacterEncodingExamples.convertToBinary("", "UTF-8"),
"11101000 10101010 10011110 ");
}
@Test
public void givenCharacterCh_whenConvertedtoBinaryWithEncodingUTF32_thenProduceResult() throws IOException {
Assert.assertEquals(
CharacterEncodingExamples.convertToBinary("", "UTF-32"),
"0 0 10001010 10011110 ");
}
@Test
public void givenUTF8String_whenDecodeByUS_ASCII_thenIgnoreMalformedInputSequence() throws IOException {
Assertions.assertEquals("The faade pattern is a software design pattern.", CharacterEncodingExamples.decodeText("The façade pattern is a software design pattern.", StandardCharsets.US_ASCII, CodingErrorAction.IGNORE));
}
@Test
public void givenUTF8String_whenDecodeByUS_ASCII_thenReplaceMalformedInputSequence() throws IOException {
Assertions.assertEquals(
"The faade pattern is a software design pattern.",
CharacterEncodingExamples.decodeText(
"The façade pattern is a software design pattern.",
StandardCharsets.US_ASCII,
CodingErrorAction.REPLACE));
}
@Test
public void givenUTF8String_whenDecodeByUS_ASCII_thenReportMalformedInputSequence() {
Assertions.assertThrows(
MalformedInputException.class,
() -> CharacterEncodingExamples.decodeText(
"The façade pattern is a software design pattern.",
StandardCharsets.US_ASCII,
CodingErrorAction.REPORT));
}
@Test
public void givenTextFile_whenLoopOverAllCandidateEncodings_thenProduceSuitableCandidateEncodings() {
Path path = Paths.get("src/test/resources/encoding.txt");
List<Charset> allCandidateCharSets = Arrays.asList(
StandardCharsets.US_ASCII, StandardCharsets.UTF_8, StandardCharsets.ISO_8859_1);
List<Charset> suitableCharsets = new ArrayList<>();
allCandidateCharSets.forEach(charset -> {
try {
CharsetDecoder charsetDecoder = charset.newDecoder().onMalformedInput(CodingErrorAction.REPORT);
Reader reader = new InputStreamReader(Files.newInputStream(path), charsetDecoder);
BufferedReader bufferedReader = new BufferedReader(reader);
bufferedReader.readLine();
suitableCharsets.add(charset);
} catch (MalformedInputException ignored) {
} catch (IOException ex) {
ex.printStackTrace();
}
});
Assertions.assertEquals(suitableCharsets, Arrays.asList(StandardCharsets.UTF_8, StandardCharsets.ISO_8859_1));
}
}
@@ -0,0 +1,71 @@
package com.baeldung.externalizable;
import org.junit.Test;
import java.io.*;
import static org.junit.Assert.assertTrue;
public class ExternalizableUnitTest {
private final static String OUTPUT_FILE = "externalizable.txt";
@Test
public void whenSerializing_thenUseExternalizable() throws IOException, ClassNotFoundException {
Country c = new Country();
c.setCapital("Yerevan");
c.setCode(374);
c.setName("Armenia");
FileOutputStream fileOutputStream = new FileOutputStream(OUTPUT_FILE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
c.writeExternal(objectOutputStream);
objectOutputStream.flush();
objectOutputStream.close();
fileOutputStream.close();
FileInputStream fileInputStream = new FileInputStream(OUTPUT_FILE);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Country c2 = new Country();
c2.readExternal(objectInputStream);
objectInputStream.close();
fileInputStream.close();
assertTrue(c2.getCode() == c.getCode());
assertTrue(c2.getName().equals(c.getName()));
}
@Test
public void whenInheritanceSerialization_then_UseExternalizable() throws IOException, ClassNotFoundException {
Region r = new Region();
r.setCapital("Yerevan");
r.setCode(374);
r.setName("Armenia");
r.setClimate("Mediterranean");
r.setPopulation(120.000);
FileOutputStream fileOutputStream = new FileOutputStream(OUTPUT_FILE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
r.writeExternal(objectOutputStream);
objectOutputStream.flush();
objectOutputStream.close();
fileOutputStream.close();
FileInputStream fileInputStream = new FileInputStream(OUTPUT_FILE);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Region r2 = new Region();
r2.readExternal(objectInputStream);
objectInputStream.close();
fileInputStream.close();
assertTrue(r2.getPopulation() == null);
}
}
@@ -0,0 +1,19 @@
package com.baeldung.fileparser;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.List;
import org.junit.Test;
public class BufferedReaderUnitTest {
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
@Test
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
List<String> lines = BufferedReaderExample.generateArrayListFromFile(TEXT_FILENAME);
assertTrue("File does not has 2 lines", lines.size() == 2);
}
}
@@ -0,0 +1,19 @@
package com.baeldung.fileparser;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.List;
import org.junit.Test;
public class FileReaderUnitTest {
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
@Test
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
List<String> lines = FileReaderExample.generateArrayListFromFile(TEXT_FILENAME);
assertTrue("File does not has 2 lines", lines.size() == 2);
}
}
@@ -0,0 +1,19 @@
package com.baeldung.fileparser;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.List;
import org.junit.Test;
public class FilesReadAllLinesUnitTest {
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
@Test
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
List<String> lines = FilesReadLinesExample.generateArrayListFromFile(TEXT_FILENAME);
assertTrue("File does not has 2 lines", lines.size() == 2);
}
}
@@ -0,0 +1,19 @@
package com.baeldung.fileparser;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.List;
import org.junit.Test;
public class ScannerIntUnitTest {
protected static final String NUMBER_FILENAME = "src/test/resources/sampleNumberFile.txt";
@Test
public void whenParsingExistingTextFile_thenGetIntArrayList() throws IOException {
List<Integer> numbers = ScannerIntExample.generateArrayListFromFile(NUMBER_FILENAME);
assertTrue("File does not has 2 lines", numbers.size() == 2);
}
}
@@ -0,0 +1,19 @@
package com.baeldung.fileparser;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.List;
import org.junit.Test;
public class ScannerStringUnitTest {
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
@Test
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
List<String> lines = ScannerStringExample.generateArrayListFromFile(TEXT_FILENAME);
assertTrue("File does not has 2 lines", lines.size() == 2);
}
}
@@ -0,0 +1,47 @@
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;
}
}
@@ -0,0 +1,46 @@
package com.baeldung.hexToAscii;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class HexToAsciiUnitTest {
@Test
public void whenHexToAscii() {
String asciiString = "http://www.baeldung.com/jackson-serialize-dates";
String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573";
assertEquals(asciiString, hexToAscii(hexEquivalent));
}
@Test
public void whenAsciiToHex() {
String asciiString = "http://www.baeldung.com/jackson-serialize-dates";
String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573";
assertEquals(hexEquivalent, asciiToHex(asciiString));
}
//
private static String asciiToHex(String asciiStr) {
char[] chars = asciiStr.toCharArray();
StringBuilder hex = new StringBuilder();
for (char ch : chars) {
hex.append(Integer.toHexString((int) ch));
}
return hex.toString();
}
private static String hexToAscii(String hexStr) {
StringBuilder output = new StringBuilder("");
for (int i = 0; i < hexStr.length(); i += 2) {
String str = hexStr.substring(i, i + 2);
output.append((char) Integer.parseInt(str, 16));
}
return output.toString();
}
}
@@ -0,0 +1,2 @@
### Relevant Articles:
- [Convert Hex to ASCII in Java](http://www.baeldung.com/java-convert-hex-to-ascii)
@@ -0,0 +1,43 @@
package com.baeldung.java.currentmethod;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* The class presents various ways of finding the name of currently executed method.
*/
public class CurrentlyExecutedMethodFinderUnitTest {
@Test
public void givenCurrentThread_whenGetStackTrace_thenFindMethod() {
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
assertEquals("givenCurrentThread_whenGetStackTrace_thenFindMethod", stackTrace[1].getMethodName());
}
@Test
public void givenException_whenGetStackTrace_thenFindMethod() {
String methodName = new Exception().getStackTrace()[0].getMethodName();
assertEquals("givenException_whenGetStackTrace_thenFindMethod", methodName);
}
@Test
public void givenThrowable_whenGetStacktrace_thenFindMethod() {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
assertEquals("givenThrowable_whenGetStacktrace_thenFindMethod", stackTrace[0].getMethodName());
}
@Test
public void givenObject_whenGetEnclosingMethod_thenFindMethod() {
String methodName = new Object() {}.getClass().getEnclosingMethod().getName();
assertEquals("givenObject_whenGetEnclosingMethod_thenFindMethod", methodName);
}
@Test
public void givenLocal_whenGetEnclosingMethod_thenFindMethod() {
class Local {};
String methodName = Local.class.getEnclosingMethod().getName();
assertEquals("givenLocal_whenGetEnclosingMethod_thenFindMethod", methodName);
}
}
@@ -0,0 +1,171 @@
package com.baeldung.java.properties;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import org.junit.Test;
public class PropertiesUnitTest {
@Test
public void givenPropertyValue_whenPropertiesFileLoaded_thenCorrect() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
String catalogConfigPath = rootPath + "catalog";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));
Properties catalogProps = new Properties();
catalogProps.load(new FileInputStream(catalogConfigPath));
String appVersion = appProps.getProperty("version");
assertEquals("1.0", appVersion);
assertEquals("files", catalogProps.getProperty("c1"));
}
@Test
public void givenPropertyValue_whenXMLPropertiesFileLoaded_thenCorrect() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String iconConfigPath = rootPath + "icons.xml";
Properties iconProps = new Properties();
iconProps.loadFromXML(new FileInputStream(iconConfigPath));
assertEquals("icon1.jpg", iconProps.getProperty("fileIcon"));
}
@Test
public void givenAbsentProperty_whenPropertiesFileLoaded_thenReturnsDefault() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));
String appVersion = appProps.getProperty("version");
String appName = appProps.getProperty("name", "defaultName");
String appGroup = appProps.getProperty("group", "baeldung");
String appDownloadAddr = appProps.getProperty("downloadAddr");
assertEquals("1.0", appVersion);
assertEquals("TestApp", appName);
assertEquals("baeldung", appGroup);
assertNull(appDownloadAddr);
}
@Test(expected = Exception.class)
public void givenImproperObjectCasting_whenPropertiesFileLoaded_thenThrowsException() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));
float appVerFloat = (float) appProps.get("version");
}
@Test
public void givenPropertyValue_whenPropertiesSet_thenCorrect() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));
appProps.setProperty("name", "NewAppName");
appProps.setProperty("downloadAddr", "www.baeldung.com/downloads");
String newAppName = appProps.getProperty("name");
assertEquals("NewAppName", newAppName);
String newAppDownloadAddr = appProps.getProperty("downloadAddr");
assertEquals("www.baeldung.com/downloads", newAppDownloadAddr);
}
@Test
public void givenPropertyValueNull_whenPropertiesRemoved_thenCorrect() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));
String versionBeforeRemoval = appProps.getProperty("version");
assertEquals("1.0", versionBeforeRemoval);
appProps.remove("version");
String versionAfterRemoval = appProps.getProperty("version");
assertNull(versionAfterRemoval);
}
@Test
public void whenPropertiesStoredInFile_thenCorrect() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));
String newAppConfigPropertiesFile = rootPath + "newApp.properties";
appProps.store(new FileWriter(newAppConfigPropertiesFile), "store to properties file");
String newAppConfigXmlFile = rootPath + "newApp.xml";
appProps.storeToXML(new FileOutputStream(newAppConfigXmlFile), "store to xml file");
}
@Test
public void givenPropertyValueAbsent_LoadsValuesFromDefaultProperties() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String defaultConfigPath = rootPath + "default.properties";
Properties defaultProps = new Properties();
defaultProps.load(new FileInputStream(defaultConfigPath));
String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties(defaultProps);
appProps.load(new FileInputStream(appConfigPath));
String appName = appProps.getProperty("name");
String appVersion = appProps.getProperty("version");
String defaultSite = appProps.getProperty("site");
assertEquals("1.0", appVersion);
assertEquals("TestApp", appName);
assertEquals("www.google.com", defaultSite);
}
@Test
public void givenPropertiesSize_whenPropertyFileLoaded_thenCorrect() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appPropsPath = rootPath + "app.properties";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appPropsPath));
appProps.list(System.out); // list all key-value pairs
Enumeration<Object> valueEnumeration = appProps.elements();
while (valueEnumeration.hasMoreElements()) {
System.out.println(valueEnumeration.nextElement());
}
Enumeration<Object> keyEnumeration = appProps.keys();
while (keyEnumeration.hasMoreElements()) {
System.out.println(keyEnumeration.nextElement());
}
int size = appProps.size();
assertEquals(3, size);
}
}
@@ -0,0 +1,501 @@
package com.baeldung.java.regex;
import static org.junit.Assert.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
public class RegexUnitTest {
private static Pattern pattern;
private static Matcher matcher;
@Test
public void givenText_whenSimpleRegexMatches_thenCorrect() {
Pattern pattern = Pattern.compile("foo");
Matcher matcher = pattern.matcher("foo");
assertTrue(matcher.find());
}
@Test
public void givenText_whenSimpleRegexMatchesTwice_thenCorrect() {
Pattern pattern = Pattern.compile("foo");
Matcher matcher = pattern.matcher("foofoo");
int matches = 0;
while (matcher.find())
matches++;
assertEquals(matches, 2);
}
@Test
public void givenText_whenMatchesWithDotMetach_thenCorrect() {
int matches = runTest(".", "foo");
assertTrue(matches > 0);
}
@Test
public void givenRepeatedText_whenMatchesOnceWithDotMetach_thenCorrect() {
int matches = runTest("foo.", "foofoo");
assertTrue(matches > 0);
assertEquals(matches, 1);
}
@Test
public void givenORSet_whenMatchesAny_thenCorrect() {
int matches = runTest("[abc]", "b");
assertTrue(matches > 0);
assertEquals(matches, 1);
}
@Test
public void givenORSet_whenMatchesAnyAndAll_thenCorrect() {
int matches = runTest("[abc]", "cab");
assertTrue(matches > 0);
assertEquals(matches, 3);
}
@Test
public void givenORSet_whenMatchesAllCombinations_thenCorrect() {
int matches = runTest("[bcr]at", "bat cat rat");
assertTrue(matches > 0);
assertEquals(matches, 3);
}
@Test
public void givenNORSet_whenMatchesNon_thenCorrect() {
int matches = runTest("[^abc]", "g");
assertTrue(matches > 0);
}
@Test
public void givenNORSet_whenMatchesAllExceptElements_thenCorrect() {
int matches = runTest("[^bcr]at", "sat mat eat");
assertTrue(matches > 0);
}
@Test
public void givenUpperCaseRange_whenMatchesUpperCase_thenCorrect() {
int matches = runTest("[A-Z]", "Two Uppercase alphabets 34 overall");
assertTrue(matches > 0);
assertEquals(matches, 2);
}
@Test
public void givenLowerCaseRange_whenMatchesLowerCase_thenCorrect() {
int matches = runTest("[a-z]", "Two Uppercase alphabets 34 overall");
assertTrue(matches > 0);
assertEquals(matches, 26);
}
@Test
public void givenBothLowerAndUpperCaseRange_whenMatchesAllLetters_thenCorrect() {
int matches = runTest("[a-zA-Z]", "Two Uppercase alphabets 34 overall");
assertTrue(matches > 0);
assertEquals(matches, 28);
}
@Test
public void givenNumberRange_whenMatchesAccurately_thenCorrect() {
int matches = runTest("[1-5]", "Two Uppercase alphabets 34 overall");
assertTrue(matches > 0);
assertEquals(matches, 2);
}
@Test
public void givenNumberRange_whenMatchesAccurately_thenCorrect2() {
int matches = runTest("[30-35]", "Two Uppercase alphabets 34 overall");
assertTrue(matches > 0);
assertEquals(matches, 1);
}
@Test
public void givenTwoSets_whenMatchesUnion_thenCorrect() {
int matches = runTest("[1-3[7-9]]", "123456789");
assertTrue(matches > 0);
assertEquals(matches, 6);
}
@Test
public void givenTwoSets_whenMatchesIntersection_thenCorrect() {
int matches = runTest("[1-6&&[3-9]]", "123456789");
assertTrue(matches > 0);
assertEquals(matches, 4);
}
@Test
public void givenSetWithSubtraction_whenMatchesAccurately_thenCorrect() {
int matches = runTest("[0-9&&[^2468]]", "123456789");
assertTrue(matches > 0);
assertEquals(matches, 5);
}
@Test
public void givenDigits_whenMatches_thenCorrect() {
int matches = runTest("\\d", "123");
assertTrue(matches > 0);
assertEquals(matches, 3);
}
@Test
public void givenNonDigits_whenMatches_thenCorrect() {
int matches = runTest("\\D", "a6c");
assertTrue(matches > 0);
assertEquals(matches, 2);
}
@Test
public void givenWhiteSpace_whenMatches_thenCorrect() {
int matches = runTest("\\s", "a c");
assertTrue(matches > 0);
assertEquals(matches, 1);
}
@Test
public void givenNonWhiteSpace_whenMatches_thenCorrect() {
int matches = runTest("\\S", "a c");
assertTrue(matches > 0);
assertEquals(matches, 2);
}
@Test
public void givenWordCharacter_whenMatches_thenCorrect() {
int matches = runTest("\\w", "hi!");
assertTrue(matches > 0);
assertEquals(matches, 2);
}
@Test
public void givenNonWordCharacter_whenMatches_thenCorrect() {
int matches = runTest("\\W", "hi!");
assertTrue(matches > 0);
assertEquals(matches, 1);
}
@Test
public void givenZeroOrOneQuantifier_whenMatches_thenCorrect() {
int matches = runTest("\\a?", "hi");
assertTrue(matches > 0);
assertEquals(matches, 3);
}
@Test
public void givenZeroOrOneQuantifier_whenMatches_thenCorrect2() {
int matches = runTest("\\a{0,1}", "hi");
assertTrue(matches > 0);
assertEquals(matches, 3);
}
@Test
public void givenZeroOrManyQuantifier_whenMatches_thenCorrect() {
int matches = runTest("\\a*", "hi");
assertTrue(matches > 0);
assertEquals(matches, 3);
}
@Test
public void givenZeroOrManyQuantifier_whenMatches_thenCorrect2() {
int matches = runTest("\\a{0,}", "hi");
assertTrue(matches > 0);
assertEquals(matches, 3);
}
@Test
public void givenOneOrManyQuantifier_whenMatches_thenCorrect() {
int matches = runTest("\\a+", "hi");
assertFalse(matches > 0);
}
@Test
public void givenOneOrManyQuantifier_whenMatches_thenCorrect2() {
int matches = runTest("\\a{1,}", "hi");
assertFalse(matches > 0);
}
@Test
public void givenBraceQuantifier_whenMatches_thenCorrect() {
int matches = runTest("a{3}", "aaaaaa");
assertTrue(matches > 0);
assertEquals(matches, 2);
}
@Test
public void givenBraceQuantifier_whenFailsToMatch_thenCorrect() {
int matches = runTest("a{3}", "aa");
assertFalse(matches > 0);
}
@Test
public void givenBraceQuantifierWithRange_whenMatches_thenCorrect() {
int matches = runTest("a{2,3}", "aaaa");
assertTrue(matches > 0);
assertEquals(matches, 1);
}
@Test
public void givenBraceQuantifierWithRange_whenMatchesLazily_thenCorrect() {
int matches = runTest("a{2,3}?", "aaaa");
assertTrue(matches > 0);
assertEquals(matches, 2);
}
@Test
public void givenCapturingGroup_whenMatches_thenCorrect() {
int matches = runTest("(\\d\\d)", "12");
assertTrue(matches > 0);
assertEquals(matches, 1);
}
@Test
public void givenCapturingGroup_whenMatches_thenCorrect2() {
int matches = runTest("(\\d\\d)", "1212");
assertTrue(matches > 0);
assertEquals(matches, 2);
}
@Test
public void givenCapturingGroup_whenMatches_thenCorrect3() {
int matches = runTest("(\\d\\d)(\\d\\d)", "1212");
assertTrue(matches > 0);
assertEquals(matches, 1);
}
@Test
public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect() {
int matches = runTest("(\\d\\d)\\1", "1212");
assertTrue(matches > 0);
assertEquals(matches, 1);
}
@Test
public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect2() {
int matches = runTest("(\\d\\d)\\1\\1\\1", "12121212");
assertTrue(matches > 0);
assertEquals(matches, 1);
}
@Test
public void givenCapturingGroupAndWrongInput_whenMatchFailsWithBackReference_thenCorrect() {
int matches = runTest("(\\d\\d)\\1", "1213");
assertFalse(matches > 0);
}
@Test
public void givenText_whenMatchesAtBeginning_thenCorrect() {
int matches = runTest("^dog", "dogs are friendly");
assertTrue(matches > 0);
}
@Test
public void givenTextAndWrongInput_whenMatchFailsAtBeginning_thenCorrect() {
int matches = runTest("^dog", "are dogs are friendly?");
assertFalse(matches > 0);
}
@Test
public void givenText_whenMatchesAtEnd_thenCorrect() {
int matches = runTest("dog$", "Man's best friend is a dog");
assertTrue(matches > 0);
}
@Test
public void givenTextAndWrongInput_whenMatchFailsAtEnd_thenCorrect() {
int matches = runTest("dog$", "is a dog man's best friend?");
assertFalse(matches > 0);
}
@Test
public void givenText_whenMatchesAtWordBoundary_thenCorrect() {
int matches = runTest("\\bdog\\b", "a dog is friendly");
assertTrue(matches > 0);
}
@Test
public void givenText_whenMatchesAtWordBoundary_thenCorrect2() {
int matches = runTest("\\bdog\\b", "dog is man's best friend");
assertTrue(matches > 0);
}
@Test
public void givenWrongText_whenMatchFailsAtWordBoundary_thenCorrect() {
int matches = runTest("\\bdog\\b", "snoop dogg is a rapper");
assertFalse(matches > 0);
}
@Test
public void givenText_whenMatchesAtWordAndNonBoundary_thenCorrect() {
int matches = runTest("\\bdog\\B", "snoop dogg is a rapper");
assertTrue(matches > 0);
}
@Test
public void givenRegexWithoutCanonEq_whenMatchFailsOnEquivalentUnicode_thenCorrect() {
int matches = runTest("\u00E9", "\u0065\u0301");
assertFalse(matches > 0);
}
@Test
public void givenRegexWithCanonEq_whenMatchesOnEquivalentUnicode_thenCorrect() {
int matches = runTest("\u00E9", "\u0065\u0301", Pattern.CANON_EQ);
assertTrue(matches > 0);
}
@Test
public void givenRegexWithDefaultMatcher_whenMatchFailsOnDifferentCases_thenCorrect() {
int matches = runTest("dog", "This is a Dog");
assertFalse(matches > 0);
}
@Test
public void givenRegexWithCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() {
int matches = runTest("dog", "This is a Dog", Pattern.CASE_INSENSITIVE);
assertTrue(matches > 0);
}
@Test
public void givenRegexWithEmbeddedCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() {
int matches = runTest("(?i)dog", "This is a Dog");
assertTrue(matches > 0);
}
@Test
public void givenRegexWithComments_whenMatchFailsWithoutFlag_thenCorrect() {
int matches = runTest("dog$ #check for word dog at end of text", "This is a dog");
assertFalse(matches > 0);
}
@Test
public void givenRegexWithComments_whenMatchesWithFlag_thenCorrect() {
int matches = runTest("dog$ #check for word dog at end of text", "This is a dog", Pattern.COMMENTS);
assertTrue(matches > 0);
}
@Test
public void givenRegexWithComments_whenMatchesWithEmbeddedFlag_thenCorrect() {
int matches = runTest("(?x)dog$ #check for word dog at end of text", "This is a dog");
assertTrue(matches > 0);
}
@Test
public void givenRegexWithLineTerminator_whenMatchFails_thenCorrect() {
Pattern pattern = Pattern.compile("(.*)");
Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line");
matcher.find();
assertEquals("this is a text", matcher.group(1));
}
@Test
public void givenRegexWithLineTerminator_whenMatchesWithDotall_thenCorrect() {
Pattern pattern = Pattern.compile("(.*)", Pattern.DOTALL);
Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line");
matcher.find();
assertEquals("this is a text" + System.getProperty("line.separator") + " continued on another line", matcher.group(1));
}
@Test
public void givenRegexWithLineTerminator_whenMatchesWithEmbeddedDotall_thenCorrect() {
Pattern pattern = Pattern.compile("(?s)(.*)");
Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line");
matcher.find();
assertEquals("this is a text" + System.getProperty("line.separator") + " continued on another line", matcher.group(1));
}
@Test
public void givenRegex_whenMatchesWithoutLiteralFlag_thenCorrect() {
int matches = runTest("(.*)", "text");
assertTrue(matches > 0);
}
@Test
public void givenRegex_whenMatchFailsWithLiteralFlag_thenCorrect() {
int matches = runTest("(.*)", "text", Pattern.LITERAL);
assertFalse(matches > 0);
}
@Test
public void givenRegex_whenMatchesWithLiteralFlag_thenCorrect() {
int matches = runTest("(.*)", "text(.*)", Pattern.LITERAL);
assertTrue(matches > 0);
}
@Test
public void givenRegex_whenMatchFailsWithoutMultilineFlag_thenCorrect() {
int matches = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
assertFalse(matches > 0);
}
@Test
public void givenRegex_whenMatchesWithMultilineFlag_thenCorrect() {
int matches = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox", Pattern.MULTILINE);
assertTrue(matches > 0);
}
@Test
public void givenRegex_whenMatchesWithEmbeddedMultilineFlag_thenCorrect() {
int matches = runTest("(?m)dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
assertTrue(matches > 0);
}
@Test
public void givenMatch_whenGetsIndices_thenCorrect() {
Pattern pattern = Pattern.compile("dog");
Matcher matcher = pattern.matcher("This dog is mine");
matcher.find();
assertEquals(5, matcher.start());
assertEquals(8, matcher.end());
}
@Test
public void whenStudyMethodsWork_thenCorrect() {
Pattern pattern = Pattern.compile("dog");
Matcher matcher = pattern.matcher("dogs are friendly");
assertTrue(matcher.lookingAt());
assertFalse(matcher.matches());
}
@Test
public void whenMatchesStudyMethodWorks_thenCorrect() {
Pattern pattern = Pattern.compile("dog");
Matcher matcher = pattern.matcher("dog");
assertTrue(matcher.matches());
}
@Test
public void whenReplaceFirstWorks_thenCorrect() {
Pattern pattern = Pattern.compile("dog");
Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly");
String newStr = matcher.replaceFirst("cat");
assertEquals("cats are domestic animals, dogs are friendly", newStr);
}
@Test
public void whenReplaceAllWorks_thenCorrect() {
Pattern pattern = Pattern.compile("dog");
Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly");
String newStr = matcher.replaceAll("cat");
assertEquals("cats are domestic animals, cats are friendly", newStr);
}
public synchronized static int runTest(String regex, String text) {
pattern = Pattern.compile(regex);
matcher = pattern.matcher(text);
int matches = 0;
while (matcher.find())
matches++;
return matches;
}
public synchronized static int runTest(String regex, String text, int flags) {
pattern = Pattern.compile(regex, flags);
matcher = pattern.matcher(text);
int matches = 0;
while (matcher.find())
matches++;
return matches;
}
}
@@ -0,0 +1,50 @@
package com.baeldung.java8;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
public class Java8MapAndFlatMap {
@Test
public void givenStream_whenCalledMap_thenProduceList() {
List<String> myList = Stream.of("a", "b")
.map(String::toUpperCase)
.collect(Collectors.toList());
assertEquals(asList("A", "B"), myList);
}
@Test
public void givenStream_whenCalledFlatMap_thenProduceFlattenedList() throws Exception {
List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b"));
System.out.println(list);
System.out.println(list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList()));
}
@Test
public void givenOptional_whenCalledMap_thenProduceOptional() {
Optional<String> s = Optional.of("test");
assertEquals(Optional.of("TEST"), s.map(String::toUpperCase));
}
@Test
public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() {
assertEquals(Optional.of(Optional.of("STRING")), Optional.of("string")
.map(s -> Optional.of("STRING")));
assertEquals(Optional.of("STRING"), Optional.of("string")
.flatMap(s -> Optional.of("STRING")));
}
}

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