[BAEL-9555] - Created a core-java-modules folder

This commit is contained in:
amit2103
2019-05-05 17:22:09 +05:30
parent 8b63b0d90a
commit 3bae5e5334
1480 changed files with 25600 additions and 5594 deletions

25
core-java-modules/core-java/.gitignore vendored Normal file
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

View File

@@ -0,0 +1,53 @@
=========
## Core Java Cookbooks and Examples
### Relevant Articles:
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java)
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)
- [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)
- [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java)
- [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)
- [JVM Log Forging](http://www.baeldung.com/jvm-log-forging)
- [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)
- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os)
- [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)
- [Class Loaders in Java](http://www.baeldung.com/java-classloaders)
- [Guide to the Java Clock Class](http://www.baeldung.com/java-clock)
- [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)
- [Guide to Java Instrumentation](http://www.baeldung.com/java-instrumentation)
- [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)
- [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)

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.

View File

@@ -0,0 +1,492 @@
<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>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<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>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.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>
<dependency>
<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>${esapi.version}</version>
</dependency>
<dependency>
<groupId>com.sun.messaging.mq</groupId>
<artifactId>fscontext</artifactId>
<version>${fscontext.version}</version>
</dependency>
<dependency>
<groupId>com.codepoetics</groupId>
<artifactId>protonpack</artifactId>
<version>${protonpack.version}</version>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>${streamex.version}</version>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>${vavr.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator-annprocess.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2database.version}</version>
</dependency>
<!-- instrumentation -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>${javaassist.version}</version>
</dependency>
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>${sun.tools.version}</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</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>
<!-- marshalling -->
<gson.version>2.8.2</gson.version>
<!-- util -->
<commons-lang3.version>3.5</commons-lang3.version>
<commons-io.version>2.5</commons-io.version>
<commons-math3.version>3.6.1</commons-math3.version>
<decimal4j.version>1.0.3</decimal4j.version>
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<fscontext.version>4.6-b01</fscontext.version>
<protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<vavr.version>0.9.0</vavr.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
<!-- maven plugins -->
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<javamoney.moneta.version>1.1</javamoney.moneta.version>
<h2database.version>1.4.197</h2database.version>
<esapi.version>2.1.0.1</esapi.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.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>
<icu4j.version>61.1</icu4j.version>
<!-- instrumentation -->
<javaassist.version>3.21.0-GA</javaassist.version>
<sun.tools.version>1.8.0</sun.tools.version>
</properties>
</project>

View File

@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@@ -0,0 +1 @@
### Relevant Articles:

View File

@@ -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());
}
}

View File

@@ -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);
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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;
}
}
}

View File

@@ -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);
}
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.classloader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class CustomClassLoader extends ClassLoader {
@Override
public Class findClass(String name) throws ClassNotFoundException {
byte[] b = loadClassFromFile(name);
return defineClass(name, b, 0, b.length);
}
private byte[] loadClassFromFile(String fileName) {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(
fileName.replace('.', File.separatorChar) + ".class");
byte[] buffer;
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
int nextValue = 0;
try {
while ( (nextValue = inputStream.read()) != -1 ) {
byteStream.write(nextValue);
}
} catch (IOException e) {
e.printStackTrace();
}
buffer = byteStream.toByteArray();
return buffer;
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.classloader;
import com.sun.javafx.util.Logging;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
public class PrintClassLoader {
public void printClassLoaders() throws ClassNotFoundException {
System.out.println("Classloader of this class:" + PrintClassLoader.class.getClassLoader());
System.out.println("Classloader of Logging:" + Logging.class.getClassLoader());
System.out.println("Classloader of ArrayList:" + ArrayList.class.getClassLoader());
}
}

View File

@@ -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.");
}
}

View File

@@ -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();
}
}

View File

