This commit is contained in:
Dassi Orleando 2017-12-05 05:29:19 +01:00
commit 28dd06d927
116 changed files with 3823 additions and 889 deletions

View File

@ -1,6 +1,7 @@
package com.baeldung.cassecuredapp.controllers;
import org.apache.log4j.Logger;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler;
@ -15,7 +16,7 @@ import javax.servlet.http.HttpServletResponse;
@Controller
public class AuthController {
private Logger logger = Logger.getLogger(AuthController.class);
private Logger logger = LogManager.getLogger(AuthController.class);
@GetMapping("/logout")
public String logout(

View File

@ -1,258 +1,276 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>core-java-8</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>core-java-8</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<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.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.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.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-8</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>
<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>
<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>
<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>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</configuration>
</execution>
</executions>
</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>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- util -->
<guava.version>21.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-math3.version>3.6.1</commons-math3.version>
<commons-io.version>2.5</commons-io.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<commons-codec.version>1.10</commons-codec.version>
<lombok.version>1.16.12</lombok.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
</properties>
<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>
<groupId>com.baeldung</groupId>
<artifactId>core-java-8</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>core-java-8</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<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.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.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.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-bytecode</artifactId>
<version>1.19</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-8</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>
<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>
<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>
<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>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</configuration>
</execution>
</executions>
</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>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- util -->
<guava.version>21.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-math3.version>3.6.1</commons-math3.version>
<commons-io.version>2.5</commons-io.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<commons-codec.version>1.10</commons-codec.version>
<lombok.version>1.16.12</lombok.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
</properties>
</project>

View File

@ -0,0 +1,45 @@
package com.baeldung.counter;
import java.util.HashMap;
import java.util.Map;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import com.baeldung.counter.CounterUtil.MutableInteger;
@Fork(value = 1, warmups = 3)
@BenchmarkMode(Mode.All)
public class CounterStatistics {
private static final Map<String, Integer> counterMap = new HashMap<>();
private static final Map<String, MutableInteger> counterWithMutableIntMap = new HashMap<>();
private static final Map<String, int[]> counterWithIntArrayMap = new HashMap<>();
private static final Map<String, Long> counterWithLongWrapperMap = new HashMap<>();
@Benchmark
public void wrapperAsCounter() {
CounterUtil.counterWithWrapperObject(counterMap);
}
@Benchmark
public void lambdaExpressionWithWrapper() {
CounterUtil.counterWithLambdaAndWrapper(counterWithLongWrapperMap);
}
@Benchmark
public void mutableIntegerAsCounter() {
CounterUtil.counterWithMutableInteger(counterWithMutableIntMap);
}
@Benchmark
public void primitiveArrayAsCounter() {
CounterUtil.counterWithPrimitiveArray(counterWithIntArrayMap);
}
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.counter;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
import org.junit.Test;
import com.baeldung.counter.CounterUtil.MutableInteger;
public class CounterTest {
@Test
public void whenMapWithWrapperAsCounter_runsSuccessfully() {
Map<String, Integer> counterMap = new HashMap<>();
CounterUtil.counterWithWrapperObject(counterMap);
assertEquals(3, counterMap.get("China")
.intValue());
assertEquals(2, counterMap.get("India")
.intValue());
}
@Test
public void whenMapWithLambdaAndWrapperCounter_runsSuccessfully() {
Map<String, Long> counterMap = new HashMap<>();
CounterUtil.counterWithLambdaAndWrapper(counterMap);
assertEquals(3l, counterMap.get("China")
.longValue());
assertEquals(2l, counterMap.get("India")
.longValue());
}
@Test
public void whenMapWithMutableIntegerCounter_runsSuccessfully() {
Map<String, MutableInteger> counterMap = new HashMap<>();
CounterUtil.counterWithMutableInteger(counterMap);
assertEquals(3, counterMap.get("China")
.getCount());
assertEquals(2, counterMap.get("India")
.getCount());
}
@Test
public void whenMapWithPrimitiveArray_runsSuccessfully() {
Map<String, int[]> counterMap = new HashMap<>();
CounterUtil.counterWithPrimitiveArray(counterMap);
assertEquals(3, counterMap.get("China")[0]);
assertEquals(2, counterMap.get("India")[0]);
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.counter;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CounterUtil {
private final static String[] COUNTRY_NAMES = { "China", "Australia", "India", "USA", "USSR", "UK", "China", "France", "Poland", "Austria", "India", "USA", "Egypt", "China" };
public static void counterWithWrapperObject(Map<String, Integer> counterMap) {
for (String country : COUNTRY_NAMES) {
counterMap.compute(country, (k, v) -> v == null ? 1 : v + 1);
}
}
public static void counterWithLambdaAndWrapper(Map<String, Long> counterMap) {
counterMap.putAll(Stream.of(COUNTRY_NAMES)
.parallel()
.collect(Collectors.groupingBy(k -> k, Collectors.counting())));
}
public static class MutableInteger {
int count;
public MutableInteger(int count) {
this.count = count;
}
public void increment() {
this.count++;
}
public int getCount() {
return this.count;
}
}
public static void counterWithMutableInteger(Map<String, MutableInteger> counterMap) {
for (String country : COUNTRY_NAMES) {
MutableInteger oldValue = counterMap.get(country);
if (oldValue != null) {
oldValue.increment();
} else {
counterMap.put(country, new MutableInteger(1));
}
}
}
public static void counterWithPrimitiveArray(Map<String, int[]> counterMap) {
for (String country : COUNTRY_NAMES) {
int[] oldCounter = counterMap.get(country);
if (oldCounter != null) {
oldCounter[0] += 1;
} else {
counterMap.put(country, new int[] { 1 });
}
}
}
}

View File

@ -0,0 +1,3 @@
javac --module-path mods -d mods/com.baeldung.httpclient^
src/modules/com.baeldung.httpclient/module-info.java^
src/modules/com.baeldung.httpclient/com/baeldung/httpclient/HttpClientExample.java

View File

@ -0,0 +1 @@
java --module-path mods -m com.baeldung.httpclient/com.baeldung.httpclient.HttpClientExample

View File

@ -0,0 +1,84 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.baeldung.httpclient;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import jdk.incubator.http.HttpClient;
import jdk.incubator.http.HttpRequest;
import jdk.incubator.http.HttpRequest.BodyProcessor;
import jdk.incubator.http.HttpResponse;
import jdk.incubator.http.HttpResponse.BodyHandler;
/**
*
* @author pkaria
*/
public class HttpClientExample {
public static void main(String[] args) throws Exception {
httpGetRequest();
httpPostRequest();
asynchronousRequest();
asynchronousMultipleRequests();
}
public static void httpGetRequest() throws URISyntaxException, IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
HttpRequest request = HttpRequest.newBuilder(httpURI).GET()
.headers("Accept-Enconding", "gzip, deflate").build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString());
String responseBody = response.body();
int responseStatusCode = response.statusCode();
System.out.println(responseBody);
}
public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException {
HttpClient client = HttpClient
.newBuilder()
.build();
HttpRequest request = HttpRequest
.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts"))
.POST(BodyProcessor.fromString("Sample Post Request"))
.build();
HttpResponse<String> response
= client.send(request, HttpResponse.BodyHandler.asString());
String responseBody = response.body();
System.out.println(responseBody);
}
public static void asynchronousRequest() throws URISyntaxException {
HttpClient client = HttpClient.newHttpClient();
URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
HttpRequest request = HttpRequest.newBuilder(httpURI).GET().build();
CompletableFuture<HttpResponse<String>> futureResponse = client.sendAsync(request,
HttpResponse.BodyHandler.asString());
}
public static void asynchronousMultipleRequests() throws URISyntaxException {
List<URI> targets = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2"));
HttpClient client = HttpClient.newHttpClient();
List<CompletableFuture<File>> futures = targets
.stream()
.map(target -> client
.sendAsync(
HttpRequest.newBuilder(target)
.GET()
.build(),
BodyHandler.asFile(Paths.get("base", target.getPath())))
.thenApply(response -> response.body())
.thenApply(path -> path.toFile()))
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,3 @@
module com.baeldung.httpclient {
requires jdk.incubator.httpclient;
}

View File

@ -9,7 +9,6 @@ import java.util.List;
import java.util.concurrent.*;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.fail;
public class WaitingForThreadsToFinishTest {
@ -40,16 +39,13 @@ public class WaitingForThreadsToFinishTest {
CountDownLatch latch = new CountDownLatch(2);
for (int i = 0; i < 2; i++) {
WORKER_THREAD_POOL.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
WORKER_THREAD_POOL.submit(() -> {
try {
Thread.sleep(1000);
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
});
}
@ -83,13 +79,9 @@ public class WaitingForThreadsToFinishTest {
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
try {
WORKER_THREAD_POOL.submit(new Callable<String>() {
@Override
public String call() throws Exception {
fail("This thread should have been rejected !");
Thread.sleep(1000000);
return null;
}
WORKER_THREAD_POOL.submit((Callable<String>) () -> {
Thread.sleep(1000000);
return null;
});
} catch (RejectedExecutionException ex) {
//

View File

@ -120,4 +120,5 @@
- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns)
- [Quick Example - Comparator vs Comparable in Java](http://www.baeldung.com/java-comparator-comparable)

95
core-java/customers.xml Normal file
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>

View File

@ -1,479 +1,496 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>core-java</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>core-java</name>
<name>core-java</name>
<dependencies>
<dependencies>
<!-- utils -->
<dependency>
<groupId>net.sourceforge.collections</groupId>
<artifactId>collections-generic</artifactId>
<version>${collections-generic.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<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.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>org.decimal4j</groupId>
<artifactId>decimal4j</artifactId>
<version>${decimal4j.version}</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bouncycastle.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>
<!-- logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</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.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>2.1.0.1</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>1.19</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.19</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.4.RELEASE</version>
<groupId>net.sourceforge.collections</groupId>
<artifactId>collections-generic</artifactId>
<version>${collections-generic.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<plugins>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
</excludes>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
</configuration>
</plugin>
<dependency>
<groupId>org.decimal4j</groupId>
<artifactId>decimal4j</artifactId>
<version>${decimal4j.version}</version>
</dependency>
<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>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<dependency>
<groupId>org.unix4j</groupId>
<artifactId>unix4j-command</artifactId>
<version>${unix4j.version}</version>
</dependency>
<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>
<dependency>
<groupId>com.googlecode.grep4j</groupId>
<artifactId>grep4j</artifactId>
<version>${grep4j.version}</version>
</dependency>
<!-- web -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<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>
<!-- marshalling -->
<plugin>
<groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<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>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</configuration>
</execution>
</executions>
</plugin>
<!-- logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</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>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</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>
<!-- test scoped -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>2.1.0.1</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.196</version>
<scope>runtime</scope>
</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>1.19</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>1.5.8.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>core-java</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
</excludes>
</configuration>
</plugin>
<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>
<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>
<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>
<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>
<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>1.6.0</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>
</plugins>
</plugins>
</build>
</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>
</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>
<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>
</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>
<executions>
<execution>
<id>run-benchmarks</id>
<!-- <phase>integration-test</phase>-->
<phase>none</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath/>
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<executions>
<execution>
<id>run-benchmarks</id>
<!-- <phase>integration-test</phase> -->
<phase>none</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath />
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- marshalling -->
<jackson.version>2.8.5</jackson.version>
<properties>
<!-- marshalling -->
<jackson.version>2.8.5</jackson.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<!-- util -->
<guava.version>23.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version>
<commons-math3.version>3.6.1</commons-math3.version>
<decimal4j.version>1.0.3</decimal4j.version>
<commons-io.version>2.5</commons-io.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<lombok.version>1.16.12</lombok.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 -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>2.8.9</mockito.version>
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
<!-- util -->
<guava.version>22.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version>
<commons-math3.version>3.6.1</commons-math3.version>
<decimal4j.version>1.0.3</decimal4j.version>
<commons-io.version>2.5</commons-io.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<lombok.version>1.16.12</lombok.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>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
</project>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>2.8.9</mockito.version>
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,51 @@
package com.baeldung.jdbcrowset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetFactory;
import javax.sql.rowset.RowSetProvider;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
public class DatabaseConfiguration {
public static Connection geth2Connection() throws Exception {
Class.forName("org.h2.Driver");
System.out.println("Driver Loaded.");
String url = "jdbc:h2:mem:testdb";
return DriverManager.getConnection(url, "sa", "");
}
public static void initDatabase(Statement stmt) throws SQLException{
int iter = 1;
while(iter<=5){
String customer = "Customer"+iter;
String sql ="INSERT INTO customers(id, name) VALUES ("+iter+ ",'"+customer+"');";
System.out.println("here is sql statmeent for execution: " + sql);
stmt.executeUpdate(sql);
iter++;
}
int iterb = 1;
while(iterb<=5){
String associate = "Associate"+iter;
String sql = "INSERT INTO associates(id, name) VALUES("+iterb+",'"+associate+"');";
System.out.println("here is sql statement for associate:"+ sql);
stmt.executeUpdate(sql);
iterb++;
}
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.jdbcrowset;
import javax.sql.RowSetEvent;
import javax.sql.RowSetListener;
public class ExampleListener implements RowSetListener {
public void cursorMoved(RowSetEvent event) {
System.out.println("ExampleListener alerted of cursorMoved event");
System.out.println(event.toString());
}
public void rowChanged(RowSetEvent event) {
System.out.println("ExampleListener alerted of rowChanged event");
System.out.println(event.toString());
}
public void rowSetChanged(RowSetEvent event) {
System.out.println("ExampleListener alerted of rowSetChanged event");
System.out.println(event.toString());
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.jdbcrowset;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sql.RowSet;
import javax.sql.rowset.Predicate;
public class FilterExample implements Predicate {
private Pattern pattern;
public FilterExample(String regexQuery) {
if (regexQuery != null && !regexQuery.isEmpty()) {
pattern = Pattern.compile(regexQuery);
}
}
public boolean evaluate(RowSet rs) {
try {
if (!rs.isAfterLast()) {
String name = rs.getString("name");
System.out.println(String.format(
"Searching for pattern '%s' in %s", pattern.toString(),
name));
Matcher matcher = pattern.matcher(name);
return matcher.matches();
} else
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean evaluate(Object value, int column) throws SQLException {
throw new UnsupportedOperationException("This operation is unsupported.");
}
public boolean evaluate(Object value, String columnName)
throws SQLException {
throw new UnsupportedOperationException("This operation is unsupported.");
}
}

View File

@ -0,0 +1,139 @@
package com.baeldung.jdbcrowset;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import com.sun.rowset.*;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.FilteredRowSet;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.JoinRowSet;
import javax.sql.rowset.RowSetFactory;
import javax.sql.rowset.RowSetProvider;
import javax.sql.rowset.WebRowSet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JdbcRowsetApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(JdbcRowsetApplication.class, args);
Statement stmt = null;
try {
Connection conn = DatabaseConfiguration.geth2Connection();
String drop = "DROP TABLE IF EXISTS customers, associates;";
String schema = "CREATE TABLE customers (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id)); ";
String schemapartb = "CREATE TABLE associates (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id));";
stmt = conn.createStatement();
stmt.executeUpdate(drop);
stmt.executeUpdate(schema);
stmt.executeUpdate(schemapartb);
// insert data
DatabaseConfiguration.initDatabase(stmt);
// JdbcRowSet Example
String sql = "SELECT * FROM customers";
JdbcRowSet jdbcRS;
jdbcRS = new JdbcRowSetImpl(conn);
jdbcRS.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
jdbcRS.setCommand(sql);
jdbcRS.execute();
jdbcRS.addRowSetListener(new ExampleListener());
while (jdbcRS.next()) {
// each call to next, generates a cursorMoved event
System.out.println("id=" + jdbcRS.getString(1));
System.out.println("name=" + jdbcRS.getString(2));
}
// CachedRowSet Example
String username = "sa";
String password = "";
String url = "jdbc:h2:mem:testdb";
CachedRowSet crs = new CachedRowSetImpl();
crs.setUsername(username);
crs.setPassword(password);
crs.setUrl(url);
crs.setCommand(sql);
crs.execute();
crs.addRowSetListener(new ExampleListener());
while (crs.next()) {
if (crs.getInt("id") == 1) {
System.out.println("CRS found customer1 and will remove the record.");
crs.deleteRow();
break;
}
}
// WebRowSet example
WebRowSet wrs = new WebRowSetImpl();
wrs.setUsername(username);
wrs.setPassword(password);
wrs.setUrl(url);
wrs.setCommand(sql);
wrs.execute();
FileOutputStream ostream = new FileOutputStream("customers.xml");
wrs.writeXml(ostream);
// JoinRowSet example
CachedRowSetImpl customers = new CachedRowSetImpl();
customers.setUsername(username);
customers.setPassword(password);
customers.setUrl(url);
customers.setCommand(sql);
customers.execute();
CachedRowSetImpl associates = new CachedRowSetImpl();
associates.setUsername(username);
associates.setPassword(password);
associates.setUrl(url);
String associatesSQL = "SELECT * FROM associates";
associates.setCommand(associatesSQL);
associates.execute();
JoinRowSet jrs = new JoinRowSetImpl();
final String ID = "id";
final String NAME = "name";
jrs.addRowSet(customers, ID);
jrs.addRowSet(associates, ID);
jrs.last();
System.out.println("Total rows: " + jrs.getRow());
jrs.beforeFirst();
while (jrs.next()) {
String string1 = jrs.getString(ID);
String string2 = jrs.getString(NAME);
System.out.println("ID: " + string1 + ", NAME: " + string2);
}
// FilteredRowSet example
RowSetFactory rsf = RowSetProvider.newFactory();
FilteredRowSet frs = rsf.createFilteredRowSet();
frs.setCommand("select * from customers");
frs.execute(conn);
frs.setFilter(new FilterExample("^[A-C].*"));
ResultSetMetaData rsmd = frs.getMetaData();
int columncount = rsmd.getColumnCount();
while (frs.next()) {
for (int i = 1; i <= columncount; i++) {
System.out.println(rsmd.getColumnLabel(i) + " = " + frs.getObject(i) + " ");
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

View File

@ -1,11 +0,0 @@
package com.baeldung.nestedclass;
public class Enclosing {
public static class Nested {
public void test() {
System.out.println("Calling test...");
}
}
}

View File

@ -1,11 +0,0 @@
package com.baeldung.nestedclass;
public class Outer {
public class Inner {
public void test() {
System.out.println("Calling test...");
}
}
}

View File

@ -1,5 +0,0 @@
package com.baeldung.nestedclass;
abstract class SimpleAbstractClass {
abstract void run();
}

View File

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

View File

@ -0,0 +1,116 @@
package com.baeldung.array;
import org.junit.Test;
import java.util.*;
public class SearchArrayTest {
@Test
public void searchArrayAllocNewCollections() {
int count = 1000;
String[] strings = seedArray(count);
long startTime = System.nanoTime();
for (int i = 0; i < count; i++) {
searchList(strings, "W");
}
long duration = System.nanoTime() - startTime;
System.out.println("SearchList: " + duration / 10000);
startTime = System.nanoTime();
for (int i = 0; i < count; i++) {
searchSet(strings,"S");
}
duration = System.nanoTime() - startTime;
System.out.println("SearchSet: " + duration / 10000);
startTime = System.nanoTime();
for (int i = 0; i < count; i++) {
searchLoop(strings, "T");
}
duration = System.nanoTime() - startTime;
System.out.println("SearchLoop: " + duration / 10000);
}
@Test
public void searchArrayReuseCollections() {
int count = 10000;
String[] strings = seedArray(count);
List<String> asList = Arrays.asList(strings);
Set<String> asSet = new HashSet<>(Arrays.asList(strings));
long startTime = System.nanoTime();
for (int i = 0; i < count; i++) {
asList.contains("W");
}
long duration = System.nanoTime() - startTime;
System.out.println("List: " + duration / 10000);
startTime = System.nanoTime();
for (int i = 0; i < count; i++) {
asSet.contains("S");
}
duration = System.nanoTime() - startTime;
System.out.println("Set: " + duration / 10000);
startTime = System.nanoTime();
for (int i = 0; i < count; i++) {
searchLoop(strings, "T");
}
duration = System.nanoTime() - startTime;
System.out.println("Loop: " + duration / 10000);
}
@Test
public void searchArrayBinarySearch() {
int count = 10000;
String[] strings = seedArray(count);
Arrays.sort(strings);
long startTime = System.nanoTime();
for (int i = 0; i < count; i++) {
Arrays.binarySearch(strings, "A");
}
long duration = System.nanoTime() - startTime;
System.out.println("Binary search: " + duration / 10000);
}
private boolean searchList(String[] strings, String searchString) {
return Arrays.asList(strings).contains(searchString);
}
private boolean searchSet(String[] strings, String searchString) {
Set<String> set = new HashSet<>(Arrays.asList(strings));
return set.contains(searchString);
}
private boolean searchLoop(String[] strings, String searchString) {
for (String s : strings) {
if (s.equals(searchString))
return true;
}
return false;
}
private String[] seedArray(int length) {
String[] strings = new String[length];
Random random = new Random();
for (int i = 0; i < length; i++)
{
strings[i] = String.valueOf(random.nextInt());
}
return strings;
}
}

View File

@ -0,0 +1,93 @@
package com.baeldung.collection;
import java.util.ConcurrentModificationException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
public class WhenUsingHashSet {
@Test
public void whenAddingElement_shouldAddElement() {
Set<String> hashset = new HashSet<>();
Assert.assertTrue(hashset.add("String Added"));
}
@Test
public void whenCheckingForElement_shouldSearchForElement() {
Set<String> hashsetContains = new HashSet<>();
hashsetContains.add("String Added");
Assert.assertTrue(hashsetContains.contains("String Added"));
}
@Test
public void whenCheckingTheSizeOfHashSet_shouldReturnThesize() {
Set<String> hashSetSize = new HashSet<>();
hashSetSize.add("String Added");
Assert.assertEquals(1, hashSetSize.size());
}
@Test
public void whenCheckingForEmptyHashSet_shouldCheckForEmpty() {
Set<String> emptyHashSet = new HashSet<>();
Assert.assertTrue(emptyHashSet.isEmpty());
}
@Test
public void whenRemovingElement_shouldRemoveElement() {
Set<String> removeFromHashSet = new HashSet<>();
removeFromHashSet.add("String Added");
Assert.assertTrue(removeFromHashSet.remove("String Added"));
}
@Test
public void whenClearingHashSet_shouldClearHashSet() {
Set<String> clearHashSet = new HashSet<>();
clearHashSet.add("String Added");
clearHashSet.clear();
Assert.assertTrue(clearHashSet.isEmpty());
}
@Test
public void whenIteratingHashSet_shouldIterateHashSet() {
Set<String> hashset = new HashSet<>();
hashset.add("First");
hashset.add("Second");
hashset.add("Third");
Iterator<String> itr = hashset.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
@Test(expected = ConcurrentModificationException.class)
public void whenModifyingHashSetWhileIterating_shouldThrowException() {
Set<String> hashset = new HashSet<>();
hashset.add("First");
hashset.add("Second");
hashset.add("Third");
Iterator<String> itr = hashset.iterator();
while (itr.hasNext()) {
itr.next();
hashset.remove("Second");
}
}
@Test
public void whenRemovingElementUsingIterator_shouldRemoveElement() {
Set<String> hashset = new HashSet<>();
hashset.add("First");
hashset.add("Second");
hashset.add("Third");
Iterator<String> itr = hashset.iterator();
while (itr.hasNext()) {
String element = itr.next();
if (element.equals("Second"))
itr.remove();
}
Assert.assertEquals(2, hashset.size());
}
}

View File

@ -0,0 +1,157 @@
package com.baeldung.jdbcrowset;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.FilteredRowSet;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.JoinRowSet;
import javax.sql.rowset.RowSetFactory;
import javax.sql.rowset.RowSetProvider;
import javax.sql.rowset.WebRowSet;
import org.junit.Before;
import org.junit.Test;
import com.sun.rowset.CachedRowSetImpl;
import com.sun.rowset.JdbcRowSetImpl;
import com.sun.rowset.JoinRowSetImpl;
import com.sun.rowset.WebRowSetImpl;
public class JdbcRowSetTest {
Statement stmt = null;
String username = "sa";
String password = "";
String url = "jdbc:h2:mem:testdb";
String sql = "SELECT * FROM customers";
@Before
public void setup() throws Exception {
Connection conn = DatabaseConfiguration.geth2Connection();
String drop = "DROP TABLE IF EXISTS customers, associates;";
String schema = "CREATE TABLE customers (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id)); ";
String schemapartb = "CREATE TABLE associates (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id));";
stmt = conn.createStatement();
stmt.executeUpdate(drop);
stmt.executeUpdate(schema);
stmt.executeUpdate(schemapartb);
DatabaseConfiguration.initDatabase(stmt);
}
// JdbcRowSet Example
@Test
public void createJdbcRowSet_SelectCustomers_ThenCorrect() throws Exception {
String sql = "SELECT * FROM customers";
JdbcRowSet jdbcRS;
Connection conn = DatabaseConfiguration.geth2Connection();
jdbcRS = new JdbcRowSetImpl(conn);
jdbcRS.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
jdbcRS.setCommand(sql);
jdbcRS.execute();
jdbcRS.addRowSetListener(new ExampleListener());
while (jdbcRS.next()) {
// each call to next, generates a cursorMoved event
System.out.println("id=" + jdbcRS.getString(1));
System.out.println("name=" + jdbcRS.getString(2));
}
}
// CachedRowSet Example
@Test
public void createCachedRowSet_DeleteRecord_ThenCorrect() throws Exception {
CachedRowSet crs = new CachedRowSetImpl();
crs.setUsername(username);
crs.setPassword(password);
crs.setUrl(url);
crs.setCommand(sql);
crs.execute();
crs.addRowSetListener(new ExampleListener());
while (crs.next()) {
if (crs.getInt("id") == 1) {
System.out.println("CRS found customer1 and will remove the record.");
crs.deleteRow();
break;
}
}
}
// WebRowSet example
@Test
public void createWebRowSet_SelectCustomers_WritetoXML_ThenCorrect() throws SQLException, IOException {
WebRowSet wrs = new WebRowSetImpl();
wrs.setUsername(username);
wrs.setPassword(password);
wrs.setUrl(url);
wrs.setCommand(sql);
wrs.execute();
FileOutputStream ostream = new FileOutputStream("customers.xml");
wrs.writeXml(ostream);
}
// JoinRowSet example
@Test
public void createCachedRowSets_DoJoinRowSet_ThenCorrect() throws Exception {
CachedRowSetImpl customers = new CachedRowSetImpl();
customers.setUsername(username);
customers.setPassword(password);
customers.setUrl(url);
customers.setCommand(sql);
customers.execute();
CachedRowSetImpl associates = new CachedRowSetImpl();
associates.setUsername(username);
associates.setPassword(password);
associates.setUrl(url);
String associatesSQL = "SELECT * FROM associates";
associates.setCommand(associatesSQL);
associates.execute();
JoinRowSet jrs = new JoinRowSetImpl();
final String ID = "id";
final String NAME = "name";
jrs.addRowSet(customers, ID);
jrs.addRowSet(associates, ID);
jrs.last();
System.out.println("Total rows: " + jrs.getRow());
jrs.beforeFirst();
while (jrs.next()) {
String string1 = jrs.getString(ID);
String string2 = jrs.getString(NAME);
System.out.println("ID: " + string1 + ", NAME: " + string2);
}
}
// FilteredRowSet example
@Test
public void createFilteredRowSet_filterByRegexExpression_thenCorrect() throws Exception {
RowSetFactory rsf = RowSetProvider.newFactory();
FilteredRowSet frs = rsf.createFilteredRowSet();
frs.setCommand("select * from customers");
Connection conn = DatabaseConfiguration.geth2Connection();
frs.execute(conn);
frs.setFilter(new FilterExample("^[A-C].*"));
ResultSetMetaData rsmd = frs.getMetaData();
int columncount = rsmd.getColumnCount();
while (frs.next()) {
for (int i = 1; i <= columncount; i++) {
System.out.println(rsmd.getColumnLabel(i) + " = " + frs.getObject(i) + " ");
}
}
}
}

View File

@ -1,11 +1,38 @@
package com.baeldung.loops;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class WhenUsingLoops {
private LoopsInJava loops = new LoopsInJava();
private static List<String> list = new ArrayList<>();
private static Set<String> set = new HashSet<>();
private static Map<String, Integer> map = new HashMap<>();
@BeforeClass
public static void setUp() {
list.add("One");
list.add("Two");
list.add("Three");
set.add("Four");
set.add("Five");
set.add("Six");
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
}
@Test
public void shouldRunForLoop() {
@ -34,4 +61,47 @@ public class WhenUsingLoops {
int[] actual = loops.do_while_loop();
Assert.assertArrayEquals(expected, actual);
}
@Test
public void whenUsingSimpleFor_shouldIterateList() {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
@Test
public void whenUsingEnhancedFor_shouldIterateList() {
for (String item : list) {
System.out.println(item);
}
}
@Test
public void whenUsingEnhancedFor_shouldIterateSet() {
for (String item : set) {
System.out.println(item);
}
}
@Test
public void whenUsingEnhancedFor_shouldIterateMap() {
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + " - " + "Value: " + entry.getValue());
}
}
@Test
public void whenUsingSimpleFor_shouldRunLabelledLoop() {
aa: for (int i = 1; i <= 3; i++) {
if (i == 1)
continue;
bb: for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break aa;
}
System.out.println(i + " " + j);
}
}
}
}

View File

@ -2,10 +2,14 @@ package com.baeldung.nestedclass;
import org.junit.Test;
public class AnonymousInnerTest {
abstract class SimpleAbstractClass {
abstract void run();
}
public class AnonymousInner {
@Test
public void whenRunAnonymousClass_thenCorrect() {
public void run() {
SimpleAbstractClass simpleAbstractClass = new SimpleAbstractClass() {
void run() {
System.out.println("Running Anonymous Class...");

View File

@ -0,0 +1,21 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class Enclosing {
private static int x = 1;
public static class StaticNested {
private void run() {
System.out.println("x = " + x);
}
}
@Test
public void test() {
Enclosing.StaticNested nested = new Enclosing.StaticNested();
nested.run();
}
}

View File

@ -1,13 +0,0 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class InnerClassTest {
@Test
public void givenInnerClassWhenInstantiating_thenCorrect() {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.test();
}
}

View File

@ -1,12 +0,0 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class LocalClassTest {
@Test
public void whenTestingLocalClass_thenCorrect() {
NewEnclosing newEnclosing = new NewEnclosing();
newEnclosing.run();
}
}

View File

@ -1,12 +0,0 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class NestedClassTest {
@Test
public void whenInstantiatingStaticNestedClass_thenCorrect() {
Enclosing.Nested nested = new Enclosing.Nested();
nested.test();
}
}

View File

@ -1,10 +1,11 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class NewEnclosing {
void run() {
private void run() {
class Local {
void run() {
System.out.println("Welcome to Baeldung!");
}
@ -12,4 +13,10 @@ public class NewEnclosing {
Local local = new Local();
local.run();
}
@Test
public void test() {
NewEnclosing newEnclosing = new NewEnclosing();
newEnclosing.run();
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class NewOuter {
int a = 1;
static int b = 2;
public class InnerClass {
int a = 3;
static final int b = 4;
public void run() {
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("NewOuterTest.this.a = " + NewOuter.this.a);
System.out.println("NewOuterTest.b = " + NewOuter.b);
System.out.println("NewOuterTest.this.b = " + NewOuter.this.b);
}
}
@Test
public void test() {
NewOuter outer = new NewOuter();
NewOuter.InnerClass inner = outer.new InnerClass();
inner.run();
}
}

View File

@ -1,32 +0,0 @@
package com.baeldung.nestedclass;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class NewOuterTest {
int a = 1;
static int b = 2;
public class InnerClass {
int a = 3;
static final int b = 4;
@Test
public void whenShadowing_thenCorrect() {
assertEquals(3, a);
assertEquals(4, b);
assertEquals(1, NewOuterTest.this.a);
assertEquals(2, NewOuterTest.b);
assertEquals(2, NewOuterTest.this.b);
}
}
@Test
public void shadowingTest() {
NewOuterTest outer = new NewOuterTest();
NewOuterTest.InnerClass inner = outer.new InnerClass();
inner.whenShadowing_thenCorrect();
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class Outer {
public class Inner {
public void run() {
System.out.println("Calling test...");
}
}
@Test
public void test() {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.run();
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.kotlin
import org.junit.Assert
import org.junit.Test
class ExtensionMethods {
@Test
fun simpleExtensionMethod() {
fun String.escapeForXml() : String {
return this
.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
}
Assert.assertEquals("Nothing", "Nothing".escapeForXml())
Assert.assertEquals("&lt;Tag&gt;", "<Tag>".escapeForXml())
Assert.assertEquals("a&amp;b", "a&b".escapeForXml())
}
@Test
fun genericExtensionMethod() {
fun <T> T.concatAsString(b: T) : String {
return this.toString() + b.toString()
}
Assert.assertEquals("12", "1".concatAsString("2"))
Assert.assertEquals("12", 1.concatAsString(2))
// This doesn't compile
// Assert.assertEquals("12", 1.concatAsString(2.0))
}
@Test
fun infixExtensionMethod() {
infix fun Number.toPowerOf(exponent: Number): Double {
return Math.pow(this.toDouble(), exponent.toDouble())
}
Assert.assertEquals(9.0, 3 toPowerOf 2, 0.1)
Assert.assertEquals(3.0, 9 toPowerOf 0.5, 0.1)
}
@Test
fun operatorExtensionMethod() {
operator fun List<Int>.times(by: Int): List<Int> {
return this.map { it * by }
}
Assert.assertEquals(listOf(2, 4, 6), listOf(1, 2, 3) * 2)
}
}

View File

@ -11,7 +11,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<dependencies>

View File

@ -11,7 +11,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<dependencies>

View File

@ -11,7 +11,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<dependencies>

View File

@ -17,12 +17,15 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties>
<hibernate.version>5.2.12.Final</hibernate.version>
<mysql.version>6.0.6</mysql.version>
<mariaDB4j.version>2.2.3</mariaDB4j.version>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.12.Final</version>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
@ -40,6 +43,21 @@
<artifactId>h2</artifactId>
<version>1.4.194</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-spatial</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>ch.vorburger.mariaDB4j</groupId>
<artifactId>mariaDB4j</artifactId>
<version>${mariaDB4j.version}</version>
</dependency>
</dependencies>
<build>
<finalName>hibernate5</finalName>

View File

@ -5,6 +5,7 @@ import com.baeldung.hibernate.pojo.EntityDescription;
import com.baeldung.hibernate.pojo.OrderEntry;
import com.baeldung.hibernate.pojo.OrderEntryIdClass;
import com.baeldung.hibernate.pojo.OrderEntryPK;
import com.baeldung.hibernate.pojo.PointEntity;
import com.baeldung.hibernate.pojo.Product;
import com.baeldung.hibernate.pojo.Phone;
import com.baeldung.hibernate.pojo.TemporalValues;
@ -23,6 +24,7 @@ import com.baeldung.hibernate.pojo.inheritance.Person;
import com.baeldung.hibernate.pojo.inheritance.Pet;
import com.baeldung.hibernate.pojo.inheritance.Vehicle;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
@ -36,8 +38,14 @@ import java.util.Properties;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static String PROPERTY_FILE_NAME;
public static SessionFactory getSessionFactory() throws IOException {
return getSessionFactory(null);
}
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
PROPERTY_FILE_NAME = propertyFileName;
if (sessionFactory == null) {
ServiceRegistry serviceRegistry = configureServiceRegistry();
sessionFactory = makeSessionFactory(serviceRegistry);
@ -70,6 +78,7 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(Vehicle.class);
metadataSources.addAnnotatedClass(Car.class);
metadataSources.addAnnotatedClass(Bag.class);
metadataSources.addAnnotatedClass(PointEntity.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder()
@ -86,12 +95,11 @@ public class HibernateUtil {
private static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource("hibernate.properties");
.getContextClassLoader()
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.hibernate.pojo;
import com.vividsolutions.jts.geom.Point;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class PointEntity {
@Id
@GeneratedValue
private Long id;
private Point point;
public PointEntity() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Point getPoint() {
return point;
}
public void setPoint(Point point) {
this.point = point;
}
@Override
public String toString() {
return "PointEntity{" + "id=" + id + ", point=" + point + '}';
}
}

View File

@ -0,0 +1,97 @@
package com.baeldung.hibernate;
import com.baeldung.hibernate.pojo.PointEntity;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.persistence.Query;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class HibernateSpatialTest {
private Session session;
private Transaction transaction;
@Before
public void setUp() throws IOException {
session = HibernateUtil.getSessionFactory("hibernate-spatial.properties")
.openSession();
transaction = session.beginTransaction();
}
@After
public void tearDown() {
transaction.rollback();
session.close();
}
@Test
public void shouldConvertWktToGeometry() throws ParseException {
Geometry geometry = wktToGeometry("POINT (2 5)");
assertEquals("Point", geometry.getGeometryType());
assertTrue(geometry instanceof Point);
}
@Test
public void shouldInsertAndSelectPoints() throws ParseException {
PointEntity entity = new PointEntity();
entity.setPoint((Point) wktToGeometry("POINT (1 1)"));
session.persist(entity);
PointEntity fromDb = session.find(PointEntity.class, entity.getId());
assertEquals("POINT (1 1)", fromDb.getPoint().toString());
}
@Test
public void shouldSelectDisjointPoints() throws ParseException {
insertPoint("POINT (1 2)");
insertPoint("POINT (3 4)");
insertPoint("POINT (5 6)");
Point point = (Point) wktToGeometry("POINT (3 4)");
Query query = session.createQuery("select p from PointEntity p "
+ "where disjoint(p.point, :point) = true", PointEntity.class);
query.setParameter("point", point);
assertEquals("POINT (1 2)", ((PointEntity) query.getResultList().get(0)).getPoint().toString());
assertEquals("POINT (5 6)", ((PointEntity) query.getResultList().get(1)).getPoint().toString());
}
@Test
public void shouldSelectAllPointsWithinPolygon() throws ParseException {
insertPoint("POINT (1 1)");
insertPoint("POINT (1 2)");
insertPoint("POINT (3 4)");
insertPoint("POINT (5 6)");
Query query = session.createQuery("select p from PointEntity p where within(p.point, :area) = true",
PointEntity.class);
query.setParameter("area", wktToGeometry("POLYGON((0 0, 0 5, 5 5, 5 0, 0 0))"));
assertThat(query.getResultList().stream().map(p -> ((PointEntity) p).getPoint().toString()))
.containsOnly("POINT (1 1)", "POINT (1 2)", "POINT (3 4)");
}
private void insertPoint(String point) throws ParseException {
PointEntity entity = new PointEntity();
entity.setPoint((Point) wktToGeometry(point));
session.persist(entity);
}
private Geometry wktToGeometry(String wellKnownText) throws ParseException {
WKTReader fromText = new WKTReader();
Geometry geom = null;
geom = fromText.read(wellKnownText);
return geom;
}
}

View File

@ -0,0 +1,10 @@
hibernate.dialect=org.hibernate.spatial.dialect.mysql.MySQL56SpatialDialect
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/hibernate-spatial
hibernate.connection.username=root
hibernate.connection.password=pass
hibernate.connection.pool_size=5
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.max_fetch_depth=5
hibernate.hbm2ddl.auto=create-drop

BIN
libraries/helloWorld.docx Normal file

Binary file not shown.

View File

@ -711,4 +711,4 @@
<hazelcast.version>3.8.4</hazelcast.version>
<caffeine.version>2.5.5</caffeine.version>
</properties>
</project>
</project>

View File

@ -12,7 +12,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<dependencies>

View File

@ -11,7 +11,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<dependencies>

View File

@ -9,7 +9,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<dependencies>

View File

View File

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<name>logback</name>
<artifactId>logback</artifactId>
<version>0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<logback.version>1.2.3</logback.version>
</properties>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,14 @@
package com.baeldung.logback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Example {
private static final Logger logger = LoggerFactory.getLogger(Example.class);
public static void main(String[] args) {
logger.info("Example log from {}", Example.class.getSimpleName());
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.logback;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import java.util.HashMap;
import java.util.Map;
public class MapAppender extends AppenderBase<ILoggingEvent> {
private final Map<String, ILoggingEvent> eventMap = new HashMap<>();
private String prefix;
@Override
protected void append(final ILoggingEvent event) {
if (prefix == null || "".equals(prefix)) {
addError("Prefix is not set for MapAppender.");
return;
}
eventMap.put(prefix + System.currentTimeMillis(), event);
}
public String getPrefix() {
return prefix;
}
public void setPrefix(final String prefix) {
this.prefix = prefix;
}
public Map<String, ILoggingEvent> getEventMap() {
return eventMap;
}
}

View File

@ -0,0 +1,18 @@
<configuration>
<appender name="map" class="com.baeldung.logback.MapAppender">
<prefix>test</prefix>
</appender>
<appender name="out" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="map"/>
<appender-ref ref="out"/>
</root>
</configuration>

View File

@ -0,0 +1,33 @@
package com.baeldung.logback;
import ch.qos.logback.classic.Logger;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertEquals;
public class MapAppenderIntegrationTest {
private Logger rootLogger;
@Before
public void setUp() throws Exception {
rootLogger = (Logger) LoggerFactory.getLogger("ROOT");
}
@Test
public void whenLoggerEmitsLoggingEvent_thenAppenderReceivesEvent() throws Exception {
rootLogger.info("Test from {}", this.getClass().getSimpleName());
MapAppender appender = (MapAppender) rootLogger.getAppender("map");
assertEquals(appender.getEventMap().size(), 1);
}
@Test
public void givenNoPrefixSet_whenLoggerEmitsEvent_thenAppenderReceivesNoEvent() throws Exception {
rootLogger.info("Test from {}", this.getClass().getSimpleName());
MapAppender appender = (MapAppender) rootLogger.getAppender("badMap");
assertEquals(appender.getEventMap().size(), 0);
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.logback;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.BasicStatusManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class MapAppenderTest {
private LoggerContext ctx;
private MapAppender mapAppender = new MapAppender();
private LoggingEvent event;
@Before
public void setUp() throws Exception {
ctx = new LoggerContext();
ctx.setName("test context");
ctx.setStatusManager(new BasicStatusManager());
mapAppender.setContext(ctx);
mapAppender.setPrefix("prefix");
event = new LoggingEvent("fqcn", ctx.getLogger("logger"), Level.INFO, "Test message for logback appender", null, new Object[0]);
ctx.start();
}
@After
public void tearDown() throws Exception {
ctx.stop();
mapAppender.stop();
}
@Test
public void whenPrefixIsNull_thenMapAppenderDoesNotLog() throws Exception {
mapAppender.setPrefix(null);
mapAppender.append(event);
assertTrue(mapAppender.getEventMap().isEmpty());
}
@Test
public void whenPrefixIsEmpty_thenMapAppenderDoesNotLog() throws Exception {
mapAppender.setPrefix("");
mapAppender.append(event);
assertTrue(mapAppender.getEventMap().isEmpty());
}
@Test
public void whenLogMessageIsEmitted_thenMapAppenderReceivesMessage() throws Exception {
mapAppender.append(event);
assertEquals(mapAppender.getEventMap().size(), 1);
mapAppender.getEventMap().forEach((k, v) -> assertTrue(k.startsWith("prefix")));
}
}

View File

@ -0,0 +1,14 @@
<configuration debug="true">
<appender name="map" class="com.baeldung.logback.MapAppender">
<prefix>test</prefix>
</appender>
<appender name="badMap" class="com.baeldung.logback.MapAppender"/>
<root level="debug">
<appender-ref ref="map"/>
<appender-ref ref="badMap"/>
</root>
</configuration>

View File

@ -11,7 +11,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<dependencies>

View File

@ -11,7 +11,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<dependencies>

View File

@ -6,7 +6,7 @@
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -15,7 +15,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<properties>

View File

@ -15,7 +15,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<dependencies>

View File

@ -12,7 +12,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<properties>

View File

@ -13,7 +13,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<properties>

View File

@ -12,7 +12,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<properties>

View File

@ -10,7 +10,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<dependencies>

View File

@ -11,7 +11,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<properties>

View File

@ -12,7 +12,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<properties>

View File

@ -11,7 +11,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<dependencies>

View File

@ -11,7 +11,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<dependencies>
@ -57,6 +57,11 @@
<artifactId>jta</artifactId>
<version>${jta.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-orm</artifactId>
<version>${hibernatesearch.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
@ -184,6 +189,7 @@
<!-- persistence -->
<hibernate.version>5.2.10.Final</hibernate.version>
<hibernatesearch.version>5.8.2.Final</hibernatesearch.version>
<mysql-connector-java.version>8.0.7-dmr</mysql-connector-java.version>
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
<jta.version>1.1</jta.version>

View File

@ -0,0 +1,76 @@
package com.baeldung.hibernatesearch;
import com.google.common.base.Preconditions;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
@EnableTransactionManagement
@Configuration
@PropertySource({ "classpath:persistence-h2.properties" })
@EnableJpaRepositories(basePackages = { "com.baeldung.hibernatesearch" })
@ComponentScan({ "com.baeldung.hibernatesearch" })
public class HibernateSearchConfig {
@Autowired
private Environment env;
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.baeldung.hibernatesearch.model" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource() {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", Preconditions.checkNotNull(env.getProperty("hibernate.hbm2ddl.auto")));
properties.setProperty("hibernate.dialect", Preconditions.checkNotNull(env.getProperty("hibernate.dialect")));
return properties;
}
}

View File

@ -0,0 +1,195 @@
package com.baeldung.hibernatesearch;
import com.baeldung.hibernatesearch.model.Product;
import org.apache.lucene.search.Query;
import org.hibernate.search.engine.ProjectionConstants;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.FullTextQuery;
import org.hibernate.search.jpa.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
@Repository
public class ProductSearchDao {
@PersistenceContext
private EntityManager entityManager;
public List<Product> searchProductNameByKeywordQuery(String text) {
Query keywordQuery = getQueryBuilder()
.keyword()
.onField("productName")
.matching(text)
.createQuery();
List<Product> results = getJpaQuery(keywordQuery).getResultList();
return results;
}
public List<Product> searchProductNameByFuzzyQuery(String text) {
Query fuzzyQuery = getQueryBuilder()
.keyword()
.fuzzy()
.withEditDistanceUpTo(2)
.withPrefixLength(0)
.onField("productName")
.matching(text)
.createQuery();
List<Product> results = getJpaQuery(fuzzyQuery).getResultList();
return results;
}
public List<Product> searchProductNameByWildcardQuery(String text) {
Query wildcardQuery = getQueryBuilder()
.keyword()
.wildcard()
.onField("productName")
.matching(text)
.createQuery();
List<Product> results = getJpaQuery(wildcardQuery).getResultList();
return results;
}
public List<Product> searchProductDescriptionByPhraseQuery(String text) {
Query phraseQuery = getQueryBuilder()
.phrase()
.withSlop(1)
.onField("description")
.sentence(text)
.createQuery();
List<Product> results = getJpaQuery(phraseQuery).getResultList();
return results;
}
public List<Product> searchProductNameAndDescriptionBySimpleQueryStringQuery(String text) {
Query simpleQueryStringQuery = getQueryBuilder()
.simpleQueryString()
.onFields("productName", "description")
.matching(text)
.createQuery();
List<Product> results = getJpaQuery(simpleQueryStringQuery).getResultList();
return results;
}
public List<Product> searchProductNameByRangeQuery(int low, int high) {
Query rangeQuery = getQueryBuilder()
.range()
.onField("memory")
.from(low)
.to(high)
.createQuery();
List<Product> results = getJpaQuery(rangeQuery).getResultList();
return results;
}
public List<Object[]> searchProductNameByMoreLikeThisQuery(Product entity) {
Query moreLikeThisQuery = getQueryBuilder()
.moreLikeThis()
.comparingField("productName")
.toEntity(entity)
.createQuery();
List<Object[]> results = getJpaQuery(moreLikeThisQuery).setProjection(ProjectionConstants.THIS, ProjectionConstants.SCORE)
.getResultList();
return results;
}
public List<Product> searchProductNameAndDescriptionByKeywordQuery(String text) {
Query keywordQuery = getQueryBuilder()
.keyword()
.onFields("productName", "description")
.matching(text)
.createQuery();
List<Product> results = getJpaQuery(keywordQuery).getResultList();
return results;
}
public List<Object[]> searchProductNameAndDescriptionByMoreLikeThisQuery(Product entity) {
Query moreLikeThisQuery = getQueryBuilder()
.moreLikeThis()
.comparingField("productName")
.toEntity(entity)
.createQuery();
List<Object[]> results = getJpaQuery(moreLikeThisQuery).setProjection(ProjectionConstants.THIS, ProjectionConstants.SCORE)
.getResultList();
return results;
}
public List<Product> searchProductNameAndDescriptionByCombinedQuery(String manufactorer, int memoryLow, int memoryTop, String extraFeature, String exclude) {
Query combinedQuery = getQueryBuilder()
.bool()
.must(getQueryBuilder().keyword()
.onField("productName")
.matching(manufactorer)
.createQuery())
.must(getQueryBuilder()
.range()
.onField("memory")
.from(memoryLow)
.to(memoryTop)
.createQuery())
.should(getQueryBuilder()
.phrase()
.onField("description")
.sentence(extraFeature)
.createQuery())
.must(getQueryBuilder()
.keyword()
.onField("productName")
.matching(exclude)
.createQuery())
.not()
.createQuery();
List<Product> results = getJpaQuery(combinedQuery).getResultList();
return results;
}
private FullTextQuery getJpaQuery(org.apache.lucene.search.Query luceneQuery) {
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
return fullTextEntityManager.createFullTextQuery(luceneQuery, Product.class);
}
private QueryBuilder getQueryBuilder() {
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
return fullTextEntityManager.getSearchFactory()
.buildQueryBuilder()
.forEntity(Product.class)
.get();
}
}

View File

@ -0,0 +1,94 @@
package com.baeldung.hibernatesearch.model;
import org.hibernate.search.annotations.*;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Indexed
@Table(name = "product")
public class Product {
@Id
private int id;
@Field(termVector = TermVector.YES)
private String productName;
@Field(termVector = TermVector.YES)
private String description;
@Field
private int memory;
public Product(int id, String productName, int memory, String description) {
this.id = id;
this.productName = productName;
this.memory = memory;
this.description = description;
}
public Product() {
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Product))
return false;
Product product = (Product) o;
if (id != product.id)
return false;
if (memory != product.memory)
return false;
if (!productName.equals(product.productName))
return false;
return description.equals(product.description);
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + productName.hashCode();
result = 31 * result + memory;
result = 31 * result + description.hashCode();
return result;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getMemory() {
return memory;
}
public void setMemory(int memory) {
this.memory = memory;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -21,7 +21,7 @@ import java.util.Properties;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-h2.properties" })
@PropertySource({ "classpath:persistence-mysql.properties" })
@ComponentScan({ "com.baeldung.persistence" })
public class PersistenceConfig {

View File

@ -4,24 +4,12 @@
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hibernate.connection.password">
buddhinisam123
</property>
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/spring_hibernate_many_to_many
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.current_session_context_class">
thread
</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">tutorialmy5ql</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring_hibernate_many_to_many</property>
<property name="hibernate.connection.username">tutorialuser</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
</session-factory>
</hibernate-configuration>

View File

@ -9,5 +9,9 @@ hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop
# hibernate.search.X
hibernate.search.default.directory_provider = filesystem
hibernate.search.default.indexBase = /data/index/default
# envers.X
envers.audit_table_suffix=_audit_log

View File

@ -4,7 +4,6 @@ import com.baeldung.hibernate.immutable.entities.Event;
import com.baeldung.hibernate.immutable.entities.EventGeneratedId;
import com.baeldung.hibernate.immutable.util.HibernateUtil;
import com.google.common.collect.Sets;
import org.hibernate.CacheMode;
import org.hibernate.Session;
import org.junit.*;
import org.junit.rules.ExpectedException;
@ -14,6 +13,9 @@ import javax.persistence.PersistenceException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
/**
* Configured in: immutable.cfg.xml
*/
public class HibernateImmutableIntegrationTest {
private static Session session;
@ -98,6 +100,7 @@ public class HibernateImmutableIntegrationTest {
public void updateEventGenerated() {
createEventGenerated();
EventGeneratedId eventGeneratedId = (EventGeneratedId) session.createQuery("FROM EventGeneratedId WHERE name LIKE '%John%'").list().get(0);
eventGeneratedId.setName("Mike");
session.update(eventGeneratedId);
session.flush();
@ -115,7 +118,6 @@ public class HibernateImmutableIntegrationTest {
private static void createEventGenerated() {
EventGeneratedId eventGeneratedId = new EventGeneratedId("John", "Doe");
eventGeneratedId.setId(4L);
session.save(eventGeneratedId);
}

View File

@ -17,6 +17,9 @@ import com.baeldung.hibernate.manytomany.util.HibernateUtil;
import com.baeldung.hibernate.manytomany.model.Employee;
import com.baeldung.hibernate.manytomany.model.Project;
/**
* Configured in: manytomany.cfg.xml
*/
public class HibernateManyToManyAnnotationMainIntegrationTest {
private static SessionFactory sessionFactory;

View File

@ -0,0 +1,187 @@
package com.baeldung.hibernatesearch;
import com.baeldung.hibernatesearch.model.Product;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.junit.Assert.*;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.Search;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Commit;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { HibernateSearchConfig.class }, loader = AnnotationConfigContextLoader.class)
@Transactional
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class HibernateSearchIntegrationTest {
@Autowired
ProductSearchDao dao;
@PersistenceContext
private EntityManager entityManager;
private List<Product> products;
@Before
public void setupTestData() {
products = Arrays.asList(new Product(1, "Apple iPhone X 256 GB", 256, "The current high-end smartphone from Apple, with lots of memory and also Face ID"),
new Product(2, "Apple iPhone X 128 GB", 128, "The current high-end smartphone from Apple, with Face ID"), new Product(3, "Apple iPhone 8 128 GB", 128, "The latest smartphone from Apple within the regular iPhone line, supporting wireless charging"),
new Product(4, "Samsung Galaxy S7 128 GB", 64, "A great Android smartphone"), new Product(5, "Microsoft Lumia 650 32 GB", 32, "A cheaper smartphone, coming with Windows Mobile"),
new Product(6, "Microsoft Lumia 640 32 GB", 32, "A cheaper smartphone, coming with Windows Mobile"), new Product(7, "Microsoft Lumia 630 16 GB", 16, "A cheaper smartphone, coming with Windows Mobile"));
}
@Commit
@Test
public void testA_whenInitialTestDataInserted_thenSuccess() {
for (int i = 0; i < products.size() - 1; i++) {
entityManager.persist(products.get(i));
}
}
@Test
public void testB_whenIndexInitialized_thenCorrectIndexSize() throws InterruptedException {
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
fullTextEntityManager.createIndexer()
.startAndWait();
int indexSize = fullTextEntityManager.getSearchFactory()
.getStatistics()
.getNumberOfIndexedEntities(Product.class.getName());
assertEquals(products.size() - 1, indexSize);
}
@Commit
@Test
public void testC_whenAdditionalTestDataInserted_thenSuccess() {
entityManager.persist(products.get(products.size() - 1));
}
@Test
public void testD_whenAdditionalTestDataInserted_thenIndexUpdatedAutomatically() {
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
int indexSize = fullTextEntityManager.getSearchFactory()
.getStatistics()
.getNumberOfIndexedEntities(Product.class.getName());
assertEquals(products.size(), indexSize);
}
@Test
public void testE_whenKeywordSearchOnName_thenCorrectMatches() {
List<Product> expected = Arrays.asList(products.get(0), products.get(1), products.get(2));
List<Product> results = dao.searchProductNameByKeywordQuery("iphone");
assertThat(results, containsInAnyOrder(expected.toArray()));
}
@Test
public void testF_whenFuzzySearch_thenCorrectMatches() {
List<Product> expected = Arrays.asList(products.get(0), products.get(1), products.get(2));
List<Product> results = dao.searchProductNameByFuzzyQuery("iPhaen");
assertThat(results, containsInAnyOrder(expected.toArray()));
}
@Test
public void testG_whenWildcardSearch_thenCorrectMatches() {
List<Product> expected = Arrays.asList(products.get(4), products.get(5), products.get(6));
List<Product> results = dao.searchProductNameByWildcardQuery("6*");
assertThat(results, containsInAnyOrder(expected.toArray()));
}
@Test
public void testH_whenPhraseSearch_thenCorrectMatches() {
List<Product> expected = Arrays.asList(products.get(2));
List<Product> results = dao.searchProductDescriptionByPhraseQuery("with wireless charging");
assertThat(results, containsInAnyOrder(expected.toArray()));
}
@Test
public void testI_whenSimpleQueryStringSearch_thenCorrectMatches() {
List<Product> expected = Arrays.asList(products.get(0), products.get(1));
List<Product> results = dao.searchProductNameAndDescriptionBySimpleQueryStringQuery("Aple~2 + \"iPhone X\" + (256 | 128)");
assertThat(results, containsInAnyOrder(expected.toArray()));
}
@Test
public void testJ_whenRangeSearch_thenCorrectMatches() {
List<Product> expected = Arrays.asList(products.get(0), products.get(1), products.get(2), products.get(3));
List<Product> results = dao.searchProductNameByRangeQuery(64, 256);
assertThat(results, containsInAnyOrder(expected.toArray()));
}
@Test
public void testK_whenMoreLikeThisSearch_thenCorrectMatchesInOrder() {
List<Product> expected = products;
List<Object[]> resultsWithScore = dao.searchProductNameByMoreLikeThisQuery(products.get(0));
List<Product> results = new LinkedList<Product>();
for (Object[] resultWithScore : resultsWithScore) {
results.add((Product) resultWithScore[0]);
}
assertThat(results, contains(expected.toArray()));
}
@Test
public void testL_whenKeywordSearchOnNameAndDescription_thenCorrectMatches() {
List<Product> expected = Arrays.asList(products.get(0), products.get(1), products.get(2));
List<Product> results = dao.searchProductNameAndDescriptionByKeywordQuery("iphone");
assertThat(results, containsInAnyOrder(expected.toArray()));
}
@Test
public void testM_whenMoreLikeThisSearchOnProductNameAndDescription_thenCorrectMatchesInOrder() {
List<Product> expected = products;
List<Object[]> resultsWithScore = dao.searchProductNameAndDescriptionByMoreLikeThisQuery(products.get(0));
List<Product> results = new LinkedList<Product>();
for (Object[] resultWithScore : resultsWithScore) {
results.add((Product) resultWithScore[0]);
}
assertThat(results, contains(expected.toArray()));
}
@Test
public void testN_whenCombinedSearch_thenCorrectMatches() {
List<Product> expected = Arrays.asList(products.get(1), products.get(2));
List<Product> results = dao.searchProductNameAndDescriptionByCombinedQuery("apple", 64, 128, "face id", "samsung");
assertThat(results, containsInAnyOrder(expected.toArray()));
}
}

View File

@ -107,6 +107,7 @@
<module>logging-modules/log-mdc</module>
<module>logging-modules/log4j</module>
<module>logging-modules/log4j2</module>
<module>logging-modules/logback</module>
<module>lombok</module>
<!-- <module>kotlin</module>-->
<module>mapstruct</module>
@ -141,6 +142,7 @@
<module>spark-java</module>
<!-- <module>spring-5</module>-->
<module>spring-5-mvc</module>
<module>spring-acl</module>
<module>spring-activiti</module>
<module>spring-akka</module>
<module>spring-amqp</module>

View File

@ -10,4 +10,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Exploring the Spring 5 MVC URL Matching Improvements](http://www.baeldung.com/spring-5-mvc-url-matching)
- [Spring 5 WebClient](http://www.baeldung.com/spring-5-webclient)
- [Spring 5 Functional Bean Registration](http://www.baeldung.com/spring-5-functional-beans)
- [The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5](http://www.baeldung.com/spring-5-junit-config)

66
spring-acl/pom.xml Normal file
View File

@ -0,0 +1,66 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-acl</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>spring-acl</name>
<description>Spring ACL</description>
<parent>
<artifactId>parent-boot-5</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-5</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-acl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.11</version>
<type>jar</type>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,80 @@
package org.baeldung.acl.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cache.ehcache.EhCacheFactoryBean;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.acls.AclPermissionCacheOptimizer;
import org.springframework.security.acls.AclPermissionEvaluator;
import org.springframework.security.acls.domain.AclAuthorizationStrategy;
import org.springframework.security.acls.domain.AclAuthorizationStrategyImpl;
import org.springframework.security.acls.domain.ConsoleAuditLogger;
import org.springframework.security.acls.domain.DefaultPermissionGrantingStrategy;
import org.springframework.security.acls.domain.EhCacheBasedAclCache;
import org.springframework.security.acls.jdbc.BasicLookupStrategy;
import org.springframework.security.acls.jdbc.JdbcMutableAclService;
import org.springframework.security.acls.jdbc.LookupStrategy;
import org.springframework.security.acls.model.PermissionGrantingStrategy;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
@Configuration
@EnableAutoConfiguration
public class ACLContext {
@Autowired
DataSource dataSource;
@Bean
public EhCacheBasedAclCache aclCache() {
return new EhCacheBasedAclCache(aclEhCacheFactoryBean().getObject(), permissionGrantingStrategy(), aclAuthorizationStrategy());
}
@Bean
public EhCacheFactoryBean aclEhCacheFactoryBean() {
EhCacheFactoryBean ehCacheFactoryBean = new EhCacheFactoryBean();
ehCacheFactoryBean.setCacheManager(aclCacheManager().getObject());
ehCacheFactoryBean.setCacheName("aclCache");
return ehCacheFactoryBean;
}
@Bean
public EhCacheManagerFactoryBean aclCacheManager() {
return new EhCacheManagerFactoryBean();
}
@Bean
public PermissionGrantingStrategy permissionGrantingStrategy() {
return new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger());
}
@Bean
public AclAuthorizationStrategy aclAuthorizationStrategy() {
return new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_ADMIN"));
}
@Bean
public MethodSecurityExpressionHandler defaultMethodSecurityExpressionHandler() {
DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
AclPermissionEvaluator permissionEvaluator = new AclPermissionEvaluator(aclService());
expressionHandler.setPermissionEvaluator(permissionEvaluator);
expressionHandler.setPermissionCacheOptimizer(new AclPermissionCacheOptimizer(aclService()));
return expressionHandler;
}
@Bean
public LookupStrategy lookupStrategy() {
return new BasicLookupStrategy(dataSource, aclCache(), aclAuthorizationStrategy(), new ConsoleAuditLogger());
}
@Bean
public JdbcMutableAclService aclService() {
return new JdbcMutableAclService(dataSource, lookupStrategy(), aclCache());
}
}

View File

@ -0,0 +1,21 @@
package org.baeldung.acl.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class AclMethodSecurityConfiguration extends GlobalMethodSecurityConfiguration {
@Autowired
MethodSecurityExpressionHandler defaultMethodSecurityExpressionHandler;
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return defaultMethodSecurityExpressionHandler;
}
}

View File

@ -0,0 +1,16 @@
package org.baeldung.acl.config;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "org.baeldung.acl.persistence.dao")
@PropertySource("classpath:org.baeldung.acl.datasource.properties")
@EntityScan(basePackages={ "org.baeldung.acl.persistence.entity" })
public class JPAPersistenceConfig {
}

View File

@ -0,0 +1,24 @@
package org.baeldung.acl.persistence.dao;
import java.util.List;
import org.baeldung.acl.persistence.entity.NoticeMessage;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
public interface NoticeMessageRepository extends JpaRepository<NoticeMessage, Long>{
@PostFilter("hasPermission(filterObject, 'READ')")
List<NoticeMessage> findAll();
@PostAuthorize("hasPermission(returnObject, 'READ')")
NoticeMessage findById(Integer id);
@SuppressWarnings("unchecked")
@PreAuthorize("hasPermission(#noticeMessage, 'WRITE')")
NoticeMessage save(@Param("noticeMessage")NoticeMessage noticeMessage);
}

View File

@ -0,0 +1,29 @@
package org.baeldung.acl.persistence.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="system_message")
public class NoticeMessage {
@Id
@Column
private Integer id;
@Column
private String content;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}

View File

@ -0,0 +1,28 @@
INSERT INTO system_message(id,content) VALUES (1,'First Level Message');
INSERT INTO system_message(id,content) VALUES (2,'Second Level Message');
INSERT INTO system_message(id,content) VALUES (3,'Third Level Message');
INSERT INTO acl_class (id, class) VALUES
(1, 'org.baeldung.acl.persistence.entity.NoticeMessage');
INSERT INTO acl_sid (id, principal, sid) VALUES
(1, 1, 'manager'),
(2, 1, 'hr'),
(3, 1, 'admin'),
(4, 0, 'ROLE_EDITOR');
INSERT INTO acl_object_identity (id, object_id_class, object_id_identity, parent_object, owner_sid, entries_inheriting) VALUES
(1, 1, 1, NULL, 3, 0),
(2, 1, 2, NULL, 3, 0),
(3, 1, 3, NULL, 3, 0)
;
INSERT INTO acl_entry (id, acl_object_identity, ace_order, sid, mask, granting, audit_success, audit_failure) VALUES
(1, 1, 1, 1, 1, 1, 1, 1),
(2, 1, 2, 1, 2, 1, 1, 1),
(3, 1, 3, 4, 1, 1, 1, 1),
(4, 2, 1, 2, 1, 1, 1, 1),
(5, 2, 2, 4, 1, 1, 1, 1),
(6, 3, 1, 4, 1, 1, 1, 1),
(7, 3, 2, 4, 2, 1, 1, 1)
;

View File

@ -0,0 +1,58 @@
create table system_message (id integer not null, content varchar(255), primary key (id));
CREATE TABLE IF NOT EXISTS acl_sid (
id bigint(20) NOT NULL AUTO_INCREMENT,
principal tinyint(1) NOT NULL,
sid varchar(100) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY unique_uk_1 (sid,principal)
);
CREATE TABLE IF NOT EXISTS acl_class (
id bigint(20) NOT NULL AUTO_INCREMENT,
class varchar(255) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY unique_uk_2 (class)
);
CREATE TABLE IF NOT EXISTS acl_entry (
id bigint(20) NOT NULL AUTO_INCREMENT,
acl_object_identity bigint(20) NOT NULL,
ace_order int(11) NOT NULL,
sid bigint(20) NOT NULL,
mask int(11) NOT NULL,
granting tinyint(1) NOT NULL,
audit_success tinyint(1) NOT NULL,
audit_failure tinyint(1) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY unique_uk_4 (acl_object_identity,ace_order)
);
CREATE TABLE IF NOT EXISTS acl_object_identity (
id bigint(20) NOT NULL AUTO_INCREMENT,
object_id_class bigint(20) NOT NULL,
object_id_identity bigint(20) NOT NULL,
parent_object bigint(20) DEFAULT NULL,
owner_sid bigint(20) DEFAULT NULL,
entries_inheriting tinyint(1) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY unique_uk_3 (object_id_class,object_id_identity)
);
ALTER TABLE acl_entry
ADD FOREIGN KEY (acl_object_identity) REFERENCES acl_object_identity(id);
ALTER TABLE acl_entry
ADD FOREIGN KEY (sid) REFERENCES acl_sid(id);
--
-- Constraints for table acl_object_identity
--
ALTER TABLE acl_object_identity
ADD FOREIGN KEY (parent_object) REFERENCES acl_object_identity (id);
ALTER TABLE acl_object_identity
ADD FOREIGN KEY (object_id_class) REFERENCES acl_class (id);
ALTER TABLE acl_object_identity
ADD FOREIGN KEY (owner_sid) REFERENCES acl_sid (id);

View File

@ -0,0 +1,12 @@
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.h2.console.path=/myconsole
spring.h2.console.enabled=true
spring.datasource.initialize=true
spring.datasource.schema=classpath:acl-schema.sql
spring.datasource.data=classpath:acl-data.sql

View File

@ -0,0 +1,119 @@
package org.baeldung.acl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.List;
import org.baeldung.acl.persistence.dao.NoticeMessageRepository;
import org.baeldung.acl.persistence.entity.NoticeMessage;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import org.springframework.test.context.web.ServletTestExecutionListener;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TestExecutionListeners(listeners={ServletTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
WithSecurityContextTestExecutionListener.class})
public class SpringAclTest extends AbstractJUnit4SpringContextTests{
private static Integer FIRST_MESSAGE_ID = 1;
private static Integer SECOND_MESSAGE_ID = 2;
private static Integer THIRD_MESSAGE_ID = 3;
private static String EDITTED_CONTENT = "EDITED";
@Configuration
@ComponentScan("org.baeldung.acl.*")
public static class SpringConfig {
}
@Autowired
NoticeMessageRepository repo;
@Test
@WithMockUser(username="manager")
public void givenUsernameManager_whenFindAllMessage_thenReturnFirstMessage(){
List<NoticeMessage> details = repo.findAll();
assertNotNull(details);
assertEquals(1,details.size());
assertEquals(FIRST_MESSAGE_ID,details.get(0).getId());
}
@Test
@WithMockUser(username="manager")
public void givenUsernameManager_whenFindFirstMessageByIdAndUpdateFirstMessageContent_thenOK(){
NoticeMessage firstMessage = repo.findById(FIRST_MESSAGE_ID);
assertNotNull(firstMessage);
assertEquals(FIRST_MESSAGE_ID,firstMessage.getId());
firstMessage.setContent(EDITTED_CONTENT);
repo.save(firstMessage);
NoticeMessage editedFirstMessage = repo.findById(FIRST_MESSAGE_ID);
assertNotNull(editedFirstMessage);
assertEquals(FIRST_MESSAGE_ID,editedFirstMessage.getId());
assertEquals(EDITTED_CONTENT,editedFirstMessage.getContent());
}
@Test
@WithMockUser(username="hr")
public void givenUsernameHr_whenFindMessageById2_thenOK(){
NoticeMessage secondMessage = repo.findById(SECOND_MESSAGE_ID);
assertNotNull(secondMessage);
assertEquals(SECOND_MESSAGE_ID,secondMessage.getId());
}
@Test(expected=AccessDeniedException.class)
@WithMockUser(username="hr")
public void givenUsernameHr_whenUpdateMessageWithId2_thenFail(){
NoticeMessage secondMessage = new NoticeMessage();
secondMessage.setId(SECOND_MESSAGE_ID);
secondMessage.setContent(EDITTED_CONTENT);
repo.save(secondMessage);
}
@Test
@WithMockUser(roles={"EDITOR"})
public void givenRoleEditor_whenFindAllMessage_thenReturnThreeMessage(){
List<NoticeMessage> details = repo.findAll();
assertNotNull(details);
assertEquals(3,details.size());
}
@Test
@WithMockUser(roles={"EDITOR"})
public void givenRoleEditor_whenUpdateThirdMessage_thenOK(){
NoticeMessage thirdMessage = new NoticeMessage();
thirdMessage.setId(THIRD_MESSAGE_ID);
thirdMessage.setContent(EDITTED_CONTENT);
repo.save(thirdMessage);
}
@Test(expected=AccessDeniedException.class)
@WithMockUser(roles={"EDITOR"})
public void givenRoleEditor_whenFindFirstMessageByIdAndUpdateFirstMessageContent_thenFail(){
NoticeMessage firstMessage = repo.findById(FIRST_MESSAGE_ID);
assertNotNull(firstMessage);
assertEquals(FIRST_MESSAGE_ID,firstMessage.getId());
firstMessage.setContent(EDITTED_CONTENT);
repo.save(firstMessage);
}
}

View File

@ -19,6 +19,7 @@
<module>spring-cloud-stream</module>
<module>spring-cloud-connectors-heroku</module>
<module>spring-cloud-aws</module>
<module>spring-cloud-consul</module>
</modules>
<packaging>pom</packaging>

View File

@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<artifactId>spring-cloud-consul</artifactId>
<packaging>jar</packaging>
<name>spring-cloud-consul</name>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-all</artifactId>
<version>1.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-config</artifactId>
<version>1.3.0.RELEASE</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

@ -0,0 +1,16 @@
package com.baeldung.spring.cloud.consul.discovery;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class DiscoveryClientApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(DiscoveryClientApplication.class).web(true)
.run(args);
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.spring.cloud.consul.discovery;
import java.net.URI;
import java.util.Optional;
import javax.naming.ServiceUnavailableException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
@RestController
public class DiscoveryClientController {
@Autowired
private DiscoveryClient discoveryClient;
private final RestTemplate restTemplate = new RestTemplate();
@GetMapping("/discoveryClient")
public String discoveryPing() throws RestClientException, ServiceUnavailableException {
URI service = serviceUrl().map(s -> s.resolve("/ping"))
.orElseThrow(ServiceUnavailableException::new);
return restTemplate.getForEntity(service, String.class)
.getBody();
}
@GetMapping("/ping")
public String ping() {
return "pong";
}
@GetMapping("/my-health-check")
public ResponseEntity<String> myCustomCheck() {
return new ResponseEntity<>(HttpStatus.OK);
}
public Optional<URI> serviceUrl() {
return discoveryClient.getInstances("myApp")
.stream()
.findFirst()
.map(si -> si.getUri());
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.spring.cloud.consul.health;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
@SpringBootApplication
public class ServiceDiscoveryApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(ServiceDiscoveryApplication.class).web(true)
.run(args);
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.spring.cloud.consul.health;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ServiceDiscoveryController {
@GetMapping("/ping")
public String ping() {
return "pong";
}
@GetMapping("/my-health-check")
public ResponseEntity<String> myCustomCheck() {
String message = "Testing my healh check function";
return new ResponseEntity<>(message, HttpStatus.FORBIDDEN);
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.spring.cloud.consul.properties;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DistributedPropertiesApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(DistributedPropertiesApplication.class).web(true)
.run(args);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.spring.cloud.consul.properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DistributedPropertiesController {
@Value("${my.prop}")
String value;
@Autowired
private MyProperties properties;
@GetMapping("/getConfigFromValue")
public String getConfigFromValue() {
return value;
}
@GetMapping("/getConfigFromProperty")
public String getConfigFromProperty() {
return properties.getProp();
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.spring.cloud.consul.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
@RefreshScope
@Configuration
@ConfigurationProperties("my")
public class MyProperties {
private String prop;
public String getProp() {
return prop;
}
public void setProp(String prop) {
this.prop = prop;
}
}

View File

@ -0,0 +1,14 @@
spring:
application:
name: myApp
cloud:
consul:
host: localhost
port: 8500
discovery:
healthCheckPath: /my-health-check
healthCheckInterval: 20s
enabled: true
instanceId: ${spring.application.name}:${random.value}
server:
port: 0

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