Merge remote-tracking branch 'central/master'

This commit is contained in:
Graham Cox 2017-10-10 17:03:17 +01:00
commit 6c0d731870
115 changed files with 3264 additions and 948 deletions

View File

@ -34,6 +34,11 @@
<artifactId>jenetics</artifactId>
<version>3.7.0</version>
</dependency>
<dependency>
<groupId>org.jgrapht</groupId>
<artifactId>jgrapht-core</artifactId>
<version>1.0.1</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,38 @@
package com.baeldung.jgrapht;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.jgrapht.VertexFactory;
import org.jgrapht.alg.HamiltonianCycle;
import org.jgrapht.generate.CompleteGraphGenerator;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleWeightedGraph;
import org.junit.Before;
import org.junit.Test;
public class CompleteGraphTest {
static SimpleWeightedGraph<String, DefaultEdge> completeGraph;
static int size = 10;
@Before
public void createCompleteGraph() {
completeGraph = new SimpleWeightedGraph<>(DefaultEdge.class);
CompleteGraphGenerator<String, DefaultEdge> completeGenerator = new CompleteGraphGenerator<String, DefaultEdge>(size);
VertexFactory<String> vFactory = new VertexFactory<String>() {
private int id = 0;
public String createVertex() {
return "v" + id++;
}
};
completeGenerator.generateGraph(completeGraph, vFactory, null);
}
@Test
public void givenCompleteGraph_whenGetHamiltonianCyclePath_thenGetVerticeListInSequence() {
List<String> verticeList = HamiltonianCycle.getApproximateOptimalForCompleteGraph(completeGraph);
assertEquals(verticeList.size(), completeGraph.vertexSet().size());
}
}

View File