@@ -0,0 +1,29 @@
package com.baeldung.curltojava;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
public class JavaCurlExamples {
public static String inputStreamToString(InputStream inputStream) {
final int bufferSize = 8 * 1024;
byte[] buffer = new byte[bufferSize];
final StringBuilder builder = new StringBuilder();
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, bufferSize)) {
while (bufferedInputStream.read(buffer) != -1) {
builder.append(new String(buffer));
}
} catch (IOException ex) {
Logger.getLogger(JavaCurlExamples.class.getName()).log(Level.SEVERE, null, ex);
}
return builder.toString();
}
public static void consumeInputStream(InputStream inputStream) {
inputStreamToString(inputStream);
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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());
}
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.encoding;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
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();
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Arithmetic {
private static Logger LOGGER = LoggerFactory.getLogger(Arithmetic.class);
public static void main(String[] args) {
try {
int result = 30 / 0; // Trying to divide by zero
} catch (ArithmeticException e) {
LOGGER.error("ArithmeticException caught!");
}
}
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ArrayIndexOutOfBounds {
private static Logger LOGGER = LoggerFactory.getLogger(ArrayIndexOutOfBounds.class);
public static void main(String[] args) {
int[] nums = new int[] { 1, 2, 3 };
try {
int numFromNegativeIndex = nums[-1]; // Trying to access at negative index
int numFromGreaterIndex = nums[4]; // Trying to access at greater index
int numFromLengthIndex = nums[3]; // Trying to access at index equal to size of the array
} catch (ArrayIndexOutOfBoundsException e) {
LOGGER.error("ArrayIndexOutOfBoundsException caught");
}
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class Animal {
}
class Dog extends Animal {
}
class Lion extends Animal {
}
public class ClassCast {
private static Logger LOGGER = LoggerFactory.getLogger(ClassCast.class);
public static void main(String[] args) {
try {
Animal animalOne = new Dog(); // At runtime the instance is dog
Dog bruno = (Dog) animalOne; // Downcasting
Animal animalTwo = new Lion(); // At runtime the instance is animal
Dog tommy = (Dog) animalTwo; // Downcasting
} catch (ClassCastException e) {
LOGGER.error("ClassCastException caught!");
}
}
}

View File

@@ -0,0 +1,25 @@
package com.baeldung.exceptions;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileNotFound {
private static Logger LOGGER = LoggerFactory.getLogger(FileNotFound.class);
public static void main(String[] args) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(new File("/invalid/file/location")));
} catch (FileNotFoundException e) {
LOGGER.error("FileNotFoundException caught!");
}
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GlobalExceptionHandler {
public static void main(String[] args) {
Handler globalExceptionHandler = new Handler();
Thread.setDefaultUncaughtExceptionHandler(globalExceptionHandler);
new GlobalExceptionHandler().performArithmeticOperation(10, 0);
}
public int performArithmeticOperation(int num1, int num2) {
return num1/num2;
}
}
class Handler implements Thread.UncaughtExceptionHandler {
private static Logger LOGGER = LoggerFactory.getLogger(Handler.class);
public void uncaughtException(Thread t, Throwable e) {
LOGGER.info("Unhandled exception caught!");
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class IllegalArgument {
private static Logger LOGGER = LoggerFactory.getLogger(IllegalArgument.class);
public static void main(String[] args) {
try {
Thread.sleep(-1000);
} catch (InterruptedException e) {
LOGGER.error("IllegalArgumentException caught!");
}
}
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.exceptions;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class IllegalState {
private static Logger LOGGER = LoggerFactory.getLogger(IllegalState.class);
public static void main(String[] args) {
List<Integer> intList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
intList.add(i);
}
Iterator<Integer> intListIterator = intList.iterator(); // Initialized with index at -1
try {
intListIterator.remove(); // IllegalStateException
} catch (IllegalStateException e) {
LOGGER.error("IllegalStateException caught!");
}
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class ChildThread extends Thread {
private static Logger LOGGER = LoggerFactory.getLogger(ChildThread.class);
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
LOGGER.error("InterruptedException caught!");
}
}
}
public class InterruptedExceptionExample {
public static void main(String[] args) throws InterruptedException {
ChildThread childThread = new ChildThread();
childThread.start();
childThread.interrupt();
}
}

View File

@@ -0,0 +1,25 @@
package com.baeldung.exceptions;
import java.net.MalformedURLException;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MalformedURL {
private static Logger LOGGER = LoggerFactory.getLogger(MalformedURL.class);
public static void main(String[] args) {
URL baeldungURL = null;
try {
baeldungURL = new URL("malformedurl");
} catch (MalformedURLException e) {
LOGGER.error("MalformedURLException caught!");
}
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NullPointer {
private static Logger LOGGER = LoggerFactory.getLogger(NullPointer.class);
public static void main(String[] args) {
Person personObj = null;
try {
String name = personObj.personName; // Accessing the field of a null object
personObj.personName = "Jon Doe"; // Modifying the field of a null object
} catch (NullPointerException e) {
LOGGER.error("NullPointerException caught!");
}
}
}
class Person {
public String personName;
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NumberFormat {
private static Logger LOGGER = LoggerFactory.getLogger(NumberFormat.class);
public static void main(String[] args) {
String str1 = "100ABCD";
try {
int x = Integer.parseInt(str1); // Converting string with inappropriate format
int y = Integer.valueOf(str1);
} catch (NumberFormatException e) {
LOGGER.error("NumberFormatException caught!");
}
}
}

View File

@@ -0,0 +1,25 @@
package com.baeldung.exceptions;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ParseExceptionExample {
private static Logger LOGGER = LoggerFactory.getLogger(ParseExceptionExample.class);
public static void main(String[] args) {
DateFormat format = new SimpleDateFormat("MM, dd, yyyy");
try {
format.parse("01, , 2010");
} catch (ParseException e) {
LOGGER.error("ParseException caught!");
}
}
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.exceptions;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.io.PrintWriter;
import java.io.StringWriter;
public class StackTraceToString {
public static void main(String[] args) {
// Convert a StackTrace to String using core java
try {
throw new NullPointerException();
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
System.out.println(sw.toString());
}
// Convert a StackTrace to String using Apache Commons
try {
throw new IndexOutOfBoundsException();
} catch (Exception e) {
System.out.println(ExceptionUtils.getStackTrace(e));
}
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StringIndexOutOfBounds {
private static Logger LOGGER = LoggerFactory.getLogger(StringIndexOutOfBounds.class);
public static void main(String[] args) {
String str = "Hello World";
try {
char charAtNegativeIndex = str.charAt(-1); // Trying to access at negative index
char charAtLengthIndex = str.charAt(11); // Trying to access at index equal to size of the string
} catch (StringIndexOutOfBoundsException e) {
LOGGER.error("StringIndexOutOfBoundsException caught");
}
}
}

View File

@@ -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);
}
}

View File

@@ -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 +
'}';
}
}

View File

@@ -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 +
'}';
}
}

View File

@@ -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 +
'}';
}
}

View File

@@ -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;
}
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}
}

View File

@@ -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;
}
}
}

View File

@@ -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;
}
}

View 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().map(e -> e.remove(v)).collect(Collectors.toList());
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;
}
}
}

View File

@@ -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;
}
}

View File

@@ -0,0 +1,70 @@
package com.baeldung.instrumentation.agent;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
public class AtmTransformer implements ClassFileTransformer {
private static Logger LOGGER = LoggerFactory.getLogger(AtmTransformer.class);
private static final String WITHDRAW_MONEY_METHOD = "withdrawMoney";
/** The internal form class name of the class to transform */
private String targetClassName;
/** The class loader of the class we want to transform */
private ClassLoader targetClassLoader;
public AtmTransformer(String targetClassName, ClassLoader targetClassLoader) {
this.targetClassName = targetClassName;
this.targetClassLoader = targetClassLoader;
}
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
byte[] byteCode = classfileBuffer;
String finalTargetClassName = this.targetClassName.replaceAll("\\.", "/"); //replace . with /
if (!className.equals(finalTargetClassName)) {
return byteCode;
}
if (className.equals(finalTargetClassName) && loader.equals(targetClassLoader)) {
LOGGER.info("[Agent] Transforming class MyAtm");
try {
ClassPool cp = ClassPool.getDefault();
CtClass cc = cp.get(targetClassName);
CtMethod m = cc.getDeclaredMethod(WITHDRAW_MONEY_METHOD);
m.addLocalVariable("startTime", CtClass.longType);
m.insertBefore("startTime = System.currentTimeMillis();");
StringBuilder endBlock = new StringBuilder();
m.addLocalVariable("endTime", CtClass.longType);
m.addLocalVariable("opTime", CtClass.longType);
endBlock.append("endTime = System.currentTimeMillis();");
endBlock.append("opTime = (endTime-startTime)/1000;");
endBlock.append("LOGGER.info(\"[Application] Withdrawal operation completed in:\" + opTime + \" seconds!\");");
m.insertAfter(endBlock.toString());
byteCode = cc.toBytecode();
cc.detach();
} catch (NotFoundException | CannotCompileException | IOException e) {
LOGGER.error("Exception", e);
}
}
return byteCode;
}
}

View File

@@ -0,0 +1,59 @@
package com.baeldung.instrumentation.agent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.instrument.Instrumentation;
public class MyInstrumentationAgent {
private static Logger LOGGER = LoggerFactory.getLogger(MyInstrumentationAgent.class);
public static void premain(String agentArgs, Instrumentation inst) {
LOGGER.info("[Agent] In premain method");
String className = "com.baeldung.instrumentation.application.MyAtm";
transformClass(className,inst);
}
public static void agentmain(String agentArgs, Instrumentation inst) {
LOGGER.info("[Agent] In agentmain method");
String className = "com.baeldung.instrumentation.application.MyAtm";
transformClass(className,inst);
}
private static void transformClass(String className, Instrumentation instrumentation) {
Class<?> targetCls = null;
ClassLoader targetClassLoader = null;
// see if we can get the class using forName
try {
targetCls = Class.forName(className);
targetClassLoader = targetCls.getClassLoader();
transform(targetCls, targetClassLoader, instrumentation);
return;
} catch (Exception ex) {
LOGGER.error("Class [{}] not found with Class.forName");
}
// otherwise iterate all loaded classes and find what we want
for(Class<?> clazz: instrumentation.getAllLoadedClasses()) {
if(clazz.getName().equals(className)) {
targetCls = clazz;
targetClassLoader = targetCls.getClassLoader();
transform(targetCls, targetClassLoader, instrumentation);
return;
}
}
throw new RuntimeException("Failed to find class [" + className + "]");
}
private static void transform(Class<?> clazz, ClassLoader classLoader, Instrumentation instrumentation) {
AtmTransformer dt = new AtmTransformer(clazz.getName(), classLoader);
instrumentation.addTransformer(dt, true);
try {
instrumentation.retransformClasses(clazz);
} catch (Exception ex) {
throw new RuntimeException("Transform failed for class: [" + clazz.getName() + "]", ex);
}
}
}

View File

@@ -0,0 +1,46 @@
package com.baeldung.instrumentation.application;
import com.sun.tools.attach.VirtualMachine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Optional;
/**
* Created by adi on 6/10/18.
*/
public class AgentLoader {
private static Logger LOGGER = LoggerFactory.getLogger(AgentLoader.class);
public static void run(String[] args) {
String agentFilePath = "/home/adi/Desktop/agent-1.0.0-jar-with-dependencies.jar";
String applicationName = "MyAtmApplication";
//iterate all jvms and get the first one that matches our application name
Optional<String> jvmProcessOpt = Optional.ofNullable(VirtualMachine.list()
.stream()
.filter(jvm -> {
LOGGER.info("jvm:{}", jvm.displayName());
return jvm.displayName().contains(applicationName);
})
.findFirst().get().id());
if(!jvmProcessOpt.isPresent()) {
LOGGER.error("Target Application not found");
return;
}
File agentFile = new File(agentFilePath);
try {
String jvmPid = jvmProcessOpt.get();
LOGGER.info("Attaching to target JVM with PID: " + jvmPid);
VirtualMachine jvm = VirtualMachine.attach(jvmPid);
jvm.loadAgent(agentFile.getAbsolutePath());
jvm.detach();
LOGGER.info("Attached to target JVM and loaded Java agent successfully");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.instrumentation.application;
/**
* Created by adi on 6/14/18.
*/
public class Launcher {
public static void main(String[] args) throws Exception {
if(args[0].equals("StartMyAtmApplication")) {
new MyAtmApplication().run(args);
} else if(args[0].equals("LoadAgent")) {
new AgentLoader().run(args);
}
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.instrumentation.application;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by adi on 6/11/18.
*/
public class MyAtm {
private static Logger LOGGER = LoggerFactory.getLogger(MyAtm.class);
private static final int account = 10;
public static void withdrawMoney(int amount) throws InterruptedException {
Thread.sleep(2000l); //processing going on here
LOGGER.info("[Application] Successful Withdrawal of [{}] units!", amount);
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.instrumentation.application;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyAtmApplication {
private static Logger LOGGER = LoggerFactory.getLogger(MyAtmApplication.class);
public static void run(String[] args) throws Exception {
LOGGER.info("[Application] Starting ATM application");
MyAtm.withdrawMoney(Integer.parseInt(args[2]));
Thread.sleep(Long.valueOf(args[1]));
MyAtm.withdrawMoney(Integer.parseInt(args[3]));
}
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.jar;
public class JarExample {
public static void main(String[] args) {
System.out.println("Hello Baeldung Reader!");
}
}

View File

@@ -0,0 +1 @@
Main-Class: com.baeldung.jar.JarExample

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.logforging;
import org.owasp.esapi.ESAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogForgingDemo {
private final Logger logger = LoggerFactory.getLogger(LogForgingDemo.class);
public void addLog(String amount) {
logger.info("Amount credited = {}", amount);
}
public static void main(String[] args) {
LogForgingDemo demo = new LogForgingDemo();
demo.addLog("300");
demo.addLog("300 \n\nweb - 2017-04-12 17:47:08,957 [main] INFO Amount reversed successfully");
demo.addLog(encode("300 \n\nweb - 2017-04-12 17:47:08,957 [main] INFO Amount reversed successfully"));
}
public static String encode(String message) {
message = message.replace('\n', '_').replace('\r', '_').replace('\t', '_');
message = ESAPI.encoder().encodeForHTML(message);
return message;
}
}

View File

@@ -0,0 +1,8 @@
package com.baeldung.manifest;
public class AppExample {
public static void main(String[] args){
System.out.println("AppExample executed!");
}
}

View File

@@ -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;
}
}

View File

@@ -0,0 +1 @@
Main-Class: com.baeldung.manifest.AppExample

View File

@@ -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();
}
}

View File

@@ -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);
}
}

View File

@@ -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
}
}