@ -0,0 +1,95 @@
package com.baeldung.jgrapht;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.IntStream;
import org.jgrapht.DirectedGraph;
import org.jgrapht.GraphPath;
import org.jgrapht.alg.CycleDetector;
import org.jgrapht.alg.KosarajuStrongConnectivityInspector;
import org.jgrapht.alg.interfaces.StrongConnectivityAlgorithm;
import org.jgrapht.alg.shortestpath.AllDirectedPaths;
import org.jgrapht.alg.shortestpath.BellmanFordShortestPath;
import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.DirectedSubgraph;
import org.jgrapht.traverse.BreadthFirstIterator;
import org.jgrapht.traverse.DepthFirstIterator;
import org.junit.Before;
import org.junit.Test;
public class DirectedGraphTests {
DirectedGraph<String, DefaultEdge> directedGraph;
@Before
public void createDirectedGraph() {
directedGraph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
IntStream.range(1, 10).forEach(i -> {
directedGraph.addVertex("v" + i);
});
directedGraph.addEdge("v1", "v2");
directedGraph.addEdge("v2", "v4");
directedGraph.addEdge("v4", "v3");
directedGraph.addEdge("v3", "v1");
directedGraph.addEdge("v5", "v4");
directedGraph.addEdge("v5", "v6");
directedGraph.addEdge("v6", "v7");
directedGraph.addEdge("v7", "v5");
directedGraph.addEdge("v8", "v5");
directedGraph.addEdge("v9", "v8");
}
@Test
public void givenDirectedGraph_whenGetStronglyConnectedSubgraphs_thenPathExistsBetweenStronglyconnectedVertices() {
StrongConnectivityAlgorithm<String, DefaultEdge> scAlg = new KosarajuStrongConnectivityInspector<>(directedGraph);
List<DirectedSubgraph<String, DefaultEdge>> stronglyConnectedSubgraphs = scAlg.stronglyConnectedSubgraphs();
List<String> stronglyConnectedVertices = new ArrayList<>(stronglyConnectedSubgraphs.get(3).vertexSet());
String randomVertex1 = stronglyConnectedVertices.get(0);
String randomVertex2 = stronglyConnectedVertices.get(3);
AllDirectedPaths<String, DefaultEdge> allDirectedPaths = new AllDirectedPaths<>(directedGraph);
List<GraphPath<String, DefaultEdge>> possiblePathList = allDirectedPaths.getAllPaths(randomVertex1, randomVertex2, false, stronglyConnectedVertices.size());
assertTrue(possiblePathList.size() > 0);
}
@Test
public void givenDirectedGraphWithCycle_whenCheckCycles_thenDetectCycles() {
CycleDetector<String, DefaultEdge> cycleDetector = new CycleDetector<String, DefaultEdge>(directedGraph);
assertTrue(cycleDetector.detectCycles());
Set<String> cycleVertices = cycleDetector.findCycles();
assertTrue(cycleVertices.size() > 0);
}
@Test
public void givenDirectedGraph_whenCreateInstanceDepthFirstIterator_thenGetIterator() {
DepthFirstIterator depthFirstIterator = new DepthFirstIterator<>(directedGraph);
assertNotNull(depthFirstIterator);
}
@Test
public void givenDirectedGraph_whenCreateInstanceBreadthFirstIterator_thenGetIterator() {
BreadthFirstIterator breadthFirstIterator = new BreadthFirstIterator<>(directedGraph);
assertNotNull(breadthFirstIterator);
}
@Test
public void givenDirectedGraph_whenGetDijkstraShortestPath_thenGetNotNullPath() {
DijkstraShortestPath dijkstraShortestPath = new DijkstraShortestPath(directedGraph);
List<String> shortestPath = dijkstraShortestPath.getPath("v1", "v4").getVertexList();
assertNotNull(shortestPath);
}
@Test
public void givenDirectedGraph_whenGetBellmanFordShortestPath_thenGetNotNullPath() {
BellmanFordShortestPath bellmanFordShortestPath = new BellmanFordShortestPath(directedGraph);
List<String> shortestPath = bellmanFordShortestPath.getPath("v1", "v4").getVertexList();
assertNotNull(shortestPath);
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.jgrapht;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.stream.IntStream;
import org.jgrapht.GraphPath;
import org.jgrapht.alg.cycle.HierholzerEulerianCycle;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleWeightedGraph;
import org.junit.Before;
import org.junit.Test;
public class EulerianCircuitTest {
SimpleWeightedGraph<String, DefaultEdge> simpleGraph;
@Before
public void createGraphWithEulerianCircuit() {
simpleGraph = new SimpleWeightedGraph<>(DefaultEdge.class);
IntStream.range(1, 6).forEach(i -> {
simpleGraph.addVertex("v" + i);
});
IntStream.range(1, 6).forEach(i -> {
int endVertexNo = (i + 1) > 5 ? 1 : i + 1;
simpleGraph.addEdge("v" + i, "v" + endVertexNo);
});
}
@Test
public void givenGraph_whenCheckEluerianCycle_thenGetResult() {
HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>();
assertTrue(eulerianCycle.isEulerian(simpleGraph));
}
@Test
public void givenGraphWithEulerianCircuit_whenGetEulerianCycle_thenGetGraphPath() {
HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>();
GraphPath path = eulerianCycle.getEulerianCycle(simpleGraph);
assertTrue(path.getEdgeList().containsAll(simpleGraph.edgeSet()));
}
}

View File

@ -0,0 +1,57 @@
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>animal-sniffer-mvn-plugin</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>example-animal-sniffer-mvn-plugin</name>
<url>http://maven.apache.org</url>
<properties>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>animal-sniffer-maven-plugin</artifactId>
<version>1.16</version>
<configuration>
<signature>
<groupId>org.codehaus.mojo.signature</groupId>
<artifactId>java16</artifactId>
<version>1.0</version>
</signature>
</configuration>
<executions>
<execution>
<id>animal-sniffer</id>
<phase>verify</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,16 @@
package com.baeldung;
//import java.nio.charset.StandardCharsets;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
//System.out.println(StandardCharsets.UTF_8.name());
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}

View File

@ -0,0 +1,256 @@
package com.baeldung.apachecayenne;
import com.baeldung.apachecayenne.persistent.Author;
import org.apache.cayenne.ObjectContext;
import org.apache.cayenne.QueryResponse;
import org.apache.cayenne.configuration.server.ServerRuntime;
import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
import org.apache.cayenne.query.*;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class CayenneAdvancedOperationTests {
private static ObjectContext context = null;
@BeforeClass
public static void setupTheCayenneContext() {
ServerRuntime cayenneRuntime = ServerRuntime.builder()
.addConfig("cayenne-project.xml")
.build();
context = cayenneRuntime.newContext();
}
@Before
public void saveThreeAuthors() {
Author authorOne = context.newObject(Author.class);
authorOne.setName("Paul Xavier");
Author authorTwo = context.newObject(Author.class);
authorTwo.setName("pAuL Smith");
Author authorThree = context.newObject(Author.class);
authorThree.setName("Vicky Sarra");
context.commitChanges();
}
@After
public void deleteAllAuthors() {
SQLTemplate deleteAuthors = new SQLTemplate(Author.class, "delete from author");
context.performGenericQuery(deleteAuthors);
}
@Test
public void givenAuthors_whenFindAllSQLTmplt_thenWeGetThreeAuthors() {
SQLTemplate select = new SQLTemplate(Author.class, "select * from Author");
List<Author> authors = context.performQuery(select);
assertEquals(authors.size(), 3);
}
@Test
public void givenAuthors_whenFindByNameSQLTmplt_thenWeGetOneAuthor() {
SQLTemplate select = new SQLTemplate(Author.class, "select * from Author where name = 'Vicky Sarra'");
List<Author> authors = context.performQuery(select);
Author author = authors.get(0);
assertEquals(authors.size(), 1);
assertEquals(author.getName(), "Vicky Sarra");
}
@Test
public void givenAuthors_whenLikeSltQry_thenWeGetOneAuthor() {
Expression qualifier = ExpressionFactory.likeExp(Author.NAME.getName(), "Paul%");
SelectQuery query = new SelectQuery(Author.class, qualifier);
List<Author> authorsTwo = context.performQuery(query);
assertEquals(authorsTwo.size(), 1);
}
@Test
public void givenAuthors_whenCtnsIgnorCaseSltQry_thenWeGetTwoAuthors() {
Expression qualifier = ExpressionFactory.containsIgnoreCaseExp(Author.NAME.getName(), "Paul");
SelectQuery query = new SelectQuery(Author.class, qualifier);
List<Author> authors = context.performQuery(query);
assertEquals(authors.size(), 2);
}
@Test
public void givenAuthors_whenCtnsIgnorCaseEndsWSltQry_thenWeGetTwoAuthors() {
Expression qualifier = ExpressionFactory.containsIgnoreCaseExp(Author.NAME.getName(), "Paul")
.andExp(ExpressionFactory.endsWithExp(Author.NAME.getName(), "h"));
SelectQuery query = new SelectQuery(Author.class, qualifier);
List<Author> authors = context.performQuery(query);
Author author = authors.get(0);
assertEquals(authors.size(), 1);
assertEquals(author.getName(), "pAuL Smith");
}
@Test
public void givenAuthors_whenAscOrderingSltQry_thenWeGetOrderedAuthors() {
SelectQuery query = new SelectQuery(Author.class);
query.addOrdering(Author.NAME.asc());
List<Author> authors = query.select(context);
Author firstAuthor = authors.get(0);
assertEquals(authors.size(), 3);
assertEquals(firstAuthor.getName(), "Paul Xavier");
}
@Test
public void givenAuthors_whenDescOrderingSltQry_thenWeGetOrderedAuthors() {
SelectQuery query = new SelectQuery(Author.class);
query.addOrdering(Author.NAME.desc());
List<Author> authors = query.select(context);
Author firstAuthor = authors.get(0);
assertEquals(authors.size(), 3);
assertEquals(firstAuthor.getName(), "pAuL Smith");
}
@Test
public void givenAuthors_onContainsObjS_thenWeGetOneRecord() {
List<Author> authors = ObjectSelect.query(Author.class)
.where(Author.NAME.contains("Paul"))
.select(context);
assertEquals(authors.size(), 1);
}
@Test
public void givenAuthors_whenLikeObjS_thenWeGetTwoAuthors() {
List<Author> authors = ObjectSelect.query(Author.class)
.where(Author.NAME.likeIgnoreCase("Paul%"))
.select(context);
assertEquals(authors.size(), 2);
}
@Test
public void givenTwoAuthor_whenEndsWithObjS_thenWeGetOrderedAuthors() {
List<Author> authors = ObjectSelect.query(Author.class)
.where(Author.NAME.endsWith("Sarra"))
.select(context);
Author firstAuthor = authors.get(0);
assertEquals(authors.size(), 1);
assertEquals(firstAuthor.getName(), "Vicky Sarra");
}
@Test
public void givenTwoAuthor_whenInObjS_thenWeGetAuthors() {
List<String> names = Arrays.asList("Paul Xavier", "pAuL Smith", "Vicky Sarra");
List<Author> authors = ObjectSelect.query(Author.class)
.where(Author.NAME.in(names))
.select(context);
assertEquals(authors.size(), 3);
}
@Test
public void givenTwoAuthor_whenNinObjS_thenWeGetAuthors() {
List<String> names = Arrays.asList("Paul Xavier", "pAuL Smith");
List<Author> authors = ObjectSelect.query(Author.class)
.where(Author.NAME.nin(names))
.select(context);
Author author = authors.get(0);
assertEquals(authors.size(), 1);
assertEquals(author.getName(), "Vicky Sarra");
}
@Test
public void givenTwoAuthor_whenIsNotNullObjS_thenWeGetAuthors() {
List<Author> authors = ObjectSelect.query(Author.class)
.where(Author.NAME.isNotNull())
.select(context);
assertEquals(authors.size(), 3);
}
@Test
public void givenAuthors_whenFindAllEJBQL_thenWeGetThreeAuthors() {
EJBQLQuery query = new EJBQLQuery("select a FROM Author a");
List<Author> authors = context.performQuery(query);
assertEquals(authors.size(), 3);
}
@Test
public void givenAuthors_whenFindByNameEJBQL_thenWeGetOneAuthor() {
EJBQLQuery query = new EJBQLQuery("select a FROM Author a WHERE a.name = 'Vicky Sarra'");
List<Author> authors = context.performQuery(query);
Author author = authors.get(0);
assertEquals(authors.size(), 1);
assertEquals(author.getName(), "Vicky Sarra");
}
@Test
public void givenAuthors_whenUpdadingByNameEJBQL_thenWeGetTheUpdatedAuthor() {
EJBQLQuery query = new EJBQLQuery("UPDATE Author AS a SET a.name = 'Vicky Edison' WHERE a.name = 'Vicky Sarra'");
QueryResponse queryResponse = context.performGenericQuery(query);
EJBQLQuery queryUpdatedAuthor = new EJBQLQuery("select a FROM Author a WHERE a.name = 'Vicky Edison'");
List<Author> authors = context.performQuery(queryUpdatedAuthor);
Author author = authors.get(0);
assertNotNull(author);
}
@Test
public void givenAuthors_whenSeletingNamesEJBQL_thenWeGetListWithSizeThree() {
String [] args = {"Paul Xavier", "pAuL Smith", "Vicky Sarra"};
List<String> names = Arrays.asList(args);
EJBQLQuery query = new EJBQLQuery("select a.name FROM Author a");
List<String> nameList = context.performQuery(query);
Collections.sort(names);
Collections.sort(nameList);
assertEquals(names.size(), 3);
assertEquals(nameList.size(), 3);
assertEquals(names, nameList);
}
@Test
public void givenAuthors_whenDeletingAllWithEJB_thenWeGetNoAuthor() {
EJBQLQuery deleteQuery = new EJBQLQuery("delete FROM Author");
EJBQLQuery findAllQuery = new EJBQLQuery("select a FROM Author a");
context.performQuery(deleteQuery);
List<Author> objects = context.performQuery(findAllQuery);
assertEquals(objects.size(), 0);
}
@Test
public void givenAuthors_whenInsertingSQLExec_thenWeGetNewAuthor() {
int inserted = SQLExec
.query("INSERT INTO Author (name) VALUES ('Baeldung')")
.update(context);
assertEquals(inserted, 1);
}
@Test
public void givenAuthors_whenUpdatingSQLExec_thenItsUpdated() {
int updated = SQLExec
.query("UPDATE Author SET name = 'Baeldung' WHERE name = 'Vicky Sarra'")
.update(context);
assertEquals(updated, 1);
}
}

1
atomix/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

46
atomix/pom.xml Normal file
View File

@ -0,0 +1,46 @@
<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.atomix.io</groupId>
<artifactId>atomix</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>io.atomix</groupId>
<artifactId>atomix-all</artifactId>
<version>1.0.0-rc9</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,27 @@
package com.atomix.example;
import io.atomix.AtomixReplica;
import io.atomix.catalyst.transport.Address;
import io.atomix.catalyst.transport.netty.NettyTransport;
import io.atomix.copycat.server.storage.Storage;
import io.atomix.copycat.server.storage.StorageLevel;
import java.io.File;
import java.util.concurrent.CompletableFuture;
public class BootstrapingCluster {
public static void main(String[] args) {
Storage storage = Storage.builder()
.withDirectory(new File("log"))
.withStorageLevel(StorageLevel.DISK)
.build();
AtomixReplica replica = AtomixReplica.builder(new Address("localhost", 8700))
.withStorage(storage)
.withTransport(new NettyTransport())
.build();
CompletableFuture<AtomixReplica> completableFuture = replica.bootstrap();
completableFuture.join();
}
}

View File

@ -0,0 +1,71 @@
package com.atomix.example;
import io.atomix.AtomixReplica;
import io.atomix.catalyst.transport.Address;
import io.atomix.catalyst.transport.netty.NettyTransport;
import io.atomix.concurrent.DistributedLock;
import io.atomix.copycat.server.storage.Storage;
import io.atomix.copycat.server.storage.StorageLevel;
import java.io.File;
import java.util.Arrays;
import java.util.List;
public class OtherNodes {
public static void main(String[] args) throws InterruptedException {
List<Address> cluster = Arrays
.asList(
new Address("localhost", 8700),
new Address("localhost", 8701),
new Address("localhost", 8702));
Storage storage = Storage.builder()
.withDirectory(new File("log"))
.withStorageLevel(StorageLevel.DISK)
.build();
AtomixReplica replica2 = AtomixReplica.builder(new Address("localhost", 8701))
.withStorage(storage)
.withTransport(new NettyTransport())
.build();
WorkerThread WT1 = new WorkerThread(replica2, cluster);
WT1.run();
AtomixReplica replica3 = AtomixReplica.builder(new Address("localhost", 8702))
.withStorage(storage)
.withTransport(new NettyTransport())
.build();
WorkerThread WT2 = new WorkerThread(replica3, cluster);
WT2.run();
Thread.sleep(6000);
DistributedLock lock = replica2.getLock("my-lock")
.join();
lock.lock()
.thenRun(() -> System.out.println("Acquired a lock"));
replica2.getMap("map")
.thenCompose(m -> m.put("bar", "Hello world!"))
.thenRun(() -> System.out.println("Value is set in Distributed Map"))
.join();
}
private static class WorkerThread extends Thread {
private AtomixReplica replica;
private List<Address> cluster;
WorkerThread(AtomixReplica replica, List<Address> cluster) {
this.replica = replica;
this.cluster = cluster;
}
public void run() {
replica.join(cluster)
.join();
}
}
}

View File

@ -0,0 +1,35 @@
package com.atomix.exampletest;
import io.atomix.AtomixClient;
import io.atomix.catalyst.transport.Address;
import io.atomix.catalyst.transport.netty.NettyTransport;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import static org.junit.Assert.assertEquals;
public class AtomixClientLiveTest {
private final AtomixClient client = AtomixClient.builder()
.withTransport(new NettyTransport())
.build();
@Test
public void whenBootstrap_thenShouldGet() throws InterruptedException, ExecutionException {
List<Address> cluster = Arrays.asList(
new Address("localhost", 8700),
new Address("localhsot", 8701));
String value = client.connect(cluster)
.thenRun(() -> System.out.println("Client Connected"))
.thenCompose(c -> client.getMap("map"))
.thenCompose(m -> m.get("bar"))
.thenApply(a -> (String) a)
.get();
assertEquals("Hello world!", value);
}
}

View File

@ -10,6 +10,7 @@ import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class DirectoryWatcherExample {
public static void main(String[] args) throws IOException, InterruptedException {
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get(System.getProperty("user.home"));
@ -21,5 +22,8 @@ public class DirectoryWatcherExample {
}
key.reset();
}
watchService.close();
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.string;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class StringTest {
@Test
public void whenCallCodePointAt_thenDecimalUnicodeReturned() {
assertEquals(97, "abcd".codePointAt(0));
}
@Test
public void whenCallConcat_thenCorrect() {
assertEquals("elephant", "elep".concat("hant"));
}
@Test
public void whenGetBytes_thenCorrect() {
byte[] byteArray = "abcd".getBytes();
byte[] expected = new byte[] { 97, 98, 99, 100 };
assertArrayEquals(expected, byteArray);
}
}

5
deeplearning4j/README.md Normal file
View File

@ -0,0 +1,5 @@
### Sample deeplearning4j Project
This is a sample project for the [deeplearning4j](https://deeplearning4j.org) library.
### Relevant Articles:
- [A Guide to deeplearning4j](http://www.baeldung.com/a-guide-to-deeplearning4j/)

33
deeplearning4j/pom.xml Normal file
View File

@ -0,0 +1,33 @@
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.deeplearning4j</groupId>
<artifactId>deeplearning4j</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>deeplearning4j</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<dl4j.version>0.9.1</dl4j.version>
</properties>
<dependencies>
<dependency>
<groupId>org.nd4j</groupId>
<artifactId>nd4j-native-platform</artifactId>
<version>${dl4j.version}</version>
</dependency>
<dependency>
<groupId>org.deeplearning4j</groupId>
<artifactId>deeplearning4j-core</artifactId>
<version>${dl4j.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,80 @@
package com.baeldung.deeplearning4j;
import org.datavec.api.records.reader.RecordReader;
import org.datavec.api.records.reader.impl.csv.CSVRecordReader;
import org.datavec.api.split.FileSplit;
import org.datavec.api.util.ClassPathResource;
import org.deeplearning4j.datasets.datavec.RecordReaderDataSetIterator;
import org.deeplearning4j.eval.Evaluation;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.layers.DenseLayer;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.dataset.SplitTestAndTrain;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import org.nd4j.linalg.dataset.api.preprocessor.DataNormalization;
import org.nd4j.linalg.dataset.api.preprocessor.NormalizerStandardize;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import java.io.IOException;
public class IrisClassifier {
private static final int CLASSES_COUNT = 3;
private static final int FEATURES_COUNT = 4;
public static void main(String[] args) throws IOException, InterruptedException {
DataSet allData;
try (RecordReader recordReader = new CSVRecordReader(0, ',')) {
recordReader.initialize(new FileSplit(new ClassPathResource("iris.txt").getFile()));
DataSetIterator iterator = new RecordReaderDataSetIterator(recordReader, 150, FEATURES_COUNT, CLASSES_COUNT);
allData = iterator.next();
}
allData.shuffle(42);
DataNormalization normalizer = new NormalizerStandardize();
normalizer.fit(allData);
normalizer.transform(allData);
SplitTestAndTrain testAndTrain = allData.splitTestAndTrain(0.65);
DataSet trainingData = testAndTrain.getTrain();
DataSet testData = testAndTrain.getTest();
MultiLayerConfiguration configuration = new NeuralNetConfiguration.Builder()
.iterations(1000)
.activation(Activation.TANH)
.weightInit(WeightInit.XAVIER)
.learningRate(0.1)
.regularization(true).l2(0.0001)
.list()
.layer(0, new DenseLayer.Builder().nIn(FEATURES_COUNT).nOut(3)
.build())
.layer(1, new DenseLayer.Builder().nIn(3).nOut(3)
.build())
.layer(2, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.activation(Activation.SOFTMAX)
.nIn(3).nOut(CLASSES_COUNT).build())
.backprop(true).pretrain(false)
.build();
MultiLayerNetwork model = new MultiLayerNetwork(configuration);
model.init();
model.fit(trainingData);
INDArray output = model.output(testData.getFeatureMatrix());
Evaluation eval = new Evaluation(CLASSES_COUNT);
eval.eval(testData.getLabels(), output);
System.out.println(eval.stats());
}
}

View File

@ -0,0 +1,150 @@
5.1,3.5,1.4,0.2,0
4.9,3.0,1.4,0.2,0
4.7,3.2,1.3,0.2,0
4.6,3.1,1.5,0.2,0
5.0,3.6,1.4,0.2,0
5.4,3.9,1.7,0.4,0
4.6,3.4,1.4,0.3,0
5.0,3.4,1.5,0.2,0
4.4,2.9,1.4,0.2,0
4.9,3.1,1.5,0.1,0
5.4,3.7,1.5,0.2,0
4.8,3.4,1.6,0.2,0
4.8,3.0,1.4,0.1,0
4.3,3.0,1.1,0.1,0
5.8,4.0,1.2,0.2,0
5.7,4.4,1.5,0.4,0
5.4,3.9,1.3,0.4,0
5.1,3.5,1.4,0.3,0
5.7,3.8,1.7,0.3,0
5.1,3.8,1.5,0.3,0
5.4,3.4,1.7,0.2,0
5.1,3.7,1.5,0.4,0
4.6,3.6,1.0,0.2,0
5.1,3.3,1.7,0.5,0
4.8,3.4,1.9,0.2,0
5.0,3.0,1.6,0.2,0
5.0,3.4,1.6,0.4,0
5.2,3.5,1.5,0.2,0
5.2,3.4,1.4,0.2,0
4.7,3.2,1.6,0.2,0
4.8,3.1,1.6,0.2,0
5.4,3.4,1.5,0.4,0
5.2,4.1,1.5,0.1,0
5.5,4.2,1.4,0.2,0
4.9,3.1,1.5,0.1,0
5.0,3.2,1.2,0.2,0
5.5,3.5,1.3,0.2,0
4.9,3.1,1.5,0.1,0
4.4,3.0,1.3,0.2,0
5.1,3.4,1.5,0.2,0
5.0,3.5,1.3,0.3,0
4.5,2.3,1.3,0.3,0
4.4,3.2,1.3,0.2,0
5.0,3.5,1.6,0.6,0
5.1,3.8,1.9,0.4,0
4.8,3.0,1.4,0.3,0
5.1,3.8,1.6,0.2,0
4.6,3.2,1.4,0.2,0
5.3,3.7,1.5,0.2,0
5.0,3.3,1.4,0.2,0
7.0,3.2,4.7,1.4,1
6.4,3.2,4.5,1.5,1
6.9,3.1,4.9,1.5,1
5.5,2.3,4.0,1.3,1
6.5,2.8,4.6,1.5,1
5.7,2.8,4.5,1.3,1
6.3,3.3,4.7,1.6,1
4.9,2.4,3.3,1.0,1
6.6,2.9,4.6,1.3,1
5.2,2.7,3.9,1.4,1
5.0,2.0,3.5,1.0,1
5.9,3.0,4.2,1.5,1
6.0,2.2,4.0,1.0,1
6.1,2.9,4.7,1.4,1
5.6,2.9,3.6,1.3,1
6.7,3.1,4.4,1.4,1
5.6,3.0,4.5,1.5,1
5.8,2.7,4.1,1.0,1
6.2,2.2,4.5,1.5,1
5.6,2.5,3.9,1.1,1
5.9,3.2,4.8,1.8,1
6.1,2.8,4.0,1.3,1
6.3,2.5,4.9,1.5,1
6.1,2.8,4.7,1.2,1
6.4,2.9,4.3,1.3,1
6.6,3.0,4.4,1.4,1
6.8,2.8,4.8,1.4,1
6.7,3.0,5.0,1.7,1
6.0,2.9,4.5,1.5,1
5.7,2.6,3.5,1.0,1
5.5,2.4,3.8,1.1,1
5.5,2.4,3.7,1.0,1
5.8,2.7,3.9,1.2,1
6.0,2.7,5.1,1.6,1
5.4,3.0,4.5,1.5,1
6.0,3.4,4.5,1.6,1
6.7,3.1,4.7,1.5,1
6.3,2.3,4.4,1.3,1
5.6,3.0,4.1,1.3,1
5.5,2.5,4.0,1.3,1
5.5,2.6,4.4,1.2,1
6.1,3.0,4.6,1.4,1
5.8,2.6,4.0,1.2,1
5.0,2.3,3.3,1.0,1
5.6,2.7,4.2,1.3,1
5.7,3.0,4.2,1.2,1
5.7,2.9,4.2,1.3,1
6.2,2.9,4.3,1.3,1
5.1,2.5,3.0,1.1,1
5.7,2.8,4.1,1.3,1
6.3,3.3,6.0,2.5,2
5.8,2.7,5.1,1.9,2
7.1,3.0,5.9,2.1,2
6.3,2.9,5.6,1.8,2
6.5,3.0,5.8,2.2,2
7.6,3.0,6.6,2.1,2
4.9,2.5,4.5,1.7,2
7.3,2.9,6.3,1.8,2
6.7,2.5,5.8,1.8,2
7.2,3.6,6.1,2.5,2
6.5,3.2,5.1,2.0,2
6.4,2.7,5.3,1.9,2
6.8,3.0,5.5,2.1,2
5.7,2.5,5.0,2.0,2
5.8,2.8,5.1,2.4,2
6.4,3.2,5.3,2.3,2
6.5,3.0,5.5,1.8,2
7.7,3.8,6.7,2.2,2
7.7,2.6,6.9,2.3,2
6.0,2.2,5.0,1.5,2
6.9,3.2,5.7,2.3,2
5.6,2.8,4.9,2.0,2
7.7,2.8,6.7,2.0,2
6.3,2.7,4.9,1.8,2
6.7,3.3,5.7,2.1,2
7.2,3.2,6.0,1.8,2
6.2,2.8,4.8,1.8,2
6.1,3.0,4.9,1.8,2
6.4,2.8,5.6,2.1,2
7.2,3.0,5.8,1.6,2
7.4,2.8,6.1,1.9,2
7.9,3.8,6.4,2.0,2
6.4,2.8,5.6,2.2,2
6.3,2.8,5.1,1.5,2
6.1,2.6,5.6,1.4,2
7.7,3.0,6.1,2.3,2
6.3,3.4,5.6,2.4,2
6.4,3.1,5.5,1.8,2
6.0,3.0,4.8,1.8,2
6.9,3.1,5.4,2.1,2
6.7,3.1,5.6,2.4,2
6.9,3.1,5.1,2.3,2
5.8,2.7,5.1,1.9,2
6.8,3.2,5.9,2.3,2
6.7,3.3,5.7,2.5,2
6.7,3.0,5.2,2.3,2
6.3,2.5,5.0,1.9,2
6.5,3.0,5.2,2.0,2
6.2,3.4,5.4,2.3,2
5.9,3.0,5.1,1.8,2

View File

@ -1,42 +0,0 @@
<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.beanvalidation</groupId>
<artifactId>beanvalidation</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>beanvalidation</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.2.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
</dependencies>
</project>

View File

@ -1,17 +0,0 @@
package com.baeldung.beanvalidation.application;
import javax.validation.Validation;
import javax.validation.Validator;
import com.baeldung.beanvalidation.model.User;
public class Application {
public static void main( String[] args ) {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
User user = new User();
user.setName("Mary");
user.setEmail("no-email");
user.setAge(36);
validator.validate(user).stream().forEach(violation -> System.out.println(violation.getMessage()));
}
}

View File

@ -1,13 +0,0 @@
package com.baeldung.beanvalidation.container;
import java.util.Optional;
import javax.validation.constraints.Positive;
public class IntegerContainer {
private Optional<@Positive(message = "Value must be a positive integer") Integer> container = Optional.empty();
public void addElement(int element) {
container = Optional.of(element);
}
}

View File

@ -1,14 +0,0 @@
package com.baeldung.beanvalidation.container;
import java.util.ArrayList;
import java.util.List;
import javax.validation.constraints.NotNull;
public class StringContainer {
private List<@NotNull String> container = new ArrayList<>();
public void addElement(String element) {
container.add(element);
}
}

View File

@ -1,48 +0,0 @@
package com.baeldung.beanvalidation.model;
import java.io.Serializable;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@NotNull(message = "Name cannot be null")
@Size(min = 2, max = 32, message = "Name must be between 2 and 32 characters")
private String name;
@Email(message = "Email must be a well-formed email address")
private String email;
@Min(value = 1, message = "Age must not be lesser than 1")
@Max(value = 99, message = "Age must not be greater than 99")
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

View File

@ -1,8 +0,0 @@
package com.baeldung.beanvalidation.service;
public interface EntityService {
public String toString();
public void processEntity();
}

View File

@ -1,45 +0,0 @@
package com.baeldung.beanvalidation.service;
import java.io.Serializable;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.baeldung.beanvalidation.model.User;
public class UserService implements EntityService, Serializable {
private static final long serialVersionUID = 1L;
@Valid
private User user;
@NotNull(message = "FileName cannot be null")
@Size(min = 5, max = 10, message = "FileName must be between 5 and 10 characters")
private String fileName;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
@Override
public void processEntity() {
// process the user here
}
@Override
public String toString() {
return "UserService [user=" + user + ", fileName=" + fileName + "]";
}
}

View File

@ -1,134 +0,0 @@
package com.baeldung.beanvalidation;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.beanvalidation.container.IntegerContainer;
import com.baeldung.beanvalidation.container.StringContainer;
import com.baeldung.beanvalidation.model.User;
import com.baeldung.beanvalidation.service.UserService;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.Assert.*;
public class ValidationTest {
private static Validator validator;
private static User user;
@BeforeClass
public static void setUpHibernateValidatorInstance() {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
@BeforeClass
public static void setUpUserInstance() {
user = new User();
}
@AfterClass
public static void tearDownHibernateValidatorInstance() {
validator = null;
}
@AfterClass
public static void tearDownUserInstance() {
user = null;
}
@Test
public void givenNullName_whenValidated_thenMessageDescriptorForName() {
user.setName(null);
user.setEmail("mary@domain.com");
user.setAge(36);
assertEquals("Name cannot be null", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
}
@Test
public void givenInvalidEmail_whenValidated_thenMessageDescriptorforEmail() {
user.setName("Mary");
user.setEmail("no-email");
user.setAge(36);
assertEquals("Email must be a well-formed email address", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
}
@Test
public void givenAgeLesserThanLowerBound_whenValidated_thenMessageDescriptorforAge() {
user.setName("Mary");
user.setEmail("mary@domain.com");
user.setAge(0);
assertEquals("Age must not be lesser than 1", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
}
@Test
public void givenAgeGreaterThanUpperBound_whenValidated_thenMessageDescriptorforAge() {
user.setName("Mary");
user.setEmail("mary@domain.com");
user.setAge(100);
assertEquals("Age must not be greater than 99", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
}
@Test
public void givenNullFileName_whenValidated_thenMessageDescriptorforFileName() {
user.setName("Mary");
user.setEmail("mary@domain.com");
user.setAge(36);
UserService userService = new UserService();
userService.setFileName(null);
userService.setUser(user);
assertEquals("FileName cannot be null", validator.validate(userService).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
}
@Test
public void givenFileNameShortherThanLowerBound_whenValidated_thenMessageDescriptorforFileName() {
user.setName("Mary");
user.setEmail("mary@domain.com");
user.setAge(36);
UserService userService = new UserService();
userService.setFileName("");
userService.setUser(user);
assertEquals("FileName must be between 5 and 10 characters", validator.validate(userService).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
}
@Test
public void givenFileNameLongerThanUpperBound_whenValidated_thenMessageDescriptorforFileName() {
user.setName("Mary");
user.setEmail("mary@domain.com");
user.setAge(36);
UserService userService = new UserService();
userService.setFileName("waytoolongfilename");
userService.setUser(user);
assertEquals("FileName must be between 5 and 10 characters", validator.validate(userService).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
}
@Test
public void givenNullUserAndNullFileName_whenValidated_thenTwoConstraintViolations() {
user.setName(null);
user.setEmail("mary@domain.com");
user.setAge(36);
UserService userService = new UserService();
userService.setFileName(null);
userService.setUser(user);
Set<ConstraintViolation<UserService>> constraintViolations = validator.validate(userService);
assertEquals(2, constraintViolations.size());
}
@Test
public void givenNullElement_whenValidated_thenOneConstraintViolation() {
StringContainer container = new StringContainer();
container.addElement(null);
Set<ConstraintViolation<StringContainer>> constraintViolations = validator.validate(container);
assertEquals(1, constraintViolations.size());
}
@Test
public void givenNegativeInteger_whenValidated_thenOneConstraintViolation() {
IntegerContainer container = new IntegerContainer();
container.addElement(-1);
Set<ConstraintViolation<IntegerContainer>> constraintViolations = validator.validate(container);
assertEquals(1, constraintViolations.size());
}
}

View File

@ -6,8 +6,8 @@
<version>0.1-SNAPSHOT</version>
<properties>
<validation-api.version>1.1.0.Final</validation-api.version>
<hibernate-validator.version>5.3.4.Final</hibernate-validator.version>
<validation-api.version>2.0.0.Final</validation-api.version>
<hibernate-validator.version>6.0.2.Final</hibernate-validator.version>
<javax.el-api.version>3.0.0</javax.el-api.version>
<javax.el.version>2.2.6</javax.el.version>
</properties>

View File

@ -0,0 +1,66 @@
package org.baeldung;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.PositiveOrZero;
public class Customer {
@NotBlank(message="Name cannot be empty")
private String name;
private List<@NotBlank(message="Address must not be blank") String> addresses;
private Integer age;
@PositiveOrZero
private OptionalInt numberOfOrders;
//@NotBlank
private Profile profile;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getAddresses() {
return addresses;
}
public void setAddresses(List<String> addresses) {
this.addresses = addresses;
}
public Optional<@Min(18) Integer> getAge() {
return Optional.ofNullable(age);
}
public void setAge(Integer age) {
this.age = age;
}
public OptionalInt getNumberOfOrders() {
return numberOfOrders;
}
public void setNumberOfOrders(OptionalInt numberOfOrders) {
this.numberOfOrders = numberOfOrders;
}
public Profile getProfile() {
return profile;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
}

View File

@ -0,0 +1,19 @@
package org.baeldung;
import java.util.Map;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
public class CustomerMap {
private Map<@Email(message="Must be a valid email") String, @NotNull Customer> customers;
public Map<String, Customer> getCustomers() {
return customers;
}
public void setCustomers(Map<String, Customer> customers) {
this.customers = customers;
}
}

View File

@ -0,0 +1,13 @@
package org.baeldung;
public class Profile {
private String companyName;
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
}

View File

@ -1,56 +1,94 @@
package org.baeldung;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Email;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import javax.validation.constraints.NotBlank;
public class User {
@NotNull(message = "Name cannot be null")
private String name;
@NotNull(message = "Name cannot be null")
private String name;
@AssertTrue
private boolean working;
@AssertTrue
private boolean working;
@Size(min = 10, max = 200, message = "Number of characters should be in between 10 and 200 inclusive")
private String aboutMe;
@Size(min = 10, max = 200, message = "Number of characters should be in between 10 and 200 inclusive")
private String aboutMe;
@Min(value = 18, message = "Age should not be less than 18")
@Max(value = 150, message = "Age should not be more than 150")
private int age;
@Min(value = 18, message = "Age should not be less than 18")
@Max(value = 150, message = "Age should not be more than 150")
private int age;
public int getAge() {
return age;
}
@Email(message = "Email should be valid")
private String email;
List<@NotBlank String> preferences;
private LocalDate dateOfBirth;
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public boolean isWorking() {
return working;
}
public void setAge(int age) {
this.age = age;
}
public void setWorking(boolean working) {
this.working = working;
}
public boolean isWorking() {
return working;
}
public String getAboutMe() {
return aboutMe;
}
public void setWorking(boolean working) {
this.working = working;
}
public void setAboutMe(String aboutMe) {
this.aboutMe = aboutMe;
}
public String getAboutMe() {
return aboutMe;
}
public String getName() {
return name;
}
public void setAboutMe(String aboutMe) {
this.aboutMe = aboutMe;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Optional<@Past LocalDate> getDateOfBirth() {
return Optional.ofNullable(dateOfBirth);
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<String> getPreferences() {
return preferences;
}
public void setPreferences(List<String> preferences) {
this.preferences = preferences;
}
}

View File

@ -0,0 +1,17 @@
package org.baeldung.valueextractors;
import javax.validation.valueextraction.ExtractedValue;
import javax.validation.valueextraction.UnwrapByDefault;
import javax.validation.valueextraction.ValueExtractor;
import org.baeldung.Profile;
@UnwrapByDefault
public class ProfileValueExtractor implements ValueExtractor<@ExtractedValue(type = String.class) Profile> {
@Override
public void extractValues(Profile originalValue, ValueExtractor.ValueReceiver receiver) {
receiver.value(null, originalValue.getCompanyName());
}
}

View File

@ -0,0 +1 @@
org.baeldung.valueextractors.ProfileValueExtractor

View File

@ -0,0 +1,88 @@
package org.baeldung;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import java.util.OptionalInt;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.baeldung.valueextractors.ProfileValueExtractor;
import org.junit.Before;
import org.junit.Test;
public class ContainerValidationIntegrationTest {
private Validator validator;
@Before
public void setup() {
ValidatorFactory factory = Validation.byDefaultProvider().configure()
.addValueExtractor(new ProfileValueExtractor()).buildValidatorFactory();
validator = factory.getValidator();
}
@Test
public void whenEmptyAddress_thenValidationFails() {
Customer customer = new Customer();
customer.setName("John");
customer.setAddresses(Collections.singletonList(" "));
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertEquals(1, violations.size());
assertEquals("Address must not be blank", violations.iterator()
.next()
.getMessage());
}
@Test
public void whenInvalidEmail_thenValidationFails() {
CustomerMap map = new CustomerMap();
map.setCustomers(Collections.singletonMap("john", new Customer()));
Set<ConstraintViolation<CustomerMap>> violations = validator.validate(map);
assertEquals(1, violations.size());
assertEquals("Must be a valid email", violations.iterator()
.next()
.getMessage());
}
@Test
public void whenAgeTooLow_thenValidationFails() {
Customer customer = new Customer();
customer.setName("John");
customer.setAge(15);
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertEquals(1, violations.size());
}
@Test
public void whenAgeNull_thenValidationSucceeds() {
Customer customer = new Customer();
customer.setName("John");
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertEquals(0, violations.size());
}
@Test
public void whenNumberOrdersValid_thenValidationSucceeds() {
Customer customer = new Customer();
customer.setName("John");
customer.setNumberOfOrders(OptionalInt.of(1));
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertEquals(0, violations.size());
}
//@Test
public void whenProfileCompanyNameBlank_thenValidationFails() {
Customer customer = new Customer();
customer.setName("John");
Profile profile = new Profile();
profile.setCompanyName(" ");
customer.setProfile(profile);
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertEquals(1, violations.size());
}
}

View File

@ -1,81 +1,126 @@
package org.baeldung;
import java.time.LocalDate;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.Optional;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.junit.Assert;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.Before;
public class ValidationIntegrationTest {
@Test
public void ifNameIsNull_nameValidationFails() {
User user = new User();
user.setWorking(true);
user.setAboutMe("Its all about me!!");
user.setAge(50);
private Validator validator;
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<User>> violations = validator.validate(user);
Assert.assertEquals(violations.isEmpty(), false);
}
@Before
public void setup() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void ifSizeNotInRange_aboutMeValidationFails() {
User user = new User();
user.setName("MyName");
user.setAboutMe("Its all about me!!");
user.setAge(50);
private User createUser() {
User user = new User();
user.setName("John");
user.setWorking(true);
user.setAge(18);
return user;
}
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<User>> violations = validator.validate(user);
Assert.assertEquals(violations.isEmpty(), false);
}
@Test
public void ifNameIsNull_nameValidationFails() {
User user = new User();
user.setWorking(true);
user.setAboutMe("Its all about me!!");
user.setAge(50);
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertEquals(violations.isEmpty(), false);
}
@Test
public void ifWorkingIsFalse_workingValidationFails() {
User user = new User();
user.setName("MyName");
user.setAboutMe("Its all about me!!");
user.setAge(50);
@Test
public void ifSizeNotInRange_aboutMeValidationFails() {
User user = new User();
user.setName("MyName");
user.setAboutMe("Its all about me!!");
user.setAge(50);
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<User>> violations = validator.validate(user);
Assert.assertEquals(violations.isEmpty(), false);
}
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertEquals(violations.isEmpty(), false);
}
@Test
public void ifAgeNotRange_ageValidationFails() {
User user = new User();
user.setName("MyName");
user.setAboutMe("Its all about me!!");
user.setAge(8);
@Test
public void ifWorkingIsFalse_workingValidationFails() {
User user = new User();
user.setName("MyName");
user.setAboutMe("Its all about me!!");
user.setAge(50);
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<User>> violations = validator.validate(user);
Assert.assertEquals(violations.isEmpty(), false);
}
@Test
public void ifFnameNullAgeNotRangeAndWorkingIsFalse_validationFailsWithThreeErrors() {
User user = new User();
user.setAboutMe("Its all about me!!");
user.setAge(300);
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertEquals(violations.isEmpty(), false);
}
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<User>> violations = validator.validate(user);
Assert.assertEquals(violations.isEmpty(), false);
Assert.assertEquals(violations.size(), 3);
}
@Test
public void ifAgeNotRange_ageValidationFails() {
User user = new User();
user.setName("MyName");
user.setAboutMe("Its all about me!!");
user.setAge(8);
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertEquals(violations.isEmpty(), false);
}
@Test
public void ifFnameNullAgeNotRangeAndWorkingIsFalse_validationFailsWithThreeErrors() {
User user = new User();
user.setAboutMe("Its all about me!!");
user.setAge(300);
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertEquals(violations.isEmpty(), false);
assertEquals(violations.size(), 3);
}
@Test
public void givenInvalidEmail_thenValidationFails() {
User user = createUser();
user.setEmail("john");
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertEquals(1, violations.size());
}
@Test
public void givenBlankPreference_thenValidationFails() {
User user = createUser();
user.setPreferences(Collections.singletonList(" "));
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertEquals(1, violations.size());
}
@Test
public void givenEmptyOptional_thenValidationSucceeds() {
User user = createUser();
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertEquals(0, violations.size());
}
@Test
public void givenPastDateOfBirth_thenValidationSuccess() {
User user = createUser();
user.setDateOfBirth(LocalDate.of(1980, 5, 20));
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertEquals(0, violations.size());
}
}

View File

@ -36,6 +36,11 @@
<artifactId>reladomo-test-util</artifactId>
<version>${reladomo.version}</version>
</dependency>
<dependency>
<groupId>com.j256.ormlite</groupId>
<artifactId>ormlite-jdbc</artifactId>
<version>${ormlite.version}</version>
</dependency>
</dependencies>
<build>
@ -144,5 +149,6 @@
<reladomo.version>16.5.1</reladomo.version>
<junit.version>4.12</junit.version>
<maven-compiler-plugin.version>3.6.2</maven-compiler-plugin.version>
<ormlite.version>5.0</ormlite.version>
</properties>
</project>

View File

@ -0,0 +1,37 @@
package com.baeldung.ormlite;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "addresses")
public class Address {
@DatabaseField(generatedId = true)
private long addressId;
@DatabaseField(canBeNull = false)
private String addressLine;
public Address() {
}
public Address(String addressLine) {
this.addressLine = addressLine;
}
public long getAddressId() {
return addressId;
}
public void setAddressId(long addressId) {
this.addressId = addressId;
}
public String getAddressLine() {
return addressLine;
}
public void setAddressLine(String addressLine) {
this.addressLine = addressLine;
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.ormlite;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable
public class Book {
@DatabaseField(generatedId = true)
private long bookId;
@DatabaseField
private String title;
@DatabaseField(foreign = true, foreignAutoRefresh = true, foreignAutoCreate = true)
private Library library;
public Book() {
}
public Book(String title) {
this.title = title;
}
public long getBookId() {
return bookId;
}
public void setBookId(long bookId) {
this.bookId = bookId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Library getLibrary() {
return library;
}
public void setLibrary(Library library) {
this.library = library;
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.ormlite;
import com.j256.ormlite.dao.ForeignCollection;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "libraries", daoClass = LibraryDaoImpl.class)
public class Library {
@DatabaseField(generatedId = true)
private long libraryId;
@DatabaseField(canBeNull = false)
private String name;
@DatabaseField(foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true)
private Address address;
@ForeignCollectionField(eager = false)
private ForeignCollection<Book> books;
public Library() {
}
public long getLibraryId() {
return libraryId;
}
public void setLibraryId(long libraryId) {
this.libraryId = libraryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public ForeignCollection<Book> getBooks() {
return books;
}
public void setBooks(ForeignCollection<Book> books) {
this.books = books;
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.ormlite;
import java.sql.SQLException;
import java.util.List;
import com.j256.ormlite.dao.Dao;
public interface LibraryDao extends Dao<Library, Long> {
public List<Library> findByName(String name) throws SQLException;
}

View File

@ -0,0 +1,21 @@
package com.baeldung.ormlite;
import java.sql.SQLException;
import java.util.List;
import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.support.ConnectionSource;
public class LibraryDaoImpl extends BaseDaoImpl<Library, Long> implements LibraryDao {
public LibraryDaoImpl(ConnectionSource connectionSource) throws SQLException {
super(connectionSource, Library.class);
}
@Override
public List<Library> findByName(String name) throws SQLException {
return super.queryForEq("name", name);
}
}

View File

@ -0,0 +1,171 @@
package com.baeldung.ormlite;
import static org.junit.Assert.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.j256.ormlite.dao.CloseableWrappedIterable;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.jdbc.JdbcPooledConnectionSource;
import com.j256.ormlite.table.TableUtils;
public class ORMLiteTest {
private static JdbcPooledConnectionSource connectionSource;
private static Dao<Library, Long> libraryDao;
private static Dao<Book, Long> bookDao;
@BeforeClass
public static void setup() throws SQLException {
connectionSource = new JdbcPooledConnectionSource("jdbc:h2:mem:myDb");
TableUtils.createTableIfNotExists(connectionSource, Library.class);
TableUtils.createTableIfNotExists(connectionSource, Address.class);
TableUtils.createTableIfNotExists(connectionSource, Book.class);
libraryDao = DaoManager.createDao(connectionSource, Library.class);
bookDao = DaoManager.createDao(connectionSource, Book.class);
}
@Test
public void givenDAO_whenCRUD_thenOk() throws SQLException {
Library library = new Library();
library.setName("My Library");
libraryDao.create(library);
Library result = libraryDao.queryForId(library.getLibraryId());
assertEquals("My Library", result.getName());
library.setName("My Other Library");
libraryDao.update(library);
libraryDao.delete(library);
}
@Test
public void whenLoopDao_thenOk() throws SQLException {
Library library1 = new Library();
library1.setName("My Library");
libraryDao.create(library1);
Library library2 = new Library();
library2.setName("My Other Library");
libraryDao.create(library2);
libraryDao.forEach(lib -> {
System.out.println(lib.getName());
});
}
@Test
public void givenIterator_whenLoop_thenOk() throws SQLException, IOException {
Library library1 = new Library();
library1.setName("My Library");
libraryDao.create(library1);
Library library2 = new Library();
library2.setName("My Other Library");
libraryDao.create(library2);
CloseableWrappedIterable<Library> wrappedIterable = libraryDao.getWrappedIterable();
try {
wrappedIterable.forEach(lib -> {
System.out.println(lib.getName());
});
} finally {
wrappedIterable.close();
}
}
@Test
public void givenCustomDao_whenSave_thenOk() throws SQLException, IOException {
Library library = new Library();
library.setName("My Library");
LibraryDao customLibraryDao = DaoManager.createDao(connectionSource, Library.class);
customLibraryDao.create(library);
assertEquals(1, customLibraryDao.findByName("My Library")
.size());
}
@Test
public void whenSaveForeignField_thenOk() throws SQLException, IOException {
Library library = new Library();
library.setName("My Library");
library.setAddress(new Address("Main Street nr 20"));
libraryDao.create(library);
Dao<Address, Long> addressDao = DaoManager.createDao(connectionSource, Address.class);
assertEquals(1, addressDao.queryForEq("addressLine", "Main Street nr 20")
.size());
}
@Test
public void whenSaveForeignCollection_thenOk() throws SQLException, IOException {
Library library = new Library();
library.setName("My Library");
libraryDao.create(library);
libraryDao.refresh(library);
library.getBooks()
.add(new Book("1984"));
Book book = new Book("It");
book.setLibrary(library);
bookDao.create(book);
assertEquals(2, bookDao.queryForEq("library_id", library)
.size());
}
@Test
public void whenGetLibrariesWithMoreThanOneBook_thenOk() throws SQLException, IOException {
Library library = new Library();
library.setName("My Library");
libraryDao.create(library);
Library library2 = new Library();
library2.setName("My Other Library");
libraryDao.create(library2);
libraryDao.refresh(library);
libraryDao.refresh(library2);
library.getBooks()
.add(new Book("Book1"));
library2.getBooks()
.add(new Book("Book2"));
library2.getBooks()
.add(new Book("Book3"));
List<Library> libraries = libraryDao.queryBuilder()
.where()
.in("libraryId", bookDao.queryBuilder()
.selectColumns("library_id")
.groupBy("library_id")
.having("count(*) > 1"))
.query();
assertEquals(1, libraries.size());
}
@After
public void clear() throws SQLException {
TableUtils.clearTable(connectionSource, Library.class);
TableUtils.clearTable(connectionSource, Book.class);
TableUtils.clearTable(connectionSource, Address.class);
}
@AfterClass
public static void tearDown() throws SQLException, IOException {
connectionSource.close();
}
}

View File

@ -41,6 +41,7 @@
- [Introduction to NoException](http://www.baeldung.com/no-exception)
- [Introduction to FunctionalJava](http://www.baeldung.com/functional-java)
- [Apache Commons IO](http://www.baeldung.com/apache-commons-io)
- [Introduction to Conflict-Free Replicated Data Types](http://www.baeldung.com/java-conflict-free-replicated-data-types)
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.

View File

@ -1,6 +1,6 @@
<?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">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
@ -487,7 +487,7 @@
<artifactId>vavr</artifactId>
<version>${vavr.version}</version>
</dependency>
<!-- Retrofit -->
<dependency>
<groupId>com.squareup.retrofit2</groupId>
@ -503,7 +503,7 @@
<groupId>com.squareup.retrofit2</groupId>
<artifactId>adapter-rxjava</artifactId>
<version>${retrofit.version}</version>
</dependency>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>logging-interceptor</artifactId>
@ -583,8 +583,34 @@
<dependency>
<groupId>com.atlassian.fugue</groupId>
<artifactId>fugue</artifactId>
<version>3.0.0-m007</version>
<version>2.6.1</version>
</dependency>
<!-- Uncomment this in order to use the jira-rest-java-client-core API -->
<!-- <dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency> -->
<dependency>
<groupId>org.jgrapht</groupId>
<artifactId>jgrapht-core</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>com.netopyr.wurmloch</groupId>
<artifactId>wurmloch-crdt</artifactId>
<version>${crdt.version}</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j</artifactId>
<version>3.3.5</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
</dependencies>
<repositories>
<repository>
@ -606,6 +632,7 @@
</repository>
</repositories>
<properties>
<crdt.version>0.1.0</crdt.version>
<multiverse.version>0.7.0</multiverse.version>
<cglib.version>3.2.4</cglib.version>
<commons-lang.version>3.6</commons-lang.version>
@ -658,6 +685,6 @@
<protonpack.version>1.14</protonpack.version>
<unit-ri.version>1.0.3</unit-ri.version>
<cache.version>1.0.0</cache.version>
<hazelcast.version>3.8.4</hazelcast.version>
<hazelcast.version>3.8.4</hazelcast.version>
</properties>
</project>
</project>

View File

@ -3,6 +3,8 @@ package com.baeldung.commons.lang3;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.concurrent.ConcurrentException;
import org.apache.commons.lang3.concurrent.BackgroundInitializer;
public class BuilderMethods {
@ -56,5 +58,36 @@ public class BuilderMethods {
System.out.println(simple1.getName());
System.out.println(simple1.hashCode());
System.out.println(simple1.toString());
SampleLazyInitializer sampleLazyInitializer = new SampleLazyInitializer();
try {
sampleLazyInitializer.get();
} catch (ConcurrentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
SampleBackgroundInitializer sampleBackgroundInitializer = new SampleBackgroundInitializer();
sampleBackgroundInitializer.start();
// Proceed with other tasks instead of waiting for the SampleBackgroundInitializer task to finish.
try {
Object result = sampleBackgroundInitializer.get();
} catch (ConcurrentException e) {
e.printStackTrace();
}
}
}
class SampleBackgroundInitializer extends BackgroundInitializer<String>{
@Override
protected String initialize() throws Exception {
return null;
}
// Any complex task that takes some time
}

View File

@ -0,0 +1,109 @@
package com.baeldung.docx;
import org.docx4j.dml.wordprocessingDrawing.Inline;
import org.docx4j.jaxb.Context;
import org.docx4j.model.table.TblFactory;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.BooleanDefaultTrue;
import org.docx4j.wml.Color;
import org.docx4j.wml.Drawing;
import org.docx4j.wml.ObjectFactory;
import org.docx4j.wml.P;
import org.docx4j.wml.R;
import org.docx4j.wml.RPr;
import org.docx4j.wml.Tbl;
import org.docx4j.wml.Tc;
import org.docx4j.wml.Text;
import org.docx4j.wml.Tr;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.nio.file.Files;
import java.util.List;
class Docx4jExample {
void createDocumentPackage(String outputPath, String imagePath) throws Exception {
WordprocessingMLPackage wordPackage = WordprocessingMLPackage.createPackage();
MainDocumentPart mainDocumentPart = wordPackage.getMainDocumentPart();
mainDocumentPart.addStyledParagraphOfText("Title", "Hello World!");
mainDocumentPart.addParagraphOfText("Welcome To Baeldung!");
ObjectFactory factory = Context.getWmlObjectFactory();
P p = factory.createP();
R r = factory.createR();
Text t = factory.createText();
t.setValue("Welcome To Baeldung");
r.getContent().add(t);
p.getContent().add(r);
RPr rpr = factory.createRPr();
BooleanDefaultTrue b = new BooleanDefaultTrue();
rpr.setB(b);
rpr.setI(b);
rpr.setCaps(b);
Color red = factory.createColor();
red.setVal("green");
rpr.setColor(red);
r.setRPr(rpr);
mainDocumentPart.getContent().add(p);
File image = new File(imagePath);
byte[] fileContent = Files.readAllBytes(image.toPath());
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage
.createImagePart(wordPackage, fileContent);
Inline inline = imagePart.createImageInline(
"Baeldung Image", "Alt Text", 1, 2, false);
P Imageparagraph = addImageToParagraph(inline);
mainDocumentPart.getContent().add(Imageparagraph);
int writableWidthTwips = wordPackage.getDocumentModel()
.getSections().get(0).getPageDimensions()
.getWritableWidthTwips();
int columnNumber = 3;
Tbl tbl = TblFactory.createTable(3, 3, writableWidthTwips / columnNumber);
List<Object> rows = tbl.getContent();
for (Object row : rows) {
Tr tr = (Tr) row;
List<Object> cells = tr.getContent();
for (Object cell : cells) {
Tc td = (Tc) cell;
td.getContent().add(p);
}
}
mainDocumentPart.getContent().add(tbl);
File exportFile = new File(outputPath);
wordPackage.save(exportFile);
}
boolean isTextExist(String testText) throws Docx4JException, JAXBException {
File doc = new File("helloWorld.docx");
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(doc);
MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart();
String textNodesXPath = "//w:t";
List<Object> paragraphs = mainDocumentPart.getJAXBNodesViaXPath(textNodesXPath, true);
for (Object obj : paragraphs) {
Text text = (Text) ((JAXBElement) obj).getValue();
String textValue = text.getValue();
if (textValue != null && textValue.contains(testText)) {
return true;
}
}
return false;
}
private static P addImageToParagraph(Inline inline) {
ObjectFactory factory = new ObjectFactory();
P p = factory.createP();
R r = factory.createR();
p.getContent().add(r);
Drawing drawing = factory.createDrawing();
r.getContent().add(drawing);
drawing.getAnchorOrInline().add(inline);
return p;
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.jdo.xml;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jdo.annotations.Element;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.PrimaryKey;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
@PersistenceCapable(
schema="/myproduct/people",
table="person"
)
public class AnnotadedPerson {
@XmlAttribute
private long personNum;
@PrimaryKey
private String firstName;
private String lastName;
@XmlElementWrapper(name="phone-numbers")
@XmlElement(name="phone-number")
@Element(types=String.class)
private List phoneNumbers = new ArrayList();
public AnnotadedPerson(long personNum, String firstName, String lastName) {
super();
this.personNum = personNum;
this.firstName = firstName;
this.lastName = lastName;
}
public long getPersonNum() {
return personNum;
}
public void setPersonNum(long personNum) {
this.personNum = personNum;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
}

View File

@ -0,0 +1,105 @@
package com.baeldung.jdo.xml;
import java.util.List;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;
import org.datanucleus.api.jdo.JDOPersistenceManagerFactory;
import org.datanucleus.metadata.PersistenceUnitMetaData;
public class MyApp {
private static PersistenceUnitMetaData pumd;
private static PersistenceManagerFactory pmf;
private static PersistenceManager pm;
public static void main( String[] args ) {
//persist product object using dynamic persistence unit
defineDynamicPersistentUnit();
Product product = new Product("id1","Sony Discman", "A standard discman from Sony", 49.99);
persistObject(product);
closePersistenceManager();
//persist AnnotatedPerson object using named pmf
defineNamedPersistenceManagerFactory("XmlDatastore");
AnnotadedPerson annotatedPerson = new AnnotadedPerson(654320,"annotated","person");
annotatedPerson.getPhoneNumbers().add("999999999");
annotatedPerson.getPhoneNumbers().add("000000000");
persistObject(annotatedPerson);
queryAnnotatedPersonsInXML();
closePersistenceManager();
//persist Person object using PMF created by properties file
definePersistenceManagerFactoryUsingPropertiesFile("META-INF\\datanucleus.properties");
Person person = new Person(654321,"bealdung","author");
person.getPhoneNumbers().add("123456789");
person.getPhoneNumbers().add("987654321");
persistObject(person);
queryPersonsInXML();
closePersistenceManager();
}
public static void defineDynamicPersistentUnit(){
PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
pumd.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myfile_dynamicPMF.xml");
pumd.addProperty("datanucleus.schema.autoCreateAll", "true");
pumd.addProperty("datanucleus.xml.indentSize", "4");
pmf = new JDOPersistenceManagerFactory(pumd, null);
pm = pmf.getPersistenceManager();
}
public static void defineNamedPersistenceManagerFactory(String pmfName){
pmf = JDOHelper.getPersistenceManagerFactory("XmlDatastore");
pm = pmf.getPersistenceManager();
}
public static void definePersistenceManagerFactoryUsingPropertiesFile(String filePath){
pmf = JDOHelper.getPersistenceManagerFactory(filePath);
pm = pmf.getPersistenceManager();
}
public static void closePersistenceManager(){
if(pm!=null && !pm.isClosed()){
pm.close();
}
}
public static void persistObject(Object obj){
Transaction tx = pm.currentTransaction();
try {
tx.begin();
pm.makePersistent(obj);
tx.commit();
} finally {
if (tx.isActive()) {
tx.rollback();
}
}
}
public static void queryPersonsInXML(){
Query<Person> query = pm.newQuery(Person.class);
List<Person> result = query.executeList();
System.out.println("name: "+result.get(0).getFirstName());
}
public static void queryAnnotatedPersonsInXML(){
Query<AnnotadedPerson> query = pm.newQuery(AnnotadedPerson.class);
List<AnnotadedPerson> result = query.executeList();
System.out.println("name: "+result.get(0).getFirstName());
}
}

View File

@ -0,0 +1,65 @@
package com.baeldung.jdo.xml;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jdo.annotations.Element;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.PrimaryKey;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
@PersistenceCapable
public class Person {
private long personNum;
@PrimaryKey
private String firstName;
private String lastName;
private List phoneNumbers = new ArrayList();
public Person(long personNum, String firstName, String lastName) {
super();
this.personNum = personNum;
this.firstName = firstName;
this.lastName = lastName;
}
public long getPersonNum() {
return personNum;
}
public void setPersonNum(long personNum) {
this.personNum = personNum;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.jdo.xml;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceAware;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
@PersistenceCapable
public class Product {
@PrimaryKey
String id;
String name;
String description;
double price;
public Product(){
}
public Product(String id,String name,String description,double price){
this.id = id;
this.name=name;
this.description = description;
this.price = price;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}

View File

@ -1,57 +0,0 @@
package com.baeldung.jira;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.JiraRestClientFactory;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class JiraClient {
private static final String USERNAME = "jira.user";
private static final String PASSWORD = "secret";
private static final String JIRA_URL = "http://jira.company.com";
public static void main(String[] args) {
final Issue issue = new JiraClient().getIssue("MYKEY-1234");
System.out.println(issue.getDescription());
}
private Issue getIssue(String issueKey) {
JiraRestClient restClient = getJiraRestClient();
Issue issue = restClient.getIssueClient().getIssue(issueKey).claim();
closeRestClient(restClient);
return issue;
}
private JiraRestClient getJiraRestClient() {
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
URI jiraServerUri = getJiraUri();
return factory
.createWithBasicHttpAuthentication(jiraServerUri, USERNAME, PASSWORD);
}
private URI getJiraUri() {
URI jiraServerUri = null;
try {
jiraServerUri = new URI(JIRA_URL);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return jiraServerUri;
}
private void closeRestClient(JiraRestClient restClient) {
try {
restClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,103 @@
package com.baeldung.jira;
import com.atlassian.jira.rest.client.api.IssueRestClient;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.domain.BasicVotes;
import com.atlassian.jira.rest.client.api.domain.Comment;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.api.domain.input.IssueInput;
import com.atlassian.jira.rest.client.api.domain.input.IssueInputBuilder;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
public class MyJiraClient {
private String username;
private String password;
private String jiraUrl;
private JiraRestClient restClient;
private MyJiraClient(String username, String password, String jiraUrl) {
this.username = username;
this.password = password;
this.jiraUrl = jiraUrl;
this.restClient = getJiraRestClient();
}
public static void main(String[] args) throws IOException {
MyJiraClient myJiraClient = new MyJiraClient("user.name", "pass", "http://jira.company.com");
final String issueKey = myJiraClient.createIssue("ABCD", 1L, "Issue created from JRJC");
myJiraClient.updateIssueDescription(issueKey, "This is description from my Jira Client");
Issue issue = myJiraClient.getIssue(issueKey);
System.out.println(issue.getDescription());
myJiraClient.voteForAnIssue(issue);
System.out.println(myJiraClient.getTotalVotesCount(issueKey));
myJiraClient.addComment(issue, "This is comment from my Jira Client");
List<Comment> comments = myJiraClient.getAllComments(issueKey);
comments.forEach(c -> System.out.println(c.getBody()));
myJiraClient.deleteIssue(issueKey, true);
myJiraClient.restClient.close();
}
private String createIssue(String projectKey, Long issueType, String issueSummary) {
IssueRestClient issueClient = restClient.getIssueClient();
IssueInput newIssue = new IssueInputBuilder(projectKey, issueType, issueSummary).build();
return issueClient.createIssue(newIssue).claim().getKey();
}
private Issue getIssue(String issueKey) {
return restClient.getIssueClient().getIssue(issueKey).claim();
}
private void voteForAnIssue(Issue issue) {
restClient.getIssueClient().vote(issue.getVotesUri()).claim();
}
private int getTotalVotesCount(String issueKey) {
BasicVotes votes = getIssue(issueKey).getVotes();
return votes == null ? 0 : votes.getVotes();
}
private void addComment(Issue issue, String commentBody) {
restClient.getIssueClient().addComment(issue.getCommentsUri(), Comment.valueOf(commentBody));
}
private List<Comment> getAllComments(String issueKey) {
return StreamSupport.stream(getIssue(issueKey).getComments().spliterator(), false)
.collect(Collectors.toList());
}
private void updateIssueDescription(String issueKey, String newDescription) {
IssueInput input = new IssueInputBuilder().setDescription(newDescription).build();
restClient.getIssueClient().updateIssue(issueKey, input).claim();
}
private void deleteIssue(String issueKey, boolean deleteSubtasks) {
restClient.getIssueClient().deleteIssue(issueKey, deleteSubtasks).claim();
}
private JiraRestClient getJiraRestClient() {
return new AsynchronousJiraRestClientFactory()
.createWithBasicHttpAuthentication(getJiraUri(), this.username, this.password);
}
private URI getJiraUri() {
return URI.create(this.jiraUrl);
}
}

View File

@ -0,0 +1,4 @@
javax.jdo.PersistenceManagerFactoryClass=org.datanucleus.api.jdo.JDOPersistenceManagerFactory
javax.jdo.option.ConnectionURL= xml:file:myfile-ds.xml
datanucleus.xml.indentSize=6
datanucleus.schema.autoCreateAll=true

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<jdoconfig xmlns="http://xmlns.jcp.org/xml/ns/jdo/jdoconfig"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/jdo/jdoconfig
http://xmlns.jcp.org/xml/ns/jdo/jdoconfig_3_2.xsd"
version="3.2">
<!-- Datastore Txn PMF -->
<persistence-manager-factory name="XmlDatastore">
<property name="javax.jdo.PersistenceManagerFactoryClass"
value="org.datanucleus.api.jdo.JDOPersistenceManagerFactory" />
<property name="javax.jdo.option.ConnectionURL" value="xml:file:namedPMF-ds.xml" />
<property name="datanucleus.xml.indentSize" value="6" />
<property name="datanucleus.schema.autoCreateAll"
value="true" />
</persistence-manager-factory>
</jdoconfig>

View File

@ -0,0 +1,21 @@
<jdo xmlns="http://xmlns.jcp.org/xml/ns/jdo/jdo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/jdo/jdo http://xmlns.jcp.org/xml/ns/jdo/jdo_3_1.xsd"
version="3.1">
<package name="com.baeldung.jdo.xml">
<class name="Person" detachable="true" schema="/myproduct/people"
table="person">
<field name="personNum">
<extension vendor-name="datanucleus" key="XmlAttribute"
value="true" />
</field>
<field name="firstName" primary-key="true" /> <!-- PK since JAXB requires String -->
<field name="lastName" />
<field name="phoneNumbers">
<collection element-type="java.lang.String" />
<element column="phoneNumber" />
</field>
</class>
</package>
</jdo>

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

View File

@ -1,85 +1,111 @@
package com.baeldung.commons.collections4;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.Bag;
import org.apache.commons.collections4.bag.CollectionBag;
import org.apache.commons.collections4.bag.HashBag;
import org.apache.commons.collections4.bag.TreeBag;
import org.junit.Assert;
import org.junit.Before;
import org.apache.commons.collections4.SortedBag;
import org.apache.commons.collections4.bag.*;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
public class BagTests {
Bag<String> baseBag;
TreeBag<String> treeBag;
@Before
public void before() {
baseBag = new HashBag<String>();
treeBag = new TreeBag<String>();
treeBag = new TreeBag<String>();
}
@Test
public void whenAdd_thenRemoveFromBaseBag_thenContainsCorrect() {
baseBag.add("apple", 2);
baseBag.add("lemon", 6);
baseBag.add("lime");
baseBag.remove("lemon");
Assert.assertEquals(3, baseBag.size());
Assert.assertFalse(baseBag.contains("lemon"));
Assert.assertTrue(baseBag.uniqueSet().contains("apple"));
List<String> containList = new ArrayList<String>();
containList.add("apple");
containList.add("lemon");
containList.add("lime");
Assert.assertFalse(baseBag.containsAll(containList));
}
@Test
public void whenAdd_thenRemoveFromBaseCollectionBag_thenContainsCorrect() {
baseBag.add("apple", 2);
baseBag.add("lemon", 6);
baseBag.add("lime");
CollectionBag<String> baseCollectionBag = new CollectionBag<String>(
baseBag);
baseCollectionBag.remove("lemon");
Assert.assertEquals(8, baseCollectionBag.size());
Assert.assertTrue(baseCollectionBag.contains("lemon"));
baseCollectionBag.remove("lemon",1);
Assert.assertEquals(7, baseCollectionBag.size());
Assert.assertTrue(baseBag.uniqueSet().contains("apple"));
List<String> containList = new ArrayList<String>();
containList.add("apple");
containList.add("lemon");
containList.add("lime");
Assert.assertTrue(baseBag.containsAll(containList));
}
@Test
public void whenAddtoTreeBag_thenRemove_thenContainsCorrect() {
treeBag.add("banana", 8);
treeBag.add("apple", 2);
treeBag.add("lime");
Assert.assertEquals(11, treeBag.size());
Assert.assertEquals("apple", treeBag.first());
Assert.assertEquals("lime", treeBag.last());
treeBag.remove("apple");
Assert.assertEquals(9, treeBag.size());
Assert.assertEquals("banana", treeBag.first());
}
@Test
public void givenMultipleCopies_whenAdded_theCountIsKept() {
Bag<Integer> bag = new HashBag<>(
Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
assertThat(bag.getCount(1), equalTo(2));
}
@Test
public void givenBag_whenBagAddAPILikeCollectionAPI_thenFalse() {
Collection<Integer> collection = new ArrayList<>();
// Collection contract defines that add() should return true
assertThat(collection.add(9), is(true));
// Even when element is already in the collection
collection.add(1);
assertThat(collection.add(1), is(true));
Bag<Integer> bag = new HashBag<>();
// Bag returns true on adding a new element
assertThat(bag.add(9), is(true));
bag.add(1);
// But breaks the contract with false when it has to increment the count
assertThat(bag.add(1), is(not(true)));
}
@Test
public void givenDecoratedBag_whenBagAddAPILikeCollectionAPI_thenTrue() {
Bag<Integer> bag = CollectionBag.collectionBag(new HashBag<>());
bag.add(1);
// This time the behavior is compliant to the Java Collection
assertThat(bag.add(1), is((true)));
}
@Test
public void givenAdd_whenCountOfElementsDefined_thenCountAreAdded() {
Bag<Integer> bag = new HashBag<>();
// Adding 1 for 5 times
bag.add(1, 5);
assertThat(bag.getCount(1), equalTo(5));
}
@Test
public void givenMultipleCopies_whenRemove_allAreRemoved() {
Bag<Integer> bag = new HashBag<>(
Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
// From 3 we delete 1, 2 remain
bag.remove(3, 1);
assertThat(bag.getCount(3), equalTo(2));
// From 2 we delete all
bag.remove(1);
assertThat(bag.getCount(1), equalTo(0));
}
@Test
public void givenTree_whenDuplicateElementsAdded_thenSort() {
TreeBag<Integer> bag = new TreeBag<>(
Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 }));
assertThat(bag.first(), equalTo(1));
assertThat(bag.getCount(bag.first()), equalTo(2));
assertThat(bag.last(), equalTo(7));
assertThat(bag.getCount(bag.last()), equalTo(3));
}
@Test
public void givenDecoratedTree_whenTreeAddAPILikeCollectionAPI_thenTrue() {
SortedBag<Integer> bag = CollectionSortedBag
.collectionSortedBag(new TreeBag<>());
bag.add(1);
assertThat(bag.add(1), is((true)));
}
@Test
public void givenSortedBag_whenDuplicateElementsAdded_thenSort() {
SynchronizedSortedBag<Integer> bag = SynchronizedSortedBag
.synchronizedSortedBag(new TreeBag<>(
Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 })));
assertThat(bag.first(), equalTo(1));
assertThat(bag.getCount(bag.first()), equalTo(2));
assertThat(bag.last(), equalTo(7));
assertThat(bag.getCount(bag.last()), equalTo(3));
}
}

View File

@ -3,7 +3,9 @@ package com.baeldung.commons.lang3;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@ -20,6 +22,7 @@ import org.apache.commons.lang3.ArchUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.lang3.arch.Processor;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.apache.commons.lang3.concurrent.ConcurrentException;
import org.apache.commons.lang3.concurrent.ConcurrentRuntimeException;
import org.apache.commons.lang3.concurrent.ConcurrentUtils;
@ -133,4 +136,14 @@ public class Lang3UtilsTest {
assertEquals(sampleObjectOne, sampleObjectTwo);
}
@Test
public void testBuildDefaults() {
BasicThreadFactory.Builder builder = new BasicThreadFactory.Builder();
BasicThreadFactory factory = builder.build();
assertNull("No naming pattern set Yet", factory.getNamingPattern());
BasicThreadFactory factory2 = builder.namingPattern("sampleNamingPattern").daemon(true).priority(Thread.MIN_PRIORITY).build();
assertNotNull("Got a naming pattern", factory2.getNamingPattern());
assertEquals("sampleNamingPattern", factory2.getNamingPattern());
}
}

View File

@ -0,0 +1,153 @@
package com.baeldung.crdt;
import com.netopyr.wurmloch.crdt.GCounter;
import com.netopyr.wurmloch.crdt.GSet;
import com.netopyr.wurmloch.crdt.LWWRegister;
import com.netopyr.wurmloch.crdt.PNCounter;
import com.netopyr.wurmloch.store.LocalCrdtStore;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class CRDTTest {
@Test
public void givenGrowOnlySet_whenTwoReplicasDiverge_thenShouldMergeItWithoutAConflict() {
//given
final LocalCrdtStore crdtStore1 = new LocalCrdtStore();
final LocalCrdtStore crdtStore2 = new LocalCrdtStore();
crdtStore1.connect(crdtStore2);
final GSet<String> replica1 = crdtStore1.createGSet("ID_1");
final GSet<String> replica2 = crdtStore2.<String>findGSet("ID_1").get();
//when
replica1.add("apple");
replica2.add("banana");
//then
assertThat(replica1).contains("apple", "banana");
assertThat(replica2).contains("apple", "banana");
//when
crdtStore1.disconnect(crdtStore2);
replica1.add("strawberry");
replica2.add("pear");
assertThat(replica1).contains("apple", "banana", "strawberry");
assertThat(replica2).contains("apple", "banana", "pear");
crdtStore1.connect(crdtStore2);
//then
assertThat(replica1).contains("apple", "banana", "strawberry", "pear");
assertThat(replica2).contains("apple", "banana", "strawberry", "pear");
}
@Test
public void givenIncrementOnlyCounter_whenTwoReplicasDiverge_thenShouldMergeIt() {
//given
final LocalCrdtStore crdtStore1 = new LocalCrdtStore();
final LocalCrdtStore crdtStore2 = new LocalCrdtStore();
crdtStore1.connect(crdtStore2);
final GCounter replica1 = crdtStore1.createGCounter("ID_1");
final GCounter replica2 = crdtStore2.findGCounter("ID_1").get();
//when
replica1.increment();
replica2.increment(2L);
//then
assertThat(replica1.get()).isEqualTo(3L);
assertThat(replica2.get()).isEqualTo(3L);
//when
crdtStore1.disconnect(crdtStore2);
replica1.increment(3L);
replica2.increment(5L);
assertThat(replica1.get()).isEqualTo(6L);
assertThat(replica2.get()).isEqualTo(8L);
crdtStore1.connect(crdtStore2);
// then
assertThat(replica1.get()).isEqualTo(11L);
assertThat(replica2.get()).isEqualTo(11L);
}
@Test
public void givenPNCounter_whenReplicasDiverge_thenShouldMergeWithoutAConflict() {
// given
final LocalCrdtStore crdtStore1 = new LocalCrdtStore();
final LocalCrdtStore crdtStore2 = new LocalCrdtStore();
crdtStore1.connect(crdtStore2);
final PNCounter replica1 = crdtStore1.createPNCounter("ID_1");
final PNCounter replica2 = crdtStore2.findPNCounter("ID_1").get();
//when
replica1.increment();
replica2.decrement(2L);
//then
assertThat(replica1.get()).isEqualTo(-1L);
assertThat(replica2.get()).isEqualTo(-1L);
//when
crdtStore1.disconnect(crdtStore2);
replica1.decrement(3L);
replica2.increment(5L);
assertThat(replica1.get()).isEqualTo(-4L);
assertThat(replica2.get()).isEqualTo(4L);
crdtStore1.connect(crdtStore2);
//then
assertThat(replica1.get()).isEqualTo(1L);
assertThat(replica2.get()).isEqualTo(1L);
}
@Test
public void givenLastWriteWinsStrategy_whenReplicasDiverge_thenAfterMergeShouldKeepOnlyLastValue() {
//given
final LocalCrdtStore crdtStore1 = new LocalCrdtStore("N_1");
final LocalCrdtStore crdtStore2 = new LocalCrdtStore("N_2");
crdtStore1.connect(crdtStore2);
final LWWRegister<String> replica1 = crdtStore1.createLWWRegister("ID_1");
final LWWRegister<String> replica2 = crdtStore2.<String>findLWWRegister("ID_1").get();
//when
replica1.set("apple");
replica2.set("banana");
// then
assertThat(replica1.get()).isEqualTo("banana");
assertThat(replica2.get()).isEqualTo("banana");
// when
crdtStore1.disconnect(crdtStore2);
replica1.set("strawberry");
replica2.set("pear");
assertThat(replica1.get()).isEqualTo("strawberry");
assertThat(replica2.get()).isEqualTo("pear");
crdtStore1.connect(crdtStore2);
//then
assertThat(replica1.get()).isEqualTo("pear");
assertThat(replica2.get()).isEqualTo("pear");
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.docx;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class Docx4jReadAndWriteTest {
private static final String imagePath = "src/main/resources/image.jpg";
private static final String outputPath = "helloWorld.docx";
@Test
public void givenWordPackage_whenTextExist_thenReturnTrue() throws Exception {
Docx4jExample docx4j = new Docx4jExample();
docx4j.createDocumentPackage(outputPath, imagePath);
assertTrue(docx4j.isTextExist("Hello World!"));
assertTrue(!docx4j.isTextExist("InexistantText"));
}
}

View File

@ -7,7 +7,9 @@ import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
@ -15,17 +17,16 @@ import java.nio.charset.StandardCharsets;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
public class JettyIntegrationTest {
private JettyServer jettyServer;
private static JettyServer jettyServer;
@Before
public void setup() throws Exception {
@BeforeClass
public static void setup() throws Exception {
jettyServer = new JettyServer();
jettyServer.start();
}
@After
public void cleanup() throws Exception {
Thread.sleep(2000);
@AfterClass
public static void cleanup() throws Exception {
jettyServer.stop();
}

View File

@ -10,3 +10,4 @@
- [Mockito @Mock, @Spy, @Captor and @InjectMocks](http://www.baeldung.com/mockito-annotations)
- [Mockitos Mock Methods](http://www.baeldung.com/mockito-mock-methods)
- [Introduction to PowerMock](http://www.baeldung.com/intro-to-powermock)
- [Mocking Exception Throwing using Mockito](http://www.baeldung.com/mockito-exceptions)

View File

@ -0,0 +1,57 @@
package org.baeldung.mockito;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.mockito.Mockito;
public class MockitoExceptionIntegrationTest {
@Test(expected = NullPointerException.class)
public void whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class);
dictMock.getMeaning("word");
}
@Test(expected = IllegalStateException.class)
public void whenConfigVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
doThrow(IllegalStateException.class).when(dictMock)
.add(anyString(), anyString());
dictMock.add("word", "meaning");
}
@Test(expected = NullPointerException.class)
public void whenConfigNonVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred"));
dictMock.getMeaning("word");
}
@Test(expected = IllegalStateException.class)
public void whenConfigVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
doThrow(new IllegalStateException("Error occurred")).when(dictMock)
.add(anyString(), anyString());
dictMock.add("word", "meaning");
}
// =====
@Test(expected = NullPointerException.class)
public void givenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dict = new MyDictionary();
MyDictionary spy = Mockito.spy(dict);
when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class);
spy.getMeaning("word");
}
}

View File

@ -28,6 +28,7 @@
</properties>
<modules>
<module>atomix</module>
<module>apache-cayenne</module>
<module>aws</module>
<module>akka-streams</module>
@ -247,6 +248,7 @@
<module>mockserver</module>
<module>undertow</module>
<module>vertx-and-rxjava</module>
<module>deeplearning4j</module>
</modules>
<dependencies>

View File

@ -3,7 +3,6 @@
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>rxjava</artifactId>
<version>1.0-SNAPSHOT</version>

View File

@ -8,7 +8,7 @@ import static junit.framework.Assert.assertTrue;
public class ObservableTest {
String result = "";
private String result = "";
@Test
public void givenString_whenJustAndSubscribe_thenEmitsSingleItem() {
@ -85,7 +85,7 @@ public class ObservableTest {
.groupBy(i -> 0 == (i % 2) ? "EVEN" : "ODD")
.subscribe(group ->
group.subscribe((number) -> {
if (group.getKey().toString().equals("EVEN")) {
if (group.getKey().equals("EVEN")) {
EVEN[0] += number;
} else {
ODD[0] += number;
@ -141,5 +141,4 @@ public class ObservableTest {
assertTrue(sum[0] == 10);
}
}

View File

@ -12,16 +12,12 @@ public class ResourceManagementTest {
String[] result = {""};
Observable<Character> values = Observable.using(
() -> {
return "MyResource";
},
r -> {
return Observable.create(o -> {
for (Character c : r.toCharArray())
o.onNext(c);
o.onCompleted();
});
},
() -> "MyResource",
r -> Observable.create(o -> {
for (Character c : r.toCharArray())
o.onNext(c);
o.onCompleted();
}),
r -> System.out.println("Disposed: " + r)
);

View File

@ -27,7 +27,6 @@ public class RxJavaBackpressureLongRunningUnitTest {
// then
testSubscriber.awaitTerminalEvent();
assertTrue(testSubscriber.getOnErrorEvents().size() == 0);
}
@Test
@ -60,7 +59,6 @@ public class RxJavaBackpressureLongRunningUnitTest {
// then
testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS);
assertTrue(testSubscriber.getOnErrorEvents().size() == 0);
}
@Test
@ -77,7 +75,6 @@ public class RxJavaBackpressureLongRunningUnitTest {
// then
testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS);
assertTrue(testSubscriber.getOnErrorEvents().size() == 0);
}
@Test
@ -88,15 +85,14 @@ public class RxJavaBackpressureLongRunningUnitTest {
// when
source.sample(100, TimeUnit.MILLISECONDS)
// .throttleFirst(100, TimeUnit.MILLISECONDS)
.observeOn(Schedulers.computation()).subscribe(testSubscriber);
// .throttleFirst(100, TimeUnit.MILLISECONDS)
.observeOn(Schedulers.computation()).subscribe(testSubscriber);
IntStream.range(0, 1_000).forEach(source::onNext);
// then
testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS);
assertTrue(testSubscriber.getOnErrorEvents().size() == 0);
}
@Test
@ -111,7 +107,6 @@ public class RxJavaBackpressureLongRunningUnitTest {
// then
testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS);
assertTrue(testSubscriber.getOnErrorEvents().size() == 0);
}
@Test
@ -120,11 +115,11 @@ public class RxJavaBackpressureLongRunningUnitTest {
TestSubscriber<Integer> testSubscriber = new TestSubscriber<>();
// when
Observable.range(1, 1_000_000).onBackpressureDrop().observeOn(Schedulers.computation()).subscribe(testSubscriber);
Observable.range(1, 1_000_000).onBackpressureDrop().observeOn(Schedulers.computation())
.subscribe(testSubscriber);
// then
testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS);
assertTrue(testSubscriber.getOnErrorEvents().size() == 0);
}
}

View File

@ -1,5 +1,15 @@
package com.baeldung.rxjava;
import org.junit.Test;
import rx.Observable;
import rx.Observable.Operator;
import rx.Observable.Transformer;
import rx.Subscriber;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.baelding.rxjava.operator.ToCleanString.toCleanString;
import static com.baelding.rxjava.operator.ToLength.toLength;
import static org.hamcrest.Matchers.hasItems;
@ -7,20 +17,6 @@ import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import rx.Observable;
import rx.Observable.Operator;
import rx.Observable.Transformer;
import rx.Subscriber;
import com.baelding.rxjava.operator.ToCleanString;
import com.baelding.rxjava.operator.ToLength;
public class RxJavaCustomOperatorUnitTest {
@Test
@ -29,7 +25,7 @@ public class RxJavaCustomOperatorUnitTest {
final List<String> results = new ArrayList<>();
final Observable<String> observable = Observable.from(list)
.lift(toCleanString());
.lift(toCleanString());
// when
observable.subscribe(results::add);
@ -46,7 +42,7 @@ public class RxJavaCustomOperatorUnitTest {
final List<Integer> results = new ArrayList<>();
final Observable<Integer> observable = Observable.from(list)
.compose(toLength());
.compose(toLength());
// when
observable.subscribe(results::add);
@ -85,8 +81,8 @@ public class RxJavaCustomOperatorUnitTest {
final List<String> results = new ArrayList<>();
Observable.from(Arrays.asList("ap_p-l@e", "or-an?ge"))
.lift(cleanStringFn)
.subscribe(results::add);
.lift(cleanStringFn)
.subscribe(results::add);
assertThat(results, notNullValue());
assertThat(results, hasSize(2));
@ -99,8 +95,8 @@ public class RxJavaCustomOperatorUnitTest {
final List<Integer> results = new ArrayList<>();
Observable.from(Arrays.asList("apple", "orange"))
.compose(toLengthFn)
.subscribe(results::add);
.compose(toLengthFn)
.subscribe(results::add);
assertThat(results, notNullValue());
assertThat(results, hasSize(2));

View File

@ -10,7 +10,9 @@ import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
public class RxJavaUnitTest {
@ -19,7 +21,8 @@ public class RxJavaUnitTest {
// given
List<String> letters = Arrays.asList("A", "B", "C", "D", "E");
List<String> results = new ArrayList<>();
Observable<String> observable = Observable.from(letters).zipWith(Observable.range(1, Integer.MAX_VALUE), (string, index) -> index + "-" + string);
Observable<String> observable = Observable.from(letters)
.zipWith(Observable.range(1, Integer.MAX_VALUE), (string, index) -> index + "-" + string);
// when
observable.subscribe(results::add);
@ -36,7 +39,8 @@ public class RxJavaUnitTest {
List<String> letters = Arrays.asList("A", "B", "C", "D", "E");
TestSubscriber<String> subscriber = new TestSubscriber<>();
Observable<String> observable = Observable.from(letters).zipWith(Observable.range(1, Integer.MAX_VALUE), ((string, index) -> index + "-" + string));
Observable<String> observable = Observable.from(letters)
.zipWith(Observable.range(1, Integer.MAX_VALUE), ((string, index) -> index + "-" + string));
// when
observable.subscribe(subscriber);
@ -54,7 +58,9 @@ public class RxJavaUnitTest {
List<String> letters = Arrays.asList("A", "B", "C", "D", "E");
TestSubscriber<String> subscriber = new TestSubscriber<>();
Observable<String> observable = Observable.from(letters).zipWith(Observable.range(1, Integer.MAX_VALUE), ((string, index) -> index + "-" + string)).concatWith(Observable.error(new RuntimeException("error in Observable")));
Observable<String> observable = Observable.from(letters)
.zipWith(Observable.range(1, Integer.MAX_VALUE), ((string, index) -> index + "-" + string))
.concatWith(Observable.error(new RuntimeException("error in Observable")));
// when
observable.subscribe(subscriber);

View File

@ -1,9 +1,6 @@
package com.baeldung.rxjava;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import rx.Observable;
@ -18,14 +15,16 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
import static java.util.concurrent.Executors.newFixedThreadPool;
import static org.hamcrest.Matchers.hasItems;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class SchedulersTest {
String result = "";
String result1 = "";
String result2 = "";
private String result = "";
private String result1 = "";
private String result2 = "";
@Test
public void givenScheduledWorker_whenScheduleAnAction_thenResultAction() throws InterruptedException {
@ -33,7 +32,8 @@ public class SchedulersTest {
Scheduler scheduler = Schedulers.immediate();
Scheduler.Worker worker = scheduler.createWorker();
worker.schedule(() -> result += "action");
Assert.assertTrue(result.equals("action"));
assertTrue(result.equals("action"));
}
@Test
@ -46,8 +46,9 @@ public class SchedulersTest {
worker.unsubscribe();
});
worker.schedule(() -> result += "Second_Action");
Thread.sleep(500);
Assert.assertTrue(result.equals("First_Action"));
await()
.until(() -> assertTrue(result.equals("First_Action")));
}
@Ignore //it's not safe, not every time is running correctly
@ -61,8 +62,9 @@ public class SchedulersTest {
worker.schedule(() -> result += "_worker_");
result += "_End";
});
Thread.sleep(2000);
Assert.assertTrue(result.equals("RxNewThreadScheduler-1_Start_End_worker_"));
await()
.until(() -> assertTrue(result.equals("RxNewThreadScheduler-1_Start_End_worker_")));
}
@Test
@ -77,9 +79,11 @@ public class SchedulersTest {
.subscribe(s ->
result1 += Thread.currentThread().getName()
);
Thread.sleep(500);
Assert.assertTrue(result1.equals("RxNewThreadScheduler-1"));
Assert.assertTrue(result2.equals("RxNewThreadScheduler-2"));
await()
.until(() -> {
assertTrue(result1.equals("RxNewThreadScheduler-1"));
assertTrue(result2.equals("RxNewThreadScheduler-2"));
});
}
@Test
@ -92,8 +96,9 @@ public class SchedulersTest {
worker.schedule(() -> result += "_worker_");
result += "_End";
});
Thread.sleep(500);
Assert.assertTrue(result.equals("main_Start_worker__End"));
await()
.until(() -> assertTrue(result.equals("main_Start_worker__End")));
}
@Test
@ -104,10 +109,10 @@ public class SchedulersTest {
.subscribe(s ->
result += Thread.currentThread().getName()
);
Thread.sleep(500);
Assert.assertTrue(result.equals("main"));
}
await()
.until(() -> assertTrue(result.equals("main")));
}
@Test
public void givenObservable_whenTrampolineScheduled_thenExecuteOnMainThread() throws InterruptedException {
@ -118,8 +123,9 @@ public class SchedulersTest {
Observable.just(1, 3, 5, 7, 9)
.subscribeOn(Schedulers.trampoline())
.subscribe(i -> result += "" + i);
Thread.sleep(500);
Assert.assertTrue(result.equals("246813579"));
await()
.until(() -> assertTrue(result.equals("246813579")));
}
@Test
@ -138,9 +144,9 @@ public class SchedulersTest {
});
result += "_mainEnd";
});
Thread.sleep(500);
Assert.assertTrue(result
.equals("mainStart_mainEnd_middleStart_middleEnd_worker_"));
await()
.until(() -> assertTrue(result.equals("mainStart_mainEnd_middleStart_middleEnd_worker_")));
}
private ThreadFactory threadFactory(String pattern) {
@ -161,7 +167,7 @@ public class SchedulersTest {
subscriber.onNext("Alfa");
subscriber.onNext("Beta");
subscriber.onCompleted();
});;
});
observable
.subscribeOn(schedulerA)
@ -171,8 +177,9 @@ public class SchedulersTest {
Throwable::printStackTrace,
() -> result += "_Completed"
);
Thread.sleep(2000);
Assert.assertTrue(result.equals("Sched-A-0Alfa_Sched-A-0Beta__Completed"));
await()
.until(() -> assertTrue(result.equals("Sched-A-0Alfa_Sched-A-0Beta__Completed")));
}
@Test
@ -181,8 +188,9 @@ public class SchedulersTest {
Observable.just("io")
.subscribeOn(Schedulers.io())
.subscribe(i -> result += Thread.currentThread().getName());
Thread.sleep(500);
Assert.assertTrue(result.equals("RxIoScheduler-2"));
await()
.until(() -> assertTrue(result.equals("RxIoScheduler-2")));
}
@Test
@ -191,8 +199,9 @@ public class SchedulersTest {
Observable.just("computation")
.subscribeOn(Schedulers.computation())
.subscribe(i -> result += Thread.currentThread().getName());
Thread.sleep(500);
Assert.assertTrue(result.equals("RxComputationScheduler-1"));
await()
.until(() -> assertTrue(result.equals("RxComputationScheduler-1")));
}
@Test
@ -203,10 +212,10 @@ public class SchedulersTest {
Observable<Long> tick = Observable.interval(1, TimeUnit.SECONDS, scheduler);
Observable.from(letters)
.zipWith(tick, (string, index) -> index + "-" + string)
.subscribeOn(scheduler)
.subscribe(subscriber);
Observable.from(letters)
.zipWith(tick, (string, index) -> index + "-" + string)
.subscribeOn(scheduler)
.subscribe(subscriber);
subscriber.assertNoValues();
subscriber.assertNotCompleted();
@ -229,10 +238,9 @@ public class SchedulersTest {
Scheduler schedulerA = Schedulers.from(poolA);
Observable.just('A', 'B')
.delay(1, TimeUnit.SECONDS, schedulerA)
.subscribe(i -> result+= Thread.currentThread().getName() + i + " ");
.subscribe(i -> result += Thread.currentThread().getName() + i + " ");
Thread.sleep(2000);
Assert.assertTrue(result.equals("Sched1-A Sched1-B "));
await()
.until(() -> assertTrue(result.equals("Sched1-A Sched1-B ")));
}
}

View File

@ -20,5 +20,4 @@ public class SingleTest {
single.subscribe();
assertTrue(result[0].equals("Hello"));
}
}

View File

@ -9,7 +9,7 @@ import static junit.framework.Assert.assertTrue;
public class SubjectTest {
@Test
public void givenSubjectAndTwoSubscribers_whenSubscribeOnSubject_thenSubscriberBeginsToAdd(){
public void givenSubjectAndTwoSubscribers_whenSubscribeOnSubject_thenSubscriberBeginsToAdd() {
PublishSubject<Integer> subject = PublishSubject.create();
subject.subscribe(SubjectImpl.getFirstObserver());

View File

@ -7,16 +7,18 @@ import rx.Observable;
import rx.Observer;
import rx.exceptions.OnErrorNotImplementedException;
import rx.schedulers.Schedulers;
import rx.schedulers.Timestamped;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
import static org.junit.Assert.assertTrue;
public class UtilityOperatorsTest {
int emittedTotal = 0;
int receivedTotal = 0;
String result = "";
private int emittedTotal = 0;
private int receivedTotal = 0;
private String result = "";
@Rule
public ExpectedException thrown = ExpectedException.none();
@ -39,12 +41,13 @@ public class UtilityOperatorsTest {
+ Thread.currentThread().getName());
});
Thread.sleep(2000);
assertTrue(emittedTotal == 1500);
assertTrue(receivedTotal == 15000);
await().until(() -> {
assertTrue(emittedTotal == 1500);
assertTrue(receivedTotal == 15000);
}
);
}
@Test
public void givenObservable_whenObserveOnBeforeOnNext_thenEmitsEventsOnComputeScheduler() throws InterruptedException {
@ -63,12 +66,12 @@ public class UtilityOperatorsTest {
+ Thread.currentThread().getName());
});
Thread.sleep(2000);
assertTrue(emittedTotal == 1500);
assertTrue(receivedTotal == 15000);
await().until(() -> {
assertTrue(emittedTotal == 1500);
assertTrue(receivedTotal == 15000);
});
}
@Test
public void givenObservable_whenSubscribeOn_thenEmitsEventsOnComputeScheduler() throws InterruptedException {
@ -87,12 +90,12 @@ public class UtilityOperatorsTest {
+ Thread.currentThread().getName());
});
Thread.sleep(2000);
assertTrue(emittedTotal == 1500);
assertTrue(receivedTotal == 15000);
await().until(() -> {
assertTrue(emittedTotal == 1500);
assertTrue(receivedTotal == 15000);
});
}
@Test
public void givenObservableWithOneEvent_whenSingle_thenEmitEvent() {
@ -197,15 +200,13 @@ public class UtilityOperatorsTest {
@Test
public void givenObservables_whenDelay_thenEventsStartAppearAfterATime() throws InterruptedException {
Observable source
= Observable.interval(1, TimeUnit.SECONDS)
Observable<Timestamped<Long>> source = Observable.interval(1, TimeUnit.SECONDS)
.take(5)
.timestamp();
Observable delay
= source.delaySubscription(2, TimeUnit.SECONDS);
Observable<Timestamped<Long>> delay = source.delaySubscription(2, TimeUnit.SECONDS);
source.subscribe(
source.<Long>subscribe(
value -> System.out.println("source :" + value),
t -> System.out.println("source error"),
() -> System.out.println("source completed"));
@ -214,7 +215,7 @@ public class UtilityOperatorsTest {
value -> System.out.println("delay : " + value),
t -> System.out.println("delay error"),
() -> System.out.println("delay completed"));
Thread.sleep(8000);
//Thread.sleep(8000);
}
@Test
@ -231,14 +232,12 @@ public class UtilityOperatorsTest {
Observable<Character> values = Observable.using(
() -> "resource",
r -> {
return Observable.create(o -> {
for (Character c : r.toCharArray()) {
o.onNext(c);
}
o.onCompleted();
});
},
r -> Observable.create(o -> {
for (Character c : r.toCharArray()) {
o.onNext(c);
}
o.onCompleted();
}),
r -> System.out.println("Disposed: " + r)
);
values.subscribe(
@ -248,7 +247,6 @@ public class UtilityOperatorsTest {
assertTrue(result.equals("resource"));
}
@Test
public void givenObservableCached_whenSubscribesWith2Actions_thenEmitsCachedValues() {
@ -269,5 +267,4 @@ public class UtilityOperatorsTest {
});
assertTrue(receivedTotal == 8);
}
}

View File

@ -13,13 +13,13 @@ import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class AutomapClassTest {
public class AutomapClassIntegrationTest {
ConnectionProvider connectionProvider = Connector.connectionProvider;
Database db = Database.from(connectionProvider);
private ConnectionProvider connectionProvider = Connector.connectionProvider;
private Database db = Database.from(connectionProvider);
Observable<Integer> create = null;
Observable<Integer> insert1, insert2 = null;
private Observable<Integer> create = null;
private Observable<Integer> insert1, insert2 = null;
@Before
public void setup() {

View File

@ -13,13 +13,13 @@ import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class AutomapInterfaceTest {
public class AutomapInterfaceIntegrationTest {
ConnectionProvider connectionProvider = Connector.connectionProvider;
Database db = Database.from(connectionProvider);
private ConnectionProvider connectionProvider = Connector.connectionProvider;
private Database db = Database.from(connectionProvider);
Observable<Integer> create = null;
Observable<Integer> insert1, insert2 = null;
private Observable<Integer> create = null;
private Observable<Integer> insert1, insert2 = null;
@Before
public void setup() {
@ -57,8 +57,7 @@ public class AutomapInterfaceTest {
@After
public void close() {
db.update("DROP TABLE EMPLOYEE")
.dependsOn(create);
.dependsOn(create);
connectionProvider.close();
}
}

View File

@ -13,12 +13,12 @@ import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class BasicQueryTypesTest {
public class BasicQueryTypesIntegrationTest {
ConnectionProvider connectionProvider = Connector.connectionProvider;
Database db = Database.from(connectionProvider);
private ConnectionProvider connectionProvider = Connector.connectionProvider;
private Database db = Database.from(connectionProvider);
Observable<Integer> create, insert1, insert2, insert3, update, delete = null;
private Observable<Integer> create, insert1, insert2, insert3, update, delete = null;
@Test
public void whenCreateTableAndInsertRecords_thenCorrect() {

View File

@ -16,15 +16,15 @@ import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class InsertBlobTest {
public class InsertBlobIntegrationTest {
ConnectionProvider connectionProvider = Connector.connectionProvider;
Database db = Database.from(connectionProvider);
private ConnectionProvider connectionProvider = Connector.connectionProvider;
private Database db = Database.from(connectionProvider);
String expectedDocument = null;
String actualDocument = null;
private String expectedDocument = null;
private String actualDocument = null;
Observable<Integer> create, insert = null;
private Observable<Integer> create, insert = null;
@Before
public void setup() throws IOException {
@ -62,4 +62,4 @@ public class InsertBlobTest {
.dependsOn(create);
connectionProvider.close();
}
}
}

View File

@ -15,15 +15,15 @@ import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class InsertClobTest {
public class InsertClobIntegrationTest {
ConnectionProvider connectionProvider = Connector.connectionProvider;
Database db = Database.from(connectionProvider);
private ConnectionProvider connectionProvider = Connector.connectionProvider;
private Database db = Database.from(connectionProvider);
String expectedDocument = null;
String actualDocument = null;
private String expectedDocument = null;
private String actualDocument = null;
Observable<Integer> create, insert = null;
private Observable<Integer> create, insert = null;
@Before
public void setup() throws IOException {

View File

@ -11,13 +11,13 @@ import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class ReturnKeysTest {
public class ReturnKeysIntegrationTest {
Observable<Boolean> begin, commit = null;
Observable<Integer> createStatement, insertStatement, updateStatement = null;
private Observable<Boolean> begin = null;
private Observable<Integer> createStatement = null;
ConnectionProvider connectionProvider = Connector.connectionProvider;
Database db = Database.from(connectionProvider);
private ConnectionProvider connectionProvider = Connector.connectionProvider;
private Database db = Database.from(connectionProvider);
@Before
public void setup() {

View File

@ -10,13 +10,12 @@ import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class TransactionTest {
public class TransactionIntegrationTest {
Observable<Boolean> begin, commit = null;
Observable<Integer> createStatement, insertStatement, updateStatement = null;
private Observable<Integer> createStatement = null;
ConnectionProvider connectionProvider = Connector.connectionProvider;
Database db = Database.from(connectionProvider);
private ConnectionProvider connectionProvider = Connector.connectionProvider;
private Database db = Database.from(connectionProvider);
@Test
public void whenCommitTransaction_thenRecordUpdated() {

View File

@ -9,9 +9,6 @@ import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.Assert.assertTrue;
/**
* @author aiet
*/
public class ExceptionHandlingTest {
private Error UNKNOWN_ERROR = new Error("unknown error");
@ -19,10 +16,10 @@ public class ExceptionHandlingTest {
@Test
public void givenSubscriberAndError_whenHandleOnErrorReturn_thenResumed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
Observable
.error(UNKNOWN_ERROR)
.<String>error(UNKNOWN_ERROR)
.onErrorReturn(Throwable::getMessage)
.subscribe(testObserver);
@ -34,10 +31,10 @@ public class ExceptionHandlingTest {
@Test
public void givenSubscriberAndError_whenHandleOnErrorResume_thenResumed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
Observable
.error(UNKNOWN_ERROR)
.<String>error(UNKNOWN_ERROR)
.onErrorResumeNext(Observable.just("one", "two"))
.subscribe(testObserver);
@ -49,10 +46,10 @@ public class ExceptionHandlingTest {
@Test
public void givenSubscriberAndError_whenHandleOnErrorResumeItem_thenResumed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
Observable
.error(UNKNOWN_ERROR)
.<String>error(UNKNOWN_ERROR)
.onErrorReturnItem("singleValue")
.subscribe(testObserver);
@ -64,10 +61,10 @@ public class ExceptionHandlingTest {
@Test
public void givenSubscriberAndError_whenHandleOnErrorResumeFunc_thenResumed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
Observable
.error(UNKNOWN_ERROR)
.<String>error(UNKNOWN_ERROR)
.onErrorResumeNext(throwable -> {
return Observable.just(throwable.getMessage(), "nextValue");
})
@ -81,11 +78,11 @@ public class ExceptionHandlingTest {
@Test
public void givenSubscriberAndError_whenChangeStateOnError_thenErrorThrown() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
final AtomicBoolean state = new AtomicBoolean(false);
Observable
.error(UNKNOWN_ERROR)
.<String>error(UNKNOWN_ERROR)
.doOnError(throwable -> state.set(true))
.subscribe(testObserver);
@ -97,10 +94,10 @@ public class ExceptionHandlingTest {
@Test
public void givenSubscriberAndError_whenExceptionOccurOnError_thenCompositeExceptionThrown() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
Observable
.error(UNKNOWN_ERROR)
.<String>error(UNKNOWN_ERROR)
.doOnError(throwable -> {
throw new RuntimeException("unexcepted");
})
@ -113,10 +110,10 @@ public class ExceptionHandlingTest {
@Test
public void givenSubscriberAndException_whenHandleOnException_thenResumed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
Observable
.error(UNKNOWN_EXCEPTION)
.<String>error(UNKNOWN_EXCEPTION)
.onExceptionResumeNext(Observable.just("exceptionResumed"))
.subscribe(testObserver);
@ -128,14 +125,14 @@ public class ExceptionHandlingTest {
@Test
public void givenSubscriberAndError_whenHandleOnException_thenNotResumed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
Observable
.error(UNKNOWN_ERROR)
.<String>error(UNKNOWN_ERROR)
.onExceptionResumeNext(Observable.just("exceptionResumed"))
.subscribe(testObserver);
testObserver.assertError(UNKNOWN_ERROR);
testObserver.assertNotComplete();
}
}

View File

@ -9,20 +9,17 @@ import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertTrue;
/**
* @author aiet
*/
public class OnErrorRetryTest {
private Error UNKNOWN_ERROR = new Error("unknown error");
@Test
public void givenSubscriberAndError_whenRetryOnError_thenRetryConfirmed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
AtomicInteger atomicCounter = new AtomicInteger(0);
Observable
.error(() -> {
.<String>error(() -> {
atomicCounter.incrementAndGet();
return UNKNOWN_ERROR;
})
@ -37,12 +34,12 @@ public class OnErrorRetryTest {
@Test
public void givenSubscriberAndError_whenRetryConditionallyOnError_thenRetryConfirmed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
AtomicInteger atomicCounter = new AtomicInteger(0);
Observable
.error(() -> {
.<String>error(() -> {
atomicCounter.incrementAndGet();
return UNKNOWN_ERROR;
})
@ -57,11 +54,11 @@ public class OnErrorRetryTest {
@Test
public void givenSubscriberAndError_whenRetryUntilOnError_thenRetryConfirmed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
AtomicInteger atomicCounter = new AtomicInteger(0);
Observable
.error(UNKNOWN_ERROR)
.<String>error(UNKNOWN_ERROR)
.retryUntil(() -> atomicCounter.incrementAndGet() > 3)
.subscribe(testObserver);
@ -73,12 +70,12 @@ public class OnErrorRetryTest {
@Test
public void givenSubscriberAndError_whenRetryWhenOnError_thenRetryConfirmed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
Exception noretryException = new Exception("don't retry");
Observable
.error(UNKNOWN_ERROR)
.retryWhen(throwableObservable -> Observable.error(noretryException))
.<String>error(UNKNOWN_ERROR)
.retryWhen(throwableObservable -> Observable.<String>error(noretryException))
.subscribe(testObserver);
testObserver.assertError(noretryException);
@ -88,11 +85,11 @@ public class OnErrorRetryTest {
@Test
public void givenSubscriberAndError_whenRetryWhenOnError_thenCompleted() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
AtomicInteger atomicCounter = new AtomicInteger(0);
Observable
.error(() -> {
.<String>error(() -> {
atomicCounter.incrementAndGet();
return UNKNOWN_ERROR;
})
@ -107,11 +104,11 @@ public class OnErrorRetryTest {
@Test
public void givenSubscriberAndError_whenRetryWhenOnError_thenResubscribed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
AtomicInteger atomicCounter = new AtomicInteger(0);
Observable
.error(() -> {
.<String>error(() -> {
atomicCounter.incrementAndGet();
return UNKNOWN_ERROR;
})
@ -126,11 +123,11 @@ public class OnErrorRetryTest {
@Test
public void givenSubscriberAndError_whenRetryWhenForMultipleTimesOnError_thenResumed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
long before = System.currentTimeMillis();
Observable
.error(UNKNOWN_ERROR)
.<String>error(UNKNOWN_ERROR)
.retryWhen(throwableObservable -> throwableObservable
.zipWith(Observable.range(1, 3), (throwable, integer) -> integer)
.flatMap(integer -> {

View File

@ -14,7 +14,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.M1</version>
<version>2.0.0.M3</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
@ -165,14 +165,6 @@
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
@ -183,14 +175,6 @@
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>

View File

@ -14,7 +14,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.M1</version>
<version>2.0.0.M3</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
@ -143,14 +143,6 @@
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
@ -161,14 +153,6 @@
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
@ -183,10 +167,10 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<junit.platform.version>1.0.0-M4</junit.platform.version>
<junit.jupiter.version>5.0.0-M4</junit.jupiter.version>
<junit.platform.version>1.0.0</junit.platform.version>
<junit.jupiter.version>5.0.0</junit.jupiter.version>
<maven-surefire-plugin.version>2.20</maven-surefire-plugin.version>
<spring.version>5.0.0.RC2</spring.version>
<spring.version>5.0.0.RELEASE</spring.version>
<reactor-spring.version>1.0.1.RELEASE</reactor-spring.version>
<johnzon.version>1.1.3</johnzon.version>
<jsonb-api.version>1.0</jsonb-api.version>

View File

@ -33,7 +33,7 @@ public class ExploreSpring5URLPatternUsingRouterFunctions {
WebServer start() throws Exception {
WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction());
HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler)
.prependFilter(new IndexRewriteFilter())
.filter(new IndexRewriteFilter())
.build();
Tomcat tomcat = new Tomcat();

View File

@ -1,5 +1,17 @@
package com.baeldung.functional;
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.POST;
import static org.springframework.web.reactive.function.server.RequestPredicates.path;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
@ -17,18 +29,9 @@ import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.WebHandler;
import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
import reactor.core.publisher.Flux;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
import static org.springframework.web.reactive.function.server.RequestPredicates.*;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
@SpringBootApplication
@ComponentScan(basePackages = { "com.baeldung.functional" })
public class FunctionalSpringBootApplication {
@ -57,7 +60,7 @@ public class FunctionalSpringBootApplication {
@Bean
public ServletRegistrationBean servletRegistrationBean() throws Exception {
HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction()))
.prependFilter(new IndexRewriteFilter())
.filter(new IndexRewriteFilter())
.build();
ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(new RootServlet(httpHandler), "/");
registrationBean.setLoadOnStartup(1);

View File

@ -1,5 +1,17 @@
package com.baeldung.functional;
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.POST;
import static org.springframework.web.reactive.function.server.RequestPredicates.path;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
@ -12,18 +24,9 @@ import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.WebHandler;
import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
import reactor.core.publisher.Flux;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
import static org.springframework.web.reactive.function.server.RequestPredicates.*;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
public class FunctionalWebApplication {
private static final Actor BRAD_PITT = new Actor("Brad", "Pitt");
@ -50,7 +53,7 @@ public class FunctionalWebApplication {
WebServer start() throws Exception {
WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction());
HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler)
.prependFilter(new IndexRewriteFilter())
.filter(new IndexRewriteFilter())
.build();
Tomcat tomcat = new Tomcat();

View File

@ -1,5 +1,20 @@
package com.baeldung.functional;
import static org.springframework.web.reactive.function.BodyExtractors.toDataBuffers;
import static org.springframework.web.reactive.function.BodyExtractors.toFormData;
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.POST;
import static org.springframework.web.reactive.function.server.RequestPredicates.path;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ServletHttpHandlerAdapter;
@ -7,29 +22,17 @@ import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.WebHandler;
import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
import static org.springframework.web.reactive.function.BodyExtractors.toDataBuffers;
import static org.springframework.web.reactive.function.BodyExtractors.toFormData;
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
import static org.springframework.web.reactive.function.server.RequestPredicates.*;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
import org.springframework.web.server.WebHandler;
public class RootServlet extends ServletHttpHandlerAdapter {
public RootServlet() {
this(WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction()))
.prependFilter(new IndexRewriteFilter())
.filter(new IndexRewriteFilter())
.build());
}

View File

@ -10,6 +10,7 @@ import javax.json.bind.annotation.JsonbTransient;
public class Person {
private int id;
@JsonbProperty("person-name")
private String name;
@JsonbProperty(nillable = true)
@ -23,8 +24,9 @@ public class Person {
public Person() {
}
public Person(String name, String email, int age, LocalDate registeredDate, BigDecimal salary) {
public Person(int id, String name, String email, int age, LocalDate registeredDate, BigDecimal salary) {
super();
this.id = id;
this.name = name;
this.email = email;
this.age = age;
@ -32,6 +34,14 @@ public class Person {
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
@ -76,7 +86,9 @@ public class Person {
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Person [name=");
builder.append("Person [id=");
builder.append(id);
builder.append(", name=");
builder.append(name);
builder.append(", email=");
builder.append(email);
@ -94,11 +106,7 @@ public class Person {
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((registeredDate == null) ? 0 : registeredDate.hashCode());
result = prime * result + ((salary == null) ? 0 : salary.hashCode());
result = prime * result + id;
return result;
}
@ -111,27 +119,7 @@ public class Person {
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (registeredDate == null) {
if (other.registeredDate != null)
return false;
} else if (!registeredDate.equals(other.registeredDate))
return false;
if (salary == null) {
if (other.salary != null)
return false;
} else if (!salary.equals(other.salary))
if (id != other.id)
return false;
return true;
}

View File

@ -26,12 +26,12 @@ public class PersonController {
public void init() {
// @formatter:off
personRepository = new ArrayList<>(Arrays.asList(
new Person("Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)),
new Person("Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)),
new Person("Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)),
new Person("Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)),
new Person("Mark", "mark@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1200)),
new Person("Julia", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000))));
new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)),
new Person(2, "Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)),
new Person(3, "Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)),
new Person(4, "Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)),
new Person(5, "Mark", "mark@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1200)),
new Person(6, "Julia", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000))));
// @formatter:on
}

View File

@ -1,28 +1,36 @@
package com.baeldung.jupiter;
import org.junit.jupiter.api.extension.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.test.context.TestContextManager;
import org.springframework.util.Assert;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.jupiter.api.extension.TestInstancePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.test.context.TestContextManager;
import org.springframework.util.Assert;
public class SpringExtension implements BeforeAllCallback, AfterAllCallback, TestInstancePostProcessor, BeforeEachCallback, AfterEachCallback, ParameterResolver {
private static final ExtensionContext.Namespace namespace = ExtensionContext.Namespace.create(SpringExtension.class);
@Override
public void beforeAll(ContainerExtensionContext context) throws Exception {
public void beforeAll(ExtensionContext context) throws Exception {
getTestContextManager(context).beforeTestClass();
}
@Override
public void afterAll(ContainerExtensionContext context) throws Exception {
public void afterAll(ExtensionContext context) throws Exception {
try {
getTestContextManager(context).afterTestClass();
} finally {
@ -38,7 +46,7 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
}
@Override
public void beforeEach(TestExtensionContext context) throws Exception {
public void beforeEach(ExtensionContext context) throws Exception {
Object testInstance = context.getTestInstance();
Method testMethod = context.getTestMethod()
.get();
@ -46,24 +54,24 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
}
@Override
public void afterEach(TestExtensionContext context) throws Exception {
public void afterEach(ExtensionContext context) throws Exception {
Object testInstance = context.getTestInstance();
Method testMethod = context.getTestMethod()
.get();
Throwable testException = context.getTestException()
Throwable testException = context.getExecutionException()
.orElse(null);
getTestContextManager(context).afterTestMethod(testInstance, testMethod, testException);
}
@Override
public boolean supports(ParameterContext parameterContext, ExtensionContext extensionContext) {
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
Parameter parameter = parameterContext.getParameter();
Executable executable = parameter.getDeclaringExecutable();
return (executable instanceof Constructor && AnnotatedElementUtils.hasAnnotation(executable, Autowired.class)) || ParameterAutowireUtils.isAutowirable(parameter);
return ((executable instanceof Constructor) && AnnotatedElementUtils.hasAnnotation(executable, Autowired.class)) || ParameterAutowireUtils.isAutowirable(parameter);
}
@Override
public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) {
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
Parameter parameter = parameterContext.getParameter();
Class<?> testClass = extensionContext.getTestClass()
.get();

View File

@ -30,15 +30,14 @@ public class JsonbIntegrationTest {
ResponseEntity<Person> response = template.withBasicAuth(username, password)
.getForEntity("/person/1", Person.class);
Person person = response.getBody();
assertTrue(person.equals(new Person("Jhon", "jhon1@test.com", 0, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500.0))));
assertTrue(person.equals(new Person(2, "Jhon", "jhon1@test.com", 0, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500.0))));
}
@Test
public void whenSendPostAPerson_thenGetOkStatus() {
ResponseEntity<Boolean> response = template.withBasicAuth(username, password)
.postForEntity("/person", "{\"birthDate\":\"07-09-2017\",\"email\":\"jhon1@test.com\",\"person-name\":\"Jhon\"}", Boolean.class);
boolean value = response.getBody();
assertTrue(true == value);
.postForEntity("/person", "{\"birthDate\":\"07-09-2017\",\"email\":\"jhon1@test.com\",\"person-name\":\"Jhon\",\"id\":10}", Boolean.class);
assertTrue(response.getBody());
}
}

View File

@ -22,15 +22,15 @@ public class JsonbTest {
@Test
public void givenPersonObject_whenSerializeWithJsonb_thenGetPersonJson() {
Person person = new Person("Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000));
Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000));
String jsonPerson = jsonb.toJson(person);
assertTrue("{\"email\":\"jhon@test.com\",\"person-name\":\"Jhon\",\"registeredDate\":\"07-09-2019\",\"salary\":\"1000.0\"}".equals(jsonPerson));
assertTrue("{\"email\":\"jhon@test.com\",\"id\":1,\"person-name\":\"Jhon\",\"registeredDate\":\"07-09-2019\",\"salary\":\"1000.0\"}".equals(jsonPerson));
}
@Test
public void givenPersonJson_whenDeserializeWithJsonb_thenGetPersonObject() {
Person person = new Person("Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));
String jsonPerson = "{\"email\":\"jhon@test.com\",\"person-name\":\"Jhon\",\"registeredDate\":\"07-09-2019\",\"salary\":\"1000.0\"}";
Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));
String jsonPerson = "{\"email\":\"jhon@test.com\",\"id\":1,\"person-name\":\"Jhon\",\"registeredDate\":\"07-09-2019\",\"salary\":\"1000.0\"}";
assertTrue(jsonb.fromJson(jsonPerson, Person.class)
.equals(person));
}

View File

@ -8,4 +8,3 @@
- [Spring YAML Configuration](http://www.baeldung.com/spring-yaml)
- [Introduction to Springs StreamUtils](http://www.baeldung.com/spring-stream-utils)
- [Using Spring @Value with Defaults](http://www.baeldung.com/spring-value-defaults)

View File

@ -2,15 +2,9 @@ package com.baeldung.hibernate.immutable.entities;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Immutable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.*;
import java.util.Set;
@Entity
@ -20,8 +14,6 @@ public class Event {
@Id
@Column(name = "event_id")
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
private Long id;
@Column(name = "title")
@ -31,6 +23,14 @@ public class Event {
@Immutable
private Set<String> guestList;
public Event() {}
public Event(Long id, String title, Set<String> guestList) {
this.id = id;
this.title = title;
this.guestList = guestList;
}
public Long getId() {
return id;
}

View File

@ -0,0 +1,55 @@
package com.baeldung.hibernate.immutable.entities;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Immutable;
import javax.persistence.*;
@Entity
@Immutable
@Table(name = "events_generated")
public class EventGeneratedId {
@Id
@Column(name = "event_generated_id")
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
private Long id;
@Column(name = "name")
private String name;
@Column(name = "description")
private String description;
public EventGeneratedId() {
}
public EventGeneratedId(String name, String description) {
this.name = name;
this.description = description;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -1,6 +1,7 @@
package com.baeldung.hibernate.immutable.util;
import com.baeldung.hibernate.immutable.entities.Event;
import com.baeldung.hibernate.immutable.entities.EventGeneratedId;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
@ -14,6 +15,7 @@ public class HibernateUtil {
// Create a session factory from immutable.cfg.xml
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(Event.class);
configuration.addAnnotatedClass(EventGeneratedId.class);
configuration.configure("immutable.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
return configuration.buildSessionFactory(serviceRegistry);

View File

@ -21,7 +21,7 @@
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="username" value="${jdbc.eventGeneratedId}"/>
<property name="password" value="${jdbc.pass}"/>
</bean>

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