View File

@@ -0,0 +1 @@
Premain-class: com.baeldung.objectsize.InstrumentationAgent

View File

@@ -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);
}
}

View File

@@ -0,0 +1,2 @@
### Relevant Articles:
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)

View File

@@ -0,0 +1,23 @@
package com.baeldung.printscreen;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
public class Screenshot {
private final String path;
public Screenshot(String path) {
this.path = path;
}
public void getScreenshot(int timeToWait) throws Exception {
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit()
.getScreenSize());
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(rectangle);
ImageIO.write(img, "jpg", new File(path));
}
}

View File

@@ -0,0 +1,39 @@
package com.baeldung.reflection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
class BaeldungReflectionUtils {
private static final Logger LOG = LoggerFactory.getLogger(BaeldungReflectionUtils.class);
static List<String> getNullPropertiesList(Customer customer) throws Exception {
PropertyDescriptor[] propDescArr = Introspector.getBeanInfo(Customer.class, Object.class).getPropertyDescriptors();
return Arrays.stream(propDescArr)
.filter(nulls(customer))
.map(PropertyDescriptor::getName)
.collect(Collectors.toList());
}
private static Predicate<PropertyDescriptor> nulls(Customer customer) {
return pd -> {
boolean result = false;
try {
Method getterMethod = pd.getReadMethod();
result = (getterMethod != null && getterMethod.invoke(customer) == null);
} catch (Exception e) {
LOG.error("error invoking getter method");
}
return result;
};
}
}

View File

@@ -0,0 +1,56 @@
package com.baeldung.reflection;
public class Customer {
private Integer id;
private String name;
private String emailId;
private Long phoneNumber;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", emailId=" + emailId + ", phoneNumber=" +
phoneNumber + "]";
}
Customer(Integer id, String name, String emailId, Long phoneNumber) {
super();
this.id = id;
this.name = name;
this.emailId = emailId;
this.phoneNumber = phoneNumber;
}
public Long getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(Long phoneNumber) {
this.phoneNumber = phoneNumber;
}
}

View File

@@ -0,0 +1,7 @@
package com.baeldung.reflection;
public class Employee extends Person {
public int employeeId;
}

View File

@@ -0,0 +1,7 @@
package com.baeldung.reflection;
public class MonthEmployee extends Employee {
protected double reward;
}

View File

@@ -0,0 +1,8 @@
package com.baeldung.reflection;
public class Person {
protected String lastName;
private String firstName;
}

View File

@@ -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"));
}
}

View File

@@ -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" }
};
}
}

View File

@@ -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" },
};
}
}

View File

@@ -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" } }
};
}
}

View File

@@ -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;
}
}

View File

@@ -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);
}
}

View File

@@ -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;
}
}

View File

@@ -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();
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.system;
import org.apache.commons.lang3.SystemUtils;
public class DetectOS {
public String getOperatingSystem() {
String os = System.getProperty("os.name");
System.out.println("Using System Property: " + os);
return os;
}
public String getOperatingSystemSystemUtils() {
String os = SystemUtils.OS_NAME;
System.out.println("Using SystemUtils: " + os);
return os;
}
}

View File

@@ -0,0 +1,46 @@
package com.baeldung.urlconnection;
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());
}
}
}

View File

@@ -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;
}
}

View File

@@ -0,0 +1,116 @@
package com.baeldung.uuid;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
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("MD5 not supported", nsae);
}
byte[] bytes = md.digest(name);
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);
}
}

View File

@@ -0,0 +1,2 @@
-d javac-target -verbose
com/baeldung/javac/Data.java

View File

@@ -0,0 +1,2 @@
-d javac-target
-verbose

View File

@@ -0,0 +1 @@
com/baeldung/javac/Data.java

View File

@@ -0,0 +1,3 @@
-d javac-target
-Xlint:rawtypes,unchecked,static,cast,serial,fallthrough
com/baeldung/javac/Data.java

View File

@@ -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

View File

@@ -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);
}
}

View File

@@ -0,0 +1,453 @@
#
# OWASP Enterprise Security API (ESAPI) Properties file -- PRODUCTION Version
#
# This file is part of the Open Web Application Security Project (OWASP)
# Enterprise Security API (ESAPI) project. For details, please see
# http://www.owasp.org/index.php/ESAPI.
#
# Copyright (c) 2008,2009 - The OWASP Foundation
#
# DISCUSS: This may cause a major backwards compatibility issue, etc. but
# from a name space perspective, we probably should have prefaced
# all the property names with ESAPI or at least OWASP. Otherwise
# there could be problems is someone loads this properties file into
# the System properties. We could also put this file into the
# esapi.jar file (perhaps as a ResourceBundle) and then allow an external
# ESAPI properties be defined that would overwrite these defaults.
# That keeps the application's properties relatively simple as usually
# they will only want to override a few properties. If looks like we
# already support multiple override levels of this in the
# DefaultSecurityConfiguration class, but I'm suggesting placing the
# defaults in the esapi.jar itself. That way, if the jar is signed,
# we could detect if those properties had been tampered with. (The
# code to check the jar signatures is pretty simple... maybe 70-90 LOC,
# but off course there is an execution penalty (similar to the way
# that the separate sunjce.jar used to be when a class from it was
# first loaded). Thoughts?
###############################################################################
#
# WARNING: Operating system protection should be used to lock down the .esapi
# resources directory and all the files inside and all the directories all the
# way up to the root directory of the file system. Note that if you are using
# file-based implementations, that some files may need to be read-write as they
# get updated dynamically.
#
# Before using, be sure to update the MasterKey and MasterSalt as described below.
# N.B.: If you had stored data that you have previously encrypted with ESAPI 1.4,
# you *must* FIRST decrypt it using ESAPI 1.4 and then (if so desired)
# re-encrypt it with ESAPI 2.0. If you fail to do this, you will NOT be
# able to decrypt your data with ESAPI 2.0.
#
# YOU HAVE BEEN WARNED!!! More details are in the ESAPI 2.0 Release Notes.
#
#===========================================================================
# ESAPI Configuration
#
# If true, then print all the ESAPI properties set here when they are loaded.
# If false, they are not printed. Useful to reduce output when running JUnit tests.
# If you need to troubleshoot a properties related problem, turning this on may help.
# This is 'false' in the src/test/resources/.esapi version. It is 'true' by
# default for reasons of backward compatibility with earlier ESAPI versions.
ESAPI.printProperties=true
# ESAPI is designed to be easily extensible. You can use the reference implementation
# or implement your own providers to take advantage of your enterprise's security
# infrastructure. The functions in ESAPI are referenced using the ESAPI locator, like:
#
# String ciphertext =
# ESAPI.encryptor().encrypt("Secret message"); // Deprecated in 2.0
# CipherText cipherText =
# ESAPI.encryptor().encrypt(new PlainText("Secret message")); // Preferred
#
# Below you can specify the classname for the provider that you wish to use in your
# application. The only requirement is that it implement the appropriate ESAPI interface.
# This allows you to switch security implementations in the future without rewriting the
# entire application.
#
# ExperimentalAccessController requires ESAPI-AccessControlPolicy.xml in .esapi directory
ESAPI.AccessControl=org.owasp.esapi.reference.DefaultAccessController
# FileBasedAuthenticator requires users.txt file in .esapi directory
ESAPI.Authenticator=org.owasp.esapi.reference.FileBasedAuthenticator
ESAPI.Encoder=org.owasp.esapi.reference.DefaultEncoder
ESAPI.Encryptor=org.owasp.esapi.reference.crypto.JavaEncryptor
ESAPI.Executor=org.owasp.esapi.reference.DefaultExecutor
ESAPI.HTTPUtilities=org.owasp.esapi.reference.DefaultHTTPUtilities
ESAPI.IntrusionDetector=org.owasp.esapi.reference.DefaultIntrusionDetector
# Log4JFactory Requires log4j.xml or log4j.properties in classpath - http://www.laliluna.de/log4j-tutorial.html
ESAPI.Logger=org.owasp.esapi.reference.Log4JLogFactory
#ESAPI.Logger=org.owasp.esapi.reference.JavaLogFactory
ESAPI.Randomizer=org.owasp.esapi.reference.DefaultRandomizer
ESAPI.Validator=org.owasp.esapi.reference.DefaultValidator
#===========================================================================
# ESAPI Authenticator
#
Authenticator.AllowedLoginAttempts=3
Authenticator.MaxOldPasswordHashes=13
Authenticator.UsernameParameterName=username
Authenticator.PasswordParameterName=password
# RememberTokenDuration (in days)
Authenticator.RememberTokenDuration=14
# Session Timeouts (in minutes)
Authenticator.IdleTimeoutDuration=20
Authenticator.AbsoluteTimeoutDuration=120
#===========================================================================
# ESAPI Encoder
#
# ESAPI canonicalizes input before validation to prevent bypassing filters with encoded attacks.
# Failure to canonicalize input is a very common mistake when implementing validation schemes.
# Canonicalization is automatic when using the ESAPI Validator, but you can also use the
# following code to canonicalize data.
#
# ESAPI.Encoder().canonicalize( "%22hello world&#x22;" );
#
# Multiple encoding is when a single encoding format is applied multiple times. Allowing
# multiple encoding is strongly discouraged.
Encoder.AllowMultipleEncoding=false
# Mixed encoding is when multiple different encoding formats are applied, or when
# multiple formats are nested. Allowing multiple encoding is strongly discouraged.
Encoder.AllowMixedEncoding=false
# The default list of codecs to apply when canonicalizing untrusted data. The list should include the codecs
# for all downstream interpreters or decoders. For example, if the data is likely to end up in a URL, HTML, or
# inside JavaScript, then the list of codecs below is appropriate. The order of the list is not terribly important.
Encoder.DefaultCodecList=HTMLEntityCodec,PercentCodec,JavaScriptCodec
#===========================================================================
# ESAPI Encryption
#
# The ESAPI Encryptor provides basic cryptographic functions with a simplified API.
# To get started, generate a new key using java -classpath esapi.jar org.owasp.esapi.reference.crypto.JavaEncryptor
# There is not currently any support for key rotation, so be careful when changing your key and salt as it
# will invalidate all signed, encrypted, and hashed data.
#
# WARNING: Not all combinations of algorithms and key lengths are supported.
# If you choose to use a key length greater than 128, you MUST download the
# unlimited strength policy files and install in the lib directory of your JRE/JDK.
# See http://java.sun.com/javase/downloads/index.jsp for more information.
#
# Backward compatibility with ESAPI Java 1.4 is supported by the two deprecated API
# methods, Encryptor.encrypt(String) and Encryptor.decrypt(String). However, whenever
# possible, these methods should be avoided as they use ECB cipher mode, which in almost
# all circumstances a poor choice because of it's weakness. CBC cipher mode is the default
# for the new Encryptor encrypt / decrypt methods for ESAPI Java 2.0. In general, you
# should only use this compatibility setting if you have persistent data encrypted with
# version 1.4 and even then, you should ONLY set this compatibility mode UNTIL
# you have decrypted all of your old encrypted data and then re-encrypted it with
# ESAPI 2.0 using CBC mode. If you have some reason to mix the deprecated 1.4 mode
# with the new 2.0 methods, make sure that you use the same cipher algorithm for both
# (256-bit AES was the default for 1.4; 128-bit is the default for 2.0; see below for
# more details.) Otherwise, you will have to use the new 2.0 encrypt / decrypt methods
# where you can specify a SecretKey. (Note that if you are using the 256-bit AES,
# that requires downloading the special jurisdiction policy files mentioned above.)
#
# ***** IMPORTANT: Do NOT forget to replace these with your own values! *****
# To calculate these values, you can run:
# java -classpath esapi.jar org.owasp.esapi.reference.crypto.JavaEncryptor
#
Encryptor.MasterKey=tzfztf56ftv
Encryptor.MasterSalt=123456ztrewq
# Provides the default JCE provider that ESAPI will "prefer" for its symmetric
# encryption and hashing. (That is it will look to this provider first, but it
# will defer to other providers if the requested algorithm is not implemented
# by this provider.) If left unset, ESAPI will just use your Java VM's current
# preferred JCE provider, which is generally set in the file
# "$JAVA_HOME/jre/lib/security/java.security".
#
# The main intent of this is to allow ESAPI symmetric encryption to be
# used with a FIPS 140-2 compliant crypto-module. For details, see the section
# "Using ESAPI Symmetric Encryption with FIPS 140-2 Cryptographic Modules" in
# the ESAPI 2.0 Symmetric Encryption User Guide, at:
# http://owasp-esapi-java.googlecode.com/svn/trunk/documentation/esapi4java-core-2.0-symmetric-crypto-user-guide.html
# However, this property also allows you to easily use an alternate JCE provider
# such as "Bouncy Castle" without having to make changes to "java.security".
# See Javadoc for SecurityProviderLoader for further details. If you wish to use
# a provider that is not known to SecurityProviderLoader, you may specify the
# fully-qualified class name of the JCE provider class that implements
# java.security.Provider. If the name contains a '.', this is interpreted as
# a fully-qualified class name that implements java.security.Provider.
#
# NOTE: Setting this property has the side-effect of changing it in your application
# as well, so if you are using JCE in your application directly rather than
# through ESAPI (you wouldn't do that, would you? ;-), it will change the
# preferred JCE provider there as well.
#
# Default: Keeps the JCE provider set to whatever JVM sets it to.
Encryptor.PreferredJCEProvider=
# AES is the most widely used and strongest encryption algorithm. This
# should agree with your Encryptor.CipherTransformation property.
# By default, ESAPI Java 1.4 uses "PBEWithMD5AndDES" and which is
# very weak. It is essentially a password-based encryption key, hashed
# with MD5 around 1K times and then encrypted with the weak DES algorithm
# (56-bits) using ECB mode and an unspecified padding (it is
# JCE provider specific, but most likely "NoPadding"). However, 2.0 uses
# "AES/CBC/PKCSPadding". If you want to change these, change them here.
# Warning: This property does not control the default reference implementation for
# ESAPI 2.0 using JavaEncryptor. Also, this property will be dropped
# in the future.
# @deprecated
Encryptor.EncryptionAlgorithm=AES
# For ESAPI Java 2.0 - New encrypt / decrypt methods use this.
Encryptor.CipherTransformation=AES/CBC/PKCS5Padding
# Applies to ESAPI 2.0 and later only!
# Comma-separated list of cipher modes that provide *BOTH*
# confidentiality *AND* message authenticity. (NIST refers to such cipher
# modes as "combined modes" so that's what we shall call them.) If any of these
# cipher modes are used then no MAC is calculated and stored
# in the CipherText upon encryption. Likewise, if one of these
# cipher modes is used with decryption, no attempt will be made
# to validate the MAC contained in the CipherText object regardless
# of whether it contains one or not. Since the expectation is that
# these cipher modes support support message authenticity already,
# injecting a MAC in the CipherText object would be at best redundant.
#
# Note that as of JDK 1.5, the SunJCE provider does not support *any*
# of these cipher modes. Of these listed, only GCM and CCM are currently
# NIST approved. YMMV for other JCE providers. E.g., Bouncy Castle supports
# GCM and CCM with "NoPadding" mode, but not with "PKCS5Padding" or other
# padding modes.
Encryptor.cipher_modes.combined_modes=GCM,CCM,IAPM,EAX,OCB,CWC
# Applies to ESAPI 2.0 and later only!
# Additional cipher modes allowed for ESAPI 2.0 encryption. These
# cipher modes are in _addition_ to those specified by the property
# 'Encryptor.cipher_modes.combined_modes'.
# Note: We will add support for streaming modes like CFB & OFB once
# we add support for 'specified' to the property 'Encryptor.ChooseIVMethod'
# (probably in ESAPI 2.1).
# DISCUSS: Better name?
Encryptor.cipher_modes.additional_allowed=CBC
# 128-bit is almost always sufficient and appears to be more resistant to
# related key attacks than is 256-bit AES. Use '_' to use default key size
# for cipher algorithms (where it makes sense because the algorithm supports
# a variable key size). Key length must agree to what's provided as the
# cipher transformation, otherwise this will be ignored after logging a
# warning.
#
# NOTE: This is what applies BOTH ESAPI 1.4 and 2.0. See warning above about mixing!
Encryptor.EncryptionKeyLength=128
# Because 2.0 uses CBC mode by default, it requires an initialization vector (IV).
# (All cipher modes except ECB require an IV.) There are two choices: we can either
# use a fixed IV known to both parties or allow ESAPI to choose a random IV. While
# the IV does not need to be hidden from adversaries, it is important that the
# adversary not be allowed to choose it. Also, random IVs are generally much more
# secure than fixed IVs. (In fact, it is essential that feed-back cipher modes
# such as CFB and OFB use a different IV for each encryption with a given key so
# in such cases, random IVs are much preferred. By default, ESAPI 2.0 uses random
# IVs. If you wish to use 'fixed' IVs, set 'Encryptor.ChooseIVMethod=fixed' and
# uncomment the Encryptor.fixedIV.
#
# Valid values: random|fixed|specified 'specified' not yet implemented; planned for 2.1
Encryptor.ChooseIVMethod=random
# If you choose to use a fixed IV, then you must place a fixed IV here that
# is known to all others who are sharing your secret key. The format should
# be a hex string that is the same length as the cipher block size for the
# cipher algorithm that you are using. The following is an *example* for AES
# from an AES test vector for AES-128/CBC as described in:
# NIST Special Publication 800-38A (2001 Edition)
# "Recommendation for Block Cipher Modes of Operation".
# (Note that the block size for AES is 16 bytes == 128 bits.)
#
Encryptor.fixedIV=0x000102030405060708090a0b0c0d0e0f
# Whether or not CipherText should use a message authentication code (MAC) with it.
# This prevents an adversary from altering the IV as well as allowing a more
# fool-proof way of determining the decryption failed because of an incorrect
# key being supplied. This refers to the "separate" MAC calculated and stored
# in CipherText, not part of any MAC that is calculated as a result of a
# "combined mode" cipher mode.
#
# If you are using ESAPI with a FIPS 140-2 cryptographic module, you *must* also
# set this property to false.
Encryptor.CipherText.useMAC=true
# Whether or not the PlainText object may be overwritten and then marked
# eligible for garbage collection. If not set, this is still treated as 'true'.
Encryptor.PlainText.overwrite=true
# Do not use DES except in a legacy situations. 56-bit is way too small key size.
#Encryptor.EncryptionKeyLength=56
#Encryptor.EncryptionAlgorithm=DES
# TripleDES is considered strong enough for most purposes.
# Note: There is also a 112-bit version of DESede. Using the 168-bit version
# requires downloading the special jurisdiction policy from Sun.
#Encryptor.EncryptionKeyLength=168
#Encryptor.EncryptionAlgorithm=DESede
Encryptor.HashAlgorithm=SHA-512
Encryptor.HashIterations=1024
Encryptor.DigitalSignatureAlgorithm=SHA1withDSA
Encryptor.DigitalSignatureKeyLength=1024
Encryptor.RandomAlgorithm=SHA1PRNG
Encryptor.CharacterEncoding=UTF-8
# This is the Pseudo Random Function (PRF) that ESAPI's Key Derivation Function
# (KDF) normally uses. Note this is *only* the PRF used for ESAPI's KDF and
# *not* what is used for ESAPI's MAC. (Currently, HmacSHA1 is always used for
# the MAC, mostly to keep the overall size at a minimum.)
#
# Currently supported choices for JDK 1.5 and 1.6 are:
# HmacSHA1 (160 bits), HmacSHA256 (256 bits), HmacSHA384 (384 bits), and
# HmacSHA512 (512 bits).
# Note that HmacMD5 is *not* supported for the PRF used by the KDF even though
# the JDKs support it. See the ESAPI 2.0 Symmetric Encryption User Guide
# further details.
Encryptor.KDF.PRF=HmacSHA256
#===========================================================================
# ESAPI HttpUtilties
#
# The HttpUtilities provide basic protections to HTTP requests and responses. Primarily these methods
# protect against malicious data from attackers, such as unprintable characters, escaped characters,
# and other simple attacks. The HttpUtilities also provides utility methods for dealing with cookies,
# headers, and CSRF tokens.
#
# Default file upload location (remember to escape backslashes with \\)
HttpUtilities.UploadDir=C:\\ESAPI\\testUpload
HttpUtilities.UploadTempDir=C:\\temp
# Force flags on cookies, if you use HttpUtilities to set cookies
HttpUtilities.ForceHttpOnlySession=false
HttpUtilities.ForceSecureSession=false
HttpUtilities.ForceHttpOnlyCookies=true
HttpUtilities.ForceSecureCookies=true
# Maximum size of HTTP headers
HttpUtilities.MaxHeaderSize=4096
# File upload configuration
HttpUtilities.ApprovedUploadExtensions=.zip,.pdf,.doc,.docx,.ppt,.pptx,.tar,.gz,.tgz,.rar,.war,.jar,.ear,.xls,.rtf,.properties,.java,.class,.txt,.xml,.jsp,.jsf,.exe,.dll
HttpUtilities.MaxUploadFileBytes=500000000
# Using UTF-8 throughout your stack is highly recommended. That includes your database driver,
# container, and any other technologies you may be using. Failure to do this may expose you
# to Unicode transcoding injection attacks. Use of UTF-8 does not hinder internationalization.
HttpUtilities.ResponseContentType=text/html; charset=UTF-8
# This is the name of the cookie used to represent the HTTP session
# Typically this will be the default "JSESSIONID"
HttpUtilities.HttpSessionIdName=JSESSIONID
#===========================================================================
# ESAPI Executor
# CHECKME - Not sure what this is used for, but surely it should be made OS independent.
Executor.WorkingDirectory=C:\\Windows\\Temp
Executor.ApprovedExecutables=C:\\Windows\\System32\\cmd.exe,C:\\Windows\\System32\\runas.exe
#===========================================================================
# ESAPI Logging
# Set the application name if these logs are combined with other applications
Logger.ApplicationName=ExampleApplication
# If you use an HTML log viewer that does not properly HTML escape log data, you can set LogEncodingRequired to true
Logger.LogEncodingRequired=false
# Determines whether ESAPI should log the application name. This might be clutter in some single-server/single-app environments.
Logger.LogApplicationName=true
# Determines whether ESAPI should log the server IP and port. This might be clutter in some single-server environments.
Logger.LogServerIP=true
# LogFileName, the name of the logging file. Provide a full directory path (e.g., C:\\ESAPI\\ESAPI_logging_file) if you
# want to place it in a specific directory.
Logger.LogFileName=ESAPI_logging_file
# MaxLogFileSize, the max size (in bytes) of a single log file before it cuts over to a new one (default is 10,000,000)
Logger.MaxLogFileSize=10000000
#===========================================================================
# ESAPI Intrusion Detection
#
# Each event has a base to which .count, .interval, and .action are added
# The IntrusionException will fire if we receive "count" events within "interval" seconds
# The IntrusionDetector is configurable to take the following actions: log, logout, and disable
# (multiple actions separated by commas are allowed e.g. event.test.actions=log,disable
#
# Custom Events
# Names must start with "event." as the base
# Use IntrusionDetector.addEvent( "test" ) in your code to trigger "event.test" here
# You can also disable intrusion detection completely by changing
# the following parameter to true
#
IntrusionDetector.Disable=false
#
IntrusionDetector.event.test.count=2
IntrusionDetector.event.test.interval=10
IntrusionDetector.event.test.actions=disable,log
# Exception Events
# All EnterpriseSecurityExceptions are registered automatically
# Call IntrusionDetector.getInstance().addException(e) for Exceptions that do not extend EnterpriseSecurityException
# Use the fully qualified classname of the exception as the base
# any intrusion is an attack
IntrusionDetector.org.owasp.esapi.errors.IntrusionException.count=1
IntrusionDetector.org.owasp.esapi.errors.IntrusionException.interval=1
IntrusionDetector.org.owasp.esapi.errors.IntrusionException.actions=log,disable,logout
# for test purposes
# CHECKME: Shouldn't there be something in the property name itself that designates
# that these are for testing???
IntrusionDetector.org.owasp.esapi.errors.IntegrityException.count=10
IntrusionDetector.org.owasp.esapi.errors.IntegrityException.interval=5
IntrusionDetector.org.owasp.esapi.errors.IntegrityException.actions=log,disable,logout
# rapid validation errors indicate scans or attacks in progress
# org.owasp.esapi.errors.ValidationException.count=10
# org.owasp.esapi.errors.ValidationException.interval=10
# org.owasp.esapi.errors.ValidationException.actions=log,logout
# sessions jumping between hosts indicates session hijacking
IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.count=2
IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.interval=10
IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.actions=log,logout
#===========================================================================
# ESAPI Validation
#
# The ESAPI Validator works on regular expressions with defined names. You can define names
# either here, or you may define application specific patterns in a separate file defined below.
# This allows enterprises to specify both organizational standards as well as application specific
# validation rules.
#
Validator.ConfigurationFile=validation.properties
# Validators used by ESAPI
Validator.AccountName=^[a-zA-Z0-9]{3,20}$
Validator.SystemCommand=^[a-zA-Z\\-\\/]{1,64}$
Validator.RoleName=^[a-z]{1,20}$
#the word TEST below should be changed to your application
#name - only relative URL's are supported
Validator.Redirect=^\\/test.*$
# Global HTTP Validation Rules
# Values with Base64 encoded data (e.g. encrypted state) will need at least [a-zA-Z0-9\/+=]
Validator.HTTPScheme=^(http|https)$
Validator.HTTPServerName=^[a-zA-Z0-9_.\\-]*$
Validator.HTTPParameterName=^[a-zA-Z0-9_]{1,32}$
Validator.HTTPParameterValue=^[a-zA-Z0-9.\\-\\/+=@_ ]*$
Validator.HTTPCookieName=^[a-zA-Z0-9\\-_]{1,32}$
Validator.HTTPCookieValue=^[a-zA-Z0-9\\-\\/+=_ ]*$
Validator.HTTPHeaderName=^[a-zA-Z0-9\\-_]{1,32}$
Validator.HTTPHeaderValue=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ ]*$
Validator.HTTPContextPath=^\\/?[a-zA-Z0-9.\\-\\/_]*$
Validator.HTTPServletPath=^[a-zA-Z0-9.\\-\\/_]*$
Validator.HTTPPath=^[a-zA-Z0-9.\\-_]*$
Validator.HTTPQueryString=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ %]*$
Validator.HTTPURI=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ ]*$
Validator.HTTPURL=^.*$
Validator.HTTPJSESSIONID=^[A-Z0-9]{10,30}$
# Validation of file related input
Validator.FileName=^[a-zA-Z0-9!@#$%^&{}\\[\\]()_+\\-=,.~'` ]{1,255}$
Validator.DirectoryName=^[a-zA-Z0-9:/\\\\!@#$%^&{}\\[\\]()_+\\-=,.~'` ]{1,255}$
# Validation of dates. Controls whether or not 'lenient' dates are accepted.
# See DataFormat.setLenient(boolean flag) for further details.
Validator.AcceptLenientDates=false

View File

@@ -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

View File

@@ -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>

View File

@@ -0,0 +1,3 @@
UK
US
Germany

View File

@@ -0,0 +1,6 @@
dataSourceClassName=//TBD
dataSource.user=//TBD
dataSource.password=//TBD
dataSource.databaseName=//TBD
dataSource.portNumber=//TBD
dataSource.serverName=//TBD

View File

@@ -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

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