fix conflicts and merge with remote
This commit is contained in:
commit
07d5347950
@ -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>
|
||||
|
@ -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());
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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()));
|
||||
}
|
||||
}
|
57
animal-sniffer-mvn-plugin/pom.xml
Normal file
57
animal-sniffer-mvn-plugin/pom.xml
Normal 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>
|
@ -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());
|
||||
}
|
||||
}
|
@ -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 );
|
||||
|
||||
}
|
||||
}
|
@ -19,22 +19,14 @@ public abstract class _Author extends CayenneDataObject {
|
||||
|
||||
public static final String ID_PK_COLUMN = "id";
|
||||
|
||||
public static final Property<String> FIRSTNAME = Property.create("firstname", String.class);
|
||||
public static final Property<String> LASTNAME = Property.create("lastname", String.class);
|
||||
public static final Property<String> NAME = Property.create("name", String.class);
|
||||
public static final Property<List<Article>> ARTICLES = Property.create("articles", List.class);
|
||||
|
||||
public void setFirstname(String firstname) {
|
||||
writeProperty("firstname", firstname);
|
||||
public void setName(String name) {
|
||||
writeProperty("name", name);
|
||||
}
|
||||
public String getFirstname() {
|
||||
return (String)readProperty("firstname");
|
||||
}
|
||||
|
||||
public void setLastname(String lastname) {
|
||||
writeProperty("lastname", lastname);
|
||||
}
|
||||
public String getLastname() {
|
||||
return (String)readProperty("lastname");
|
||||
public String getName() {
|
||||
return (String)readProperty("name");
|
||||
}
|
||||
|
||||
public void addToArticles(Article obj) {
|
||||
|
@ -11,17 +11,15 @@
|
||||
<db-attribute name="title" type="VARCHAR" isMandatory="true" length="254"/>
|
||||
</db-entity>
|
||||
<db-entity name="author" catalog="intro_cayenne">
|
||||
<db-attribute name="firstname" type="VARCHAR" isMandatory="true" length="254"/>
|
||||
<db-attribute name="id" type="INTEGER" isPrimaryKey="true" isGenerated="true" isMandatory="true" length="10"/>
|
||||
<db-attribute name="lastname" type="VARCHAR" isMandatory="true" length="254"/>
|
||||
<db-attribute name="name" type="VARCHAR" isMandatory="true" length="254"/>
|
||||
</db-entity>
|
||||
<obj-entity name="Article" className="com.baeldung.apachecayenne.persistent.Article" dbEntityName="article">
|
||||
<obj-attribute name="content" type="java.lang.String" db-attribute-path="content"/>
|
||||
<obj-attribute name="title" type="java.lang.String" db-attribute-path="title"/>
|
||||
</obj-entity>
|
||||
<obj-entity name="Author" className="com.baeldung.apachecayenne.persistent.Author" dbEntityName="author">
|
||||
<obj-attribute name="firstname" type="java.lang.String" db-attribute-path="firstname"/>
|
||||
<obj-attribute name="lastname" type="java.lang.String" db-attribute-path="lastname"/>
|
||||
<obj-attribute name="name" type="java.lang.String" db-attribute-path="name"/>
|
||||
</obj-entity>
|
||||
<db-relationship name="author" source="article" target="author" toMany="false">
|
||||
<db-attribute-pair source="author_id" target="id"/>
|
||||
|
@ -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() {
|
||||
String [] args = {"Paul Xavier", "pAuL Smith", "Vicky Sarra"};
|
||||
List<Author> authors = ObjectSelect.query(Author.class)
|
||||
.where(Author.NAME.in(Arrays.asList(args)))
|
||||
.select(context);
|
||||
|
||||
assertEquals(authors.size(), 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoAuthor_whenNinObjS_thenWeGetAuthors() {
|
||||
String [] args = {"Paul Xavier", "pAuL Smith"};
|
||||
List<Author> authors = ObjectSelect.query(Author.class)
|
||||
.where(Author.NAME.nin(Arrays.asList(args)))
|
||||
.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);
|
||||
}
|
||||
}
|
@ -39,8 +39,7 @@ public class CayenneOperationTests {
|
||||
@Test
|
||||
public void givenAuthor_whenInsert_thenWeGetOneRecordInTheDatabase() {
|
||||
Author author = context.newObject(Author.class);
|
||||
author.setFirstname("Paul");
|
||||
author.setLastname("Smith");
|
||||
author.setName("Paul");
|
||||
|
||||
context.commitChanges();
|
||||
|
||||
@ -51,28 +50,24 @@ public class CayenneOperationTests {
|
||||
@Test
|
||||
public void givenAuthor_whenInsert_andQueryByFirstName_thenWeGetTheAuthor() {
|
||||
Author author = context.newObject(Author.class);
|
||||
author.setFirstname("Paul");
|
||||
author.setLastname("Smith");
|
||||
author.setName("Paul");
|
||||
|
||||
context.commitChanges();
|
||||
|
||||
Author expectedAuthor = ObjectSelect.query(Author.class)
|
||||
.where(Author.FIRSTNAME.eq("Paul"))
|
||||
.where(Author.NAME.eq("Paul"))
|
||||
.selectOne(context);
|
||||
|
||||
assertEquals("Paul", expectedAuthor.getFirstname());
|
||||
assertEquals("Smith", expectedAuthor.getLastname());
|
||||
assertEquals("Paul", expectedAuthor.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoAuthor_whenInsert_andQueryAll_thenWeGetTwoAuthors() {
|
||||
Author firstAuthor = context.newObject(Author.class);
|
||||
firstAuthor.setFirstname("Paul");
|
||||
firstAuthor.setLastname("Smith");
|
||||
firstAuthor.setName("Paul");
|
||||
|
||||
Author secondAuthor = context.newObject(Author.class);
|
||||
secondAuthor.setFirstname("Ludovic");
|
||||
secondAuthor.setLastname("Garcia");
|
||||
secondAuthor.setName("Ludovic");
|
||||
|
||||
context.commitChanges();
|
||||
|
||||
@ -83,44 +78,40 @@ public class CayenneOperationTests {
|
||||
@Test
|
||||
public void givenAuthor_whenUpdating_thenWeGetAnUpatedeAuthor() {
|
||||
Author author = context.newObject(Author.class);
|
||||
author.setFirstname("Paul");
|
||||
author.setLastname("Smith");
|
||||
author.setName("Paul");
|
||||
context.commitChanges();
|
||||
|
||||
Author expectedAuthor = ObjectSelect.query(Author.class)
|
||||
.where(Author.FIRSTNAME.eq("Paul"))
|
||||
.where(Author.NAME.eq("Paul"))
|
||||
.selectOne(context);
|
||||
expectedAuthor.setLastname("Smith 2");
|
||||
expectedAuthor.setName("Garcia");
|
||||
context.commitChanges();
|
||||
|
||||
assertEquals(author.getFirstname(), expectedAuthor.getFirstname());
|
||||
assertEquals(author.getLastname(), expectedAuthor.getLastname());
|
||||
assertEquals(author.getName(), expectedAuthor.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthor_whenDeleting_thenWeLostHisDetails() {
|
||||
Author author = context.newObject(Author.class);
|
||||
author.setFirstname("Paul");
|
||||
author.setLastname("Smith");
|
||||
author.setName("Paul");
|
||||
context.commitChanges();
|
||||
|
||||
Author savedAuthor = ObjectSelect.query(Author.class)
|
||||
.where(Author.FIRSTNAME.eq("Paul")).selectOne(context);
|
||||
.where(Author.NAME.eq("Paul")).selectOne(context);
|
||||
if(savedAuthor != null) {
|
||||
context.deleteObjects(author);
|
||||
context.commitChanges();
|
||||
}
|
||||
|
||||
Author expectedAuthor = ObjectSelect.query(Author.class)
|
||||
.where(Author.FIRSTNAME.eq("Paul")).selectOne(context);
|
||||
.where(Author.NAME.eq("Paul")).selectOne(context);
|
||||
assertNull(expectedAuthor);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthor_whenAttachingToArticle_thenTheRelationIsMade() {
|
||||
Author author = context.newObject(Author.class);
|
||||
author.setFirstname("Paul");
|
||||
author.setLastname("Smith");
|
||||
author.setName("Paul");
|
||||
|
||||
Article article = context.newObject(Article.class);
|
||||
article.setTitle("My post title");
|
||||
@ -130,7 +121,7 @@ public class CayenneOperationTests {
|
||||
context.commitChanges();
|
||||
|
||||
Author expectedAuthor = ObjectSelect.query(Author.class)
|
||||
.where(Author.LASTNAME.eq("Smith"))
|
||||
.where(Author.NAME.eq("Paul"))
|
||||
.selectOne(context);
|
||||
|
||||
Article expectedArticle = (expectedAuthor.getArticles()).get(0);
|
||||
|
1
atomix/.gitignore
vendored
Normal file
1
atomix/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
/target
|
46
atomix/pom.xml
Normal file
46
atomix/pom.xml
Normal 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>
|
@ -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();
|
||||
}
|
||||
}
|
71
atomix/src/main/java/com/atomix/example/OtherNodes.java
Normal file
71
atomix/src/main/java/com/atomix/example/OtherNodes.java
Normal 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();
|
||||
}
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
|
3
guest/tomcat-app/WebContent/META-INF/MANIFEST.MF
Normal file
3
guest/tomcat-app/WebContent/META-INF/MANIFEST.MF
Normal file
@ -0,0 +1,3 @@
|
||||
Manifest-Version: 1.0
|
||||
Class-Path:
|
||||
|
28
guest/tomcat-app/WebContent/WEB-INF/web.xml
Normal file
28
guest/tomcat-app/WebContent/WEB-INF/web.xml
Normal file
@ -0,0 +1,28 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
|
||||
id="WebApp_ID" version="3.1">
|
||||
<display-name>tomcat-app</display-name>
|
||||
<servlet>
|
||||
<servlet-name>tomcat-app</servlet-name>
|
||||
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
|
||||
<init-param>
|
||||
<param-name>javax.ws.rs.Application</param-name>
|
||||
<param-value>com.stackify.ApplicationInitializer</param-value>
|
||||
</init-param>
|
||||
<load-on-startup>1</load-on-startup>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>tomcat-app</servlet-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
</servlet-mapping>
|
||||
<filter>
|
||||
<filter-name>javamelody</filter-name>
|
||||
<filter-class>net.bull.javamelody.MonitoringFilter</filter-class>
|
||||
<init-param>
|
||||
<param-name>gzip-compression-disabled</param-name>
|
||||
<param-value>true</param-value>
|
||||
</init-param>
|
||||
</filter>
|
||||
</web-app>
|
70
guest/tomcat-app/pom.xml
Normal file
70
guest/tomcat-app/pom.xml
Normal file
@ -0,0 +1,70 @@
|
||||
<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.stackify</groupId>
|
||||
<artifactId>tomcat-app</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.containers</groupId>
|
||||
<artifactId>jersey-container-servlet</artifactId>
|
||||
<version>2.25.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.media</groupId>
|
||||
<artifactId>jersey-media-moxy</artifactId>
|
||||
<version>2.25.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.rest-assured</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
<version>3.0.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>1.4.195</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>2.8.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.bull.javamelody</groupId>
|
||||
<artifactId>javamelody-core</artifactId>
|
||||
<version>1.69.0</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>3.0.0</version>
|
||||
<configuration>
|
||||
<warSourceDirectory>WebContent</warSourceDirectory>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
@ -0,0 +1,9 @@
|
||||
package com.stackify;
|
||||
|
||||
import org.glassfish.jersey.server.ResourceConfig;
|
||||
|
||||
public class ApplicationInitializer extends ResourceConfig {
|
||||
public ApplicationInitializer() {
|
||||
packages("com.stackify.services");
|
||||
}
|
||||
}
|
@ -0,0 +1,67 @@
|
||||
package com.stackify.daos;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import com.stackify.models.User;
|
||||
import com.stackify.utils.ConnectionUtil;
|
||||
|
||||
public class UserDAO {
|
||||
|
||||
private Logger logger = LogManager.getLogger(UserDAO.class);
|
||||
|
||||
public void createTable() {
|
||||
try (Connection con = ConnectionUtil.getConnection()) {
|
||||
String createQuery = "CREATE TABLE IF NOT EXISTS users(email varchar(50) primary key, name varchar(50))";
|
||||
PreparedStatement pstmt = con.prepareStatement(createQuery);
|
||||
|
||||
pstmt.execute();
|
||||
} catch (SQLException exc) {
|
||||
logger.error(exc.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void add(User user) {
|
||||
try (Connection con = ConnectionUtil.getConnection()) {
|
||||
|
||||
String insertQuery = "INSERT INTO users(email,name) VALUES(?,?)";
|
||||
PreparedStatement pstmt = con.prepareStatement(insertQuery);
|
||||
pstmt.setString(1, user.getEmail());
|
||||
pstmt.setString(2, user.getName());
|
||||
|
||||
pstmt.executeUpdate();
|
||||
} catch (SQLException exc) {
|
||||
logger.error(exc.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public List<User> findAll() {
|
||||
List<User> users = new ArrayList<>();
|
||||
|
||||
try (Connection con = ConnectionUtil.getConnection()) {
|
||||
String query = "SELECT * FROM users";
|
||||
PreparedStatement pstmt = con.prepareStatement(query);
|
||||
|
||||
ResultSet rs = pstmt.executeQuery();
|
||||
while (rs.next()) {
|
||||
User user = new User();
|
||||
user.setEmail(rs.getString("email"));
|
||||
user.setName(rs.getString("name"));
|
||||
users.add(user);
|
||||
}
|
||||
} catch (SQLException exc) {
|
||||
logger.error(exc.getMessage());
|
||||
}
|
||||
|
||||
return users;
|
||||
}
|
||||
|
||||
}
|
43
guest/tomcat-app/src/main/java/com/stackify/models/User.java
Normal file
43
guest/tomcat-app/src/main/java/com/stackify/models/User.java
Normal file
@ -0,0 +1,43 @@
|
||||
package com.stackify.models;
|
||||
|
||||
import javax.ws.rs.core.Link;
|
||||
|
||||
public class User {
|
||||
private String email;
|
||||
private String name;
|
||||
private Link link;
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String email, String name) {
|
||||
super();
|
||||
this.email = email;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Link getLink() {
|
||||
return link;
|
||||
}
|
||||
|
||||
public void setLink(Link link) {
|
||||
this.link = link;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package com.stackify.services;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.ws.rs.container.ContainerRequestContext;
|
||||
import javax.ws.rs.container.ContainerResponseContext;
|
||||
import javax.ws.rs.container.ContainerResponseFilter;
|
||||
import javax.ws.rs.ext.Provider;
|
||||
|
||||
@Provider
|
||||
public class CorsFilter implements ContainerResponseFilter {
|
||||
|
||||
@Override
|
||||
public void filter(final ContainerRequestContext requestContext,
|
||||
final ContainerResponseContext response) throws IOException {
|
||||
response.getHeaders().add("Access-Control-Allow-Origin", "*");
|
||||
response.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept");
|
||||
}
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package com.stackify.services;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
import com.stackify.daos.UserDAO;
|
||||
import com.stackify.models.User;
|
||||
|
||||
@Path("/users")
|
||||
public class UserService {
|
||||
private UserDAO userDao = new UserDAO();
|
||||
|
||||
public UserService (){
|
||||
userDao.createTable();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public Response addUser(User user) {
|
||||
userDao.add(user);
|
||||
return Response.ok()
|
||||
.build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public List<User> getUsers() {
|
||||
return userDao.findAll();
|
||||
}
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
package com.stackify.utils;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import javax.naming.Context;
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
public class ConnectionUtil {
|
||||
|
||||
private static Logger logger = LogManager.getLogger(ConnectionUtil.class);
|
||||
|
||||
public static Connection getConnection() {
|
||||
try {
|
||||
String jndiName = "java:/comp/env/jdbc/MyDataSource";
|
||||
|
||||
Context initialContext = new InitialContext();
|
||||
DataSource datasource = (DataSource)initialContext.lookup(jndiName);
|
||||
if (datasource != null) {
|
||||
return datasource.getConnection();
|
||||
}
|
||||
else {
|
||||
logger.error("Failed to lookup datasource.");
|
||||
}
|
||||
}
|
||||
|
||||
catch (NamingException | SQLException exc) {
|
||||
logger.error(exc.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
@ -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>
|
@ -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()));
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -1,8 +0,0 @@
|
||||
package com.baeldung.beanvalidation.service;
|
||||
|
||||
public interface EntityService {
|
||||
|
||||
public String toString();
|
||||
|
||||
public void processEntity();
|
||||
}
|
@ -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 + "]";
|
||||
}
|
||||
}
|
@ -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());
|
||||
}
|
||||
}
|
@ -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>
|
||||
|
66
javaxval/src/main/java/org/baeldung/Customer.java
Normal file
66
javaxval/src/main/java/org/baeldung/Customer.java
Normal 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;
|
||||
}
|
||||
|
||||
}
|
19
javaxval/src/main/java/org/baeldung/CustomerMap.java
Normal file
19
javaxval/src/main/java/org/baeldung/CustomerMap.java
Normal 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;
|
||||
}
|
||||
}
|
13
javaxval/src/main/java/org/baeldung/Profile.java
Normal file
13
javaxval/src/main/java/org/baeldung/Profile.java
Normal 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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
List<@NotBlank String> preferences;
|
||||
|
||||
public boolean isWorking() {
|
||||
return working;
|
||||
}
|
||||
private LocalDate dateOfBirth;
|
||||
|
||||
public void setWorking(boolean working) {
|
||||
this.working = working;
|
||||
}
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public String getAboutMe() {
|
||||
return aboutMe;
|
||||
}
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public void setAboutMe(String aboutMe) {
|
||||
this.aboutMe = aboutMe;
|
||||
}
|
||||
public boolean isWorking() {
|
||||
return working;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public void setWorking(boolean working) {
|
||||
this.working = working;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public String getAboutMe() {
|
||||
return aboutMe;
|
||||
}
|
||||
|
||||
public void setAboutMe(String aboutMe) {
|
||||
this.aboutMe = aboutMe;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1 @@
|
||||
org.baeldung.valueextractors.ProfileValueExtractor
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
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 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 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());
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -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>
|
||||
@ -569,12 +569,38 @@
|
||||
<groupId>javax.cache</groupId>
|
||||
<artifactId>cache-api</artifactId>
|
||||
<version>${cache.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.hazelcast</groupId>
|
||||
<artifactId>hazelcast</artifactId>
|
||||
<version>${hazelcast.version}</version>
|
||||
</dependency>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.hazelcast</groupId>
|
||||
<artifactId>hazelcast</artifactId>
|
||||
<version>${hazelcast.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.atlassian.jira</groupId>
|
||||
<artifactId>jira-rest-java-client-core</artifactId>
|
||||
<version>4.0.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.atlassian.fugue</groupId>
|
||||
<artifactId>fugue</artifactId>
|
||||
<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>
|
||||
</dependencies>
|
||||
<repositories>
|
||||
<repository>
|
||||
@ -590,8 +616,13 @@
|
||||
<name>bintray</name>
|
||||
<url>http://dl.bintray.com/cuba-platform/main</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>atlassian-public</id>
|
||||
<url>https://packages.atlassian.com/maven/repository/public</url>
|
||||
</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>
|
||||
@ -644,6 +675,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>
|
@ -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
|
||||
|
||||
}
|
||||
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
105
libraries/src/main/java/com/baeldung/jdo/xml/MyApp.java
Normal file
105
libraries/src/main/java/com/baeldung/jdo/xml/MyApp.java
Normal 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());
|
||||
}
|
||||
}
|
65
libraries/src/main/java/com/baeldung/jdo/xml/Person.java
Normal file
65
libraries/src/main/java/com/baeldung/jdo/xml/Person.java
Normal 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;
|
||||
}
|
||||
|
||||
}
|
58
libraries/src/main/java/com/baeldung/jdo/xml/Product.java
Normal file
58
libraries/src/main/java/com/baeldung/jdo/xml/Product.java
Normal 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;
|
||||
}
|
||||
|
||||
|
||||
}
|
103
libraries/src/main/java/com/baeldung/jira/MyJiraClient.java
Normal file
103
libraries/src/main/java/com/baeldung/jira/MyJiraClient.java
Normal 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();
|
||||
}
|
||||
|
||||
public 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();
|
||||
}
|
||||
|
||||
public void voteForAnIssue(Issue issue) {
|
||||
restClient.getIssueClient().vote(issue.getVotesUri()).claim();
|
||||
}
|
||||
|
||||
public int getTotalVotesCount(String issueKey) {
|
||||
BasicVotes votes = getIssue(issueKey).getVotes();
|
||||
return votes == null ? 0 : votes.getVotes();
|
||||
}
|
||||
|
||||
public void addComment(Issue issue, String commentBody) {
|
||||
restClient.getIssueClient().addComment(issue.getCommentsUri(), Comment.valueOf(commentBody));
|
||||
}
|
||||
|
||||
public List<Comment> getAllComments(String issueKey) {
|
||||
return StreamSupport.stream(getIssue(issueKey).getComments().spliterator(), false)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public void updateIssueDescription(String issueKey, String newDescription) {
|
||||
IssueInput input = new IssueInputBuilder().setDescription(newDescription).build();
|
||||
restClient.getIssueClient().updateIssue(issueKey, input).claim();
|
||||
}
|
||||
|
||||
public 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);
|
||||
}
|
||||
}
|
@ -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
|
17
libraries/src/main/resources/META-INF/jdoconfig.xml
Normal file
17
libraries/src/main/resources/META-INF/jdoconfig.xml
Normal 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>
|
21
libraries/src/main/resources/META-INF/package.jdo
Normal file
21
libraries/src/main/resources/META-INF/package.jdo
Normal 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>
|
@ -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;
|
||||
@Test
|
||||
public void givenMultipleCopies_whenAdded_theCountIsKept() {
|
||||
Bag<Integer> bag = new HashBag<>(
|
||||
Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
|
||||
|
||||
@Before
|
||||
public void before() {
|
||||
baseBag = new HashBag<String>();
|
||||
treeBag = new TreeBag<String>();
|
||||
treeBag = new TreeBag<String>();
|
||||
}
|
||||
assertThat(bag.getCount(1), equalTo(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAdd_thenRemoveFromBaseBag_thenContainsCorrect() {
|
||||
baseBag.add("apple", 2);
|
||||
baseBag.add("lemon", 6);
|
||||
baseBag.add("lime");
|
||||
@Test
|
||||
public void givenBag_whenBagAddAPILikeCollectionAPI_thenFalse() {
|
||||
Collection<Integer> collection = new ArrayList<>();
|
||||
|
||||
baseBag.remove("lemon");
|
||||
Assert.assertEquals(3, baseBag.size());
|
||||
Assert.assertFalse(baseBag.contains("lemon"));
|
||||
// Collection contract defines that add() should return true
|
||||
assertThat(collection.add(9), is(true));
|
||||
|
||||
Assert.assertTrue(baseBag.uniqueSet().contains("apple"));
|
||||
// Even when element is already in the collection
|
||||
collection.add(1);
|
||||
assertThat(collection.add(1), is(true));
|
||||
|
||||
List<String> containList = new ArrayList<String>();
|
||||
containList.add("apple");
|
||||
containList.add("lemon");
|
||||
containList.add("lime");
|
||||
Assert.assertFalse(baseBag.containsAll(containList));
|
||||
}
|
||||
Bag<Integer> bag = new HashBag<>();
|
||||
|
||||
@Test
|
||||
public void whenAdd_thenRemoveFromBaseCollectionBag_thenContainsCorrect() {
|
||||
baseBag.add("apple", 2);
|
||||
baseBag.add("lemon", 6);
|
||||
baseBag.add("lime");
|
||||
// Bag returns true on adding a new element
|
||||
assertThat(bag.add(9), is(true));
|
||||
|
||||
CollectionBag<String> baseCollectionBag = new CollectionBag<String>(
|
||||
baseBag);
|
||||
bag.add(1);
|
||||
// But breaks the contract with false when it has to increment the count
|
||||
assertThat(bag.add(1), is(not(true)));
|
||||
}
|
||||
|
||||
baseCollectionBag.remove("lemon");
|
||||
Assert.assertEquals(8, baseCollectionBag.size());
|
||||
Assert.assertTrue(baseCollectionBag.contains("lemon"));
|
||||
@Test
|
||||
public void givenDecoratedBag_whenBagAddAPILikeCollectionAPI_thenTrue() {
|
||||
Bag<Integer> bag = CollectionBag.collectionBag(new HashBag<>());
|
||||
|
||||
baseCollectionBag.remove("lemon",1);
|
||||
Assert.assertEquals(7, baseCollectionBag.size());
|
||||
bag.add(1);
|
||||
// This time the behavior is compliant to the Java Collection
|
||||
assertThat(bag.add(1), is((true)));
|
||||
}
|
||||
|
||||
Assert.assertTrue(baseBag.uniqueSet().contains("apple"));
|
||||
@Test
|
||||
public void givenAdd_whenCountOfElementsDefined_thenCountAreAdded() {
|
||||
Bag<Integer> bag = new HashBag<>();
|
||||
|
||||
List<String> containList = new ArrayList<String>();
|
||||
containList.add("apple");
|
||||
containList.add("lemon");
|
||||
containList.add("lime");
|
||||
Assert.assertTrue(baseBag.containsAll(containList));
|
||||
}
|
||||
// Adding 1 for 5 times
|
||||
bag.add(1, 5);
|
||||
assertThat(bag.getCount(1), equalTo(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddtoTreeBag_thenRemove_thenContainsCorrect() {
|
||||
treeBag.add("banana", 8);
|
||||
treeBag.add("apple", 2);
|
||||
treeBag.add("lime");
|
||||
@Test
|
||||
public void givenMultipleCopies_whenRemove_allAreRemoved() {
|
||||
Bag<Integer> bag = new HashBag<>(
|
||||
Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
|
||||
|
||||
Assert.assertEquals(11, treeBag.size());
|
||||
Assert.assertEquals("apple", treeBag.first());
|
||||
Assert.assertEquals("lime", treeBag.last());
|
||||
// From 3 we delete 1, 2 remain
|
||||
bag.remove(3, 1);
|
||||
assertThat(bag.getCount(3), equalTo(2));
|
||||
|
||||
treeBag.remove("apple");
|
||||
Assert.assertEquals(9, treeBag.size());
|
||||
Assert.assertEquals("banana", treeBag.first());
|
||||
// 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));
|
||||
}
|
||||
}
|
||||
|
@ -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());
|
||||
|
||||
}
|
||||
}
|
||||
|
153
libraries/src/test/java/com/baeldung/crdt/CRDTTest.java
Normal file
153
libraries/src/test/java/com/baeldung/crdt/CRDTTest.java
Normal 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");
|
||||
}
|
||||
}
|
@ -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");
|
||||
}
|
||||
}
|
1
pom.xml
1
pom.xml
@ -28,6 +28,7 @@
|
||||
</properties>
|
||||
|
||||
<modules>
|
||||
<module>atomix</module>
|
||||
<module>apache-cayenne</module>
|
||||
<module>aws</module>
|
||||
<module>akka-streams</module>
|
||||
|
@ -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>
|
||||
|
||||
@ -47,6 +46,12 @@
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>22.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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)
|
||||
);
|
||||
|
||||
|
@ -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);
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -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));
|
||||
|
@ -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);
|
||||
|
235
rxjava/src/test/java/com/baeldung/rxjava/SchedulersTest.java
Normal file
235
rxjava/src/test/java/com/baeldung/rxjava/SchedulersTest.java
Normal file
@ -0,0 +1,235 @@
|
||||
package com.baeldung.rxjava;
|
||||
|
||||
import com.google.common.util.concurrent.ThreadFactoryBuilder;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import rx.Observable;
|
||||
import rx.Scheduler;
|
||||
import rx.observers.TestSubscriber;
|
||||
import rx.schedulers.Schedulers;
|
||||
import rx.schedulers.TestScheduler;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static java.util.concurrent.Executors.newFixedThreadPool;
|
||||
import static org.hamcrest.Matchers.hasItems;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class SchedulersTest {
|
||||
private String result = "";
|
||||
private String result1 = "";
|
||||
private String result2 = "";
|
||||
|
||||
@Test
|
||||
public void givenScheduledWorker_whenScheduleAnAction_thenResultAction() throws InterruptedException {
|
||||
System.out.println("scheduling");
|
||||
Scheduler scheduler = Schedulers.immediate();
|
||||
Scheduler.Worker worker = scheduler.createWorker();
|
||||
worker.schedule(() -> result += "action");
|
||||
Assert.assertTrue(result.equals("action"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenScheduledWorker_whenUnsubscribeOnWorker_thenResultFirstAction() throws InterruptedException {
|
||||
System.out.println("canceling");
|
||||
Scheduler scheduler = Schedulers.newThread();
|
||||
Scheduler.Worker worker = scheduler.createWorker();
|
||||
worker.schedule(() -> {
|
||||
result += "First_Action";
|
||||
worker.unsubscribe();
|
||||
});
|
||||
worker.schedule(() -> result += "Second_Action");
|
||||
Thread.sleep(500);
|
||||
Assert.assertTrue(result.equals("First_Action"));
|
||||
}
|
||||
|
||||
@Ignore //it's not safe, not every time is running correctly
|
||||
@Test
|
||||
public void givenWorker_whenScheduledOnNewThread_thenResultIsBoundToNewThread() throws InterruptedException {
|
||||
System.out.println("newThread_1");
|
||||
Scheduler scheduler = Schedulers.newThread();
|
||||
Scheduler.Worker worker = scheduler.createWorker();
|
||||
worker.schedule(() -> {
|
||||
result += Thread.currentThread().getName() + "_Start";
|
||||
worker.schedule(() -> result += "_worker_");
|
||||
result += "_End";
|
||||
});
|
||||
Thread.sleep(2000);
|
||||
Assert.assertTrue(result.equals("RxNewThreadScheduler-1_Start_End_worker_"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenObservable_whenObserveOnNewThread_thenRunOnDifferentThreadEachTime() throws InterruptedException {
|
||||
System.out.println("newThread_2");
|
||||
Observable.just("Hello")
|
||||
.observeOn(Schedulers.newThread())
|
||||
.doOnNext(s ->
|
||||
result2 += Thread.currentThread().getName()
|
||||
)
|
||||
.observeOn(Schedulers.newThread())
|
||||
.subscribe(s ->
|
||||
result1 += Thread.currentThread().getName()
|
||||
);
|
||||
Thread.sleep(500);
|
||||
Assert.assertTrue(result1.equals("RxNewThreadScheduler-1"));
|
||||
Assert.assertTrue(result2.equals("RxNewThreadScheduler-2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWorker_whenScheduledOnImmediate_thenResultIsBoundToThread() throws InterruptedException {
|
||||
System.out.println("immediate_1");
|
||||
Scheduler scheduler = Schedulers.immediate();
|
||||
Scheduler.Worker worker = scheduler.createWorker();
|
||||
worker.schedule(() -> {
|
||||
result += Thread.currentThread().getName() + "_Start";
|
||||
worker.schedule(() -> result += "_worker_");
|
||||
result += "_End";
|
||||
});
|
||||
Thread.sleep(500);
|
||||
Assert.assertTrue(result.equals("main_Start_worker__End"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenObservable_whenImmediateScheduled_thenExecuteOnMainThread() throws InterruptedException {
|
||||
System.out.println("immediate_2");
|
||||
Observable.just("Hello")
|
||||
.subscribeOn(Schedulers.immediate())
|
||||
.subscribe(s ->
|
||||
result += Thread.currentThread().getName()
|
||||
);
|
||||
Thread.sleep(500);
|
||||
Assert.assertTrue(result.equals("main"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenObservable_whenTrampolineScheduled_thenExecuteOnMainThread() throws InterruptedException {
|
||||
System.out.println("trampoline_1");
|
||||
Observable.just(2, 4, 6, 8)
|
||||
.subscribeOn(Schedulers.trampoline())
|
||||
.subscribe(i -> result += "" + i);
|
||||
Observable.just(1, 3, 5, 7, 9)
|
||||
.subscribeOn(Schedulers.trampoline())
|
||||
.subscribe(i -> result += "" + i);
|
||||
Thread.sleep(500);
|
||||
Assert.assertTrue(result.equals("246813579"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWorker_whenScheduledOnTrampoline_thenComposeResultAsBlocking() throws InterruptedException {
|
||||
System.out.println("trampoline_2");
|
||||
Scheduler scheduler = Schedulers.trampoline();
|
||||
Scheduler.Worker worker = scheduler.createWorker();
|
||||
worker.schedule(() -> {
|
||||
result += Thread.currentThread().getName() + "Start";
|
||||
worker.schedule(() -> {
|
||||
result += "_middleStart";
|
||||
worker.schedule(() ->
|
||||
result += "_worker_"
|
||||
);
|
||||
result += "_middleEnd";
|
||||
});
|
||||
result += "_mainEnd";
|
||||
});
|
||||
Thread.sleep(500);
|
||||
Assert.assertTrue(result
|
||||
.equals("mainStart_mainEnd_middleStart_middleEnd_worker_"));
|
||||
}
|
||||
|
||||
private ThreadFactory threadFactory(String pattern) {
|
||||
return new ThreadFactoryBuilder()
|
||||
.setNameFormat(pattern)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExecutors_whenSchedulerFromCreatedExecutors_thenReturnElementsOnEacheThread() throws InterruptedException {
|
||||
System.out.println("from");
|
||||
ExecutorService poolA = newFixedThreadPool(10, threadFactory("Sched-A-%d"));
|
||||
Scheduler schedulerA = Schedulers.from(poolA);
|
||||
ExecutorService poolB = newFixedThreadPool(10, threadFactory("Sched-B-%d"));
|
||||
Scheduler schedulerB = Schedulers.from(poolB);
|
||||
|
||||
Observable<String> observable = Observable.create(subscriber -> {
|
||||
subscriber.onNext("Alfa");
|
||||
subscriber.onNext("Beta");
|
||||
subscriber.onCompleted();
|
||||
});
|
||||
;
|
||||
|
||||
observable
|
||||
.subscribeOn(schedulerA)
|
||||
.subscribeOn(schedulerB)
|
||||
.subscribe(
|
||||
x -> result += Thread.currentThread().getName() + x + "_",
|
||||
Throwable::printStackTrace,
|
||||
() -> result += "_Completed"
|
||||
);
|
||||
Thread.sleep(2000);
|
||||
Assert.assertTrue(result.equals("Sched-A-0Alfa_Sched-A-0Beta__Completed"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenObservable_whenIoScheduling_thenReturnThreadName() throws InterruptedException {
|
||||
System.out.println("io");
|
||||
Observable.just("io")
|
||||
.subscribeOn(Schedulers.io())
|
||||
.subscribe(i -> result += Thread.currentThread().getName());
|
||||
Thread.sleep(500);
|
||||
Assert.assertTrue(result.equals("RxIoScheduler-2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenObservable_whenComputationScheduling_thenReturnThreadName() throws InterruptedException {
|
||||
System.out.println("computation");
|
||||
Observable.just("computation")
|
||||
.subscribeOn(Schedulers.computation())
|
||||
.subscribe(i -> result += Thread.currentThread().getName());
|
||||
Thread.sleep(500);
|
||||
Assert.assertTrue(result.equals("RxComputationScheduler-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLetters_whenTestScheduling_thenReturnValuesControllingAdvanceTime() throws InterruptedException {
|
||||
List<String> letters = Arrays.asList("A", "B", "C");
|
||||
TestScheduler scheduler = Schedulers.test();
|
||||
TestSubscriber<String> subscriber = new TestSubscriber<>();
|
||||
|
||||
Observable<Long> tick = Observable.interval(1, TimeUnit.SECONDS, scheduler);
|
||||
|
||||
Observable.from(letters)
|
||||
.zipWith(tick, (string, index) -> index + "-" + string)
|
||||
.subscribeOn(scheduler)
|
||||
.subscribe(subscriber);
|
||||
|
||||
subscriber.assertNoValues();
|
||||
subscriber.assertNotCompleted();
|
||||
|
||||
scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
|
||||
subscriber.assertNoErrors();
|
||||
subscriber.assertValueCount(1);
|
||||
subscriber.assertValues("0-A");
|
||||
|
||||
scheduler.advanceTimeTo(3, TimeUnit.SECONDS);
|
||||
subscriber.assertCompleted();
|
||||
subscriber.assertNoErrors();
|
||||
subscriber.assertValueCount(3);
|
||||
assertThat(subscriber.getOnNextEvents(), hasItems("0-A", "1-B", "2-C"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLetters_whenDelay_thenReturne() throws InterruptedException {
|
||||
ExecutorService poolA = newFixedThreadPool(10, threadFactory("Sched1-"));
|
||||
Scheduler schedulerA = Schedulers.from(poolA);
|
||||
Observable.just('A', 'B')
|
||||
.delay(1, TimeUnit.SECONDS, schedulerA)
|
||||
.subscribe(i -> result += Thread.currentThread().getName() + i + " ");
|
||||
|
||||
Thread.sleep(2000);
|
||||
Assert.assertTrue(result.equals("Sched1-A Sched1-B "));
|
||||
}
|
||||
}
|
@ -20,5 +20,4 @@ public class SingleTest {
|
||||
single.subscribe();
|
||||
assertTrue(result[0].equals("Hello"));
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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());
|
||||
|
@ -7,6 +7,7 @@ import rx.Observable;
|
||||
import rx.Observer;
|
||||
import rx.exceptions.OnErrorNotImplementedException;
|
||||
import rx.schedulers.Schedulers;
|
||||
import rx.schedulers.Timestamped;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@ -14,9 +15,9 @@ 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();
|
||||
@ -44,7 +45,6 @@ public class UtilityOperatorsTest {
|
||||
assertTrue(receivedTotal == 15000);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenObservable_whenObserveOnBeforeOnNext_thenEmitsEventsOnComputeScheduler() throws InterruptedException {
|
||||
|
||||
@ -68,7 +68,6 @@ public class UtilityOperatorsTest {
|
||||
assertTrue(receivedTotal == 15000);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenObservable_whenSubscribeOn_thenEmitsEventsOnComputeScheduler() throws InterruptedException {
|
||||
|
||||
@ -92,7 +91,6 @@ public class UtilityOperatorsTest {
|
||||
assertTrue(receivedTotal == 15000);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenObservableWithOneEvent_whenSingle_thenEmitEvent() {
|
||||
|
||||
@ -197,15 +195,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"));
|
||||
@ -231,14 +227,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 +242,6 @@ public class UtilityOperatorsTest {
|
||||
assertTrue(result.equals("resource"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenObservableCached_whenSubscribesWith2Actions_thenEmitsCachedValues() {
|
||||
|
||||
@ -269,5 +262,4 @@ public class UtilityOperatorsTest {
|
||||
});
|
||||
assertTrue(receivedTotal == 8);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -13,7 +13,7 @@ import com.github.davidmoten.rx.jdbc.Database;
|
||||
|
||||
import rx.Observable;
|
||||
|
||||
public class AutomapClassTest {
|
||||
public class AutomapClassIntegrationTest {
|
||||
|
||||
private ConnectionProvider connectionProvider = Connector.connectionProvider;
|
||||
private Database db = Database.from(connectionProvider);
|
@ -13,7 +13,7 @@ import com.github.davidmoten.rx.jdbc.Database;
|
||||
|
||||
import rx.Observable;
|
||||
|
||||
public class AutomapInterfaceTest {
|
||||
public class AutomapInterfaceIntegrationTest {
|
||||
|
||||
private ConnectionProvider connectionProvider = Connector.connectionProvider;
|
||||
private Database db = Database.from(connectionProvider);
|
||||
@ -57,8 +57,7 @@ public class AutomapInterfaceTest {
|
||||
@After
|
||||
public void close() {
|
||||
db.update("DROP TABLE EMPLOYEE")
|
||||
.dependsOn(create);
|
||||
.dependsOn(create);
|
||||
connectionProvider.close();
|
||||
}
|
||||
|
||||
}
|
@ -13,7 +13,7 @@ import com.github.davidmoten.rx.jdbc.Database;
|
||||
|
||||
import rx.Observable;
|
||||
|
||||
public class BasicQueryTypesTest {
|
||||
public class BasicQueryTypesIntegrationTest {
|
||||
|
||||
private ConnectionProvider connectionProvider = Connector.connectionProvider;
|
||||
private Database db = Database.from(connectionProvider);
|
@ -16,7 +16,7 @@ import com.github.davidmoten.rx.jdbc.Database;
|
||||
|
||||
import rx.Observable;
|
||||
|
||||
public class InsertBlobTest {
|
||||
public class InsertBlobIntegrationTest {
|
||||
|
||||
private ConnectionProvider connectionProvider = Connector.connectionProvider;
|
||||
private Database db = Database.from(connectionProvider);
|
@ -15,7 +15,7 @@ import com.github.davidmoten.rx.jdbc.Database;
|
||||
|
||||
import rx.Observable;
|
||||
|
||||
public class InsertClobTest {
|
||||
public class InsertClobIntegrationTest {
|
||||
|
||||
private ConnectionProvider connectionProvider = Connector.connectionProvider;
|
||||
private Database db = Database.from(connectionProvider);
|
@ -11,7 +11,7 @@ import com.github.davidmoten.rx.jdbc.Database;
|
||||
|
||||
import rx.Observable;
|
||||
|
||||
public class ReturnKeysTest {
|
||||
public class ReturnKeysIntegrationTest {
|
||||
|
||||
private Observable<Boolean> begin = null;
|
||||
private Observable<Integer> createStatement = null;
|
@ -10,7 +10,7 @@ import com.github.davidmoten.rx.jdbc.Database;
|
||||
|
||||
import rx.Observable;
|
||||
|
||||
public class TransactionTest {
|
||||
public class TransactionIntegrationTest {
|
||||
|
||||
private Observable<Integer> createStatement = null;
|
||||
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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 -> {
|
||||
|
@ -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>
|
||||
|
@ -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>
|
||||
|
@ -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();
|
||||
|
@ -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);
|
||||
|
@ -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();
|
||||
|
@ -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());
|
||||
}
|
||||
|
||||
|
@ -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;
|
||||
}
|
||||
|
@ -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
|
||||
|
||||
}
|
||||
|
@ -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();
|
||||
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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));
|
||||
}
|
||||
|
@ -8,4 +8,3 @@
|
||||
- [Spring YAML Configuration](http://www.baeldung.com/spring-yaml)
|
||||
- [Introduction to Spring’s StreamUtils](http://www.baeldung.com/spring-stream-utils)
|
||||
- [Using Spring @Value with Defaults](http://www.baeldung.com/spring-value-defaults)
|
||||
|
||||
|
@ -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;
|
||||
}
|
||||
|
@ -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;
|
||||
}
|
||||
}
|
@ -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);
|
||||
|
@ -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>
|
||||
|
||||
|
@ -1,7 +1,7 @@
|
||||
# jdbc.X
|
||||
jdbc.driverClassName=org.h2.Driver
|
||||
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
|
||||
jdbc.user=sa
|
||||
jdbc.eventGeneratedId=sa
|
||||
jdbc.pass=sa
|
||||
|
||||
# hibernate.X
|
||||
|
@ -1,7 +1,7 @@
|
||||
# jdbc.X
|
||||
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
|
||||
jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate5_01?createDatabaseIfNotExist=true
|
||||
jdbc.user=tutorialuser
|
||||
jdbc.eventGeneratedId=tutorialuser
|
||||
jdbc.pass=tutorialmy5ql
|
||||
|
||||
# hibernate.X
|
||||
|
@ -1,6 +1,7 @@
|
||||
package com.baeldung.hibernate.immutable;
|
||||
|
||||
import com.baeldung.hibernate.immutable.entities.Event;
|
||||
import com.baeldung.hibernate.immutable.entities.EventGeneratedId;
|
||||
import com.baeldung.hibernate.immutable.util.HibernateUtil;
|
||||
import com.google.common.collect.Sets;
|
||||
import org.hibernate.CacheMode;
|
||||
@ -10,6 +11,9 @@ import org.junit.rules.ExpectedException;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.core.IsEqual.equalTo;
|
||||
|
||||
public class HibernateImmutableIntegrationTest {
|
||||
|
||||
private static Session session;
|
||||
@ -22,6 +26,7 @@ public class HibernateImmutableIntegrationTest {
|
||||
session = HibernateUtil.getSessionFactory().getCurrentSession();
|
||||
session.beginTransaction();
|
||||
createEvent();
|
||||
createEventGenerated();
|
||||
session.setCacheMode(CacheMode.REFRESH);
|
||||
}
|
||||
|
||||
@ -35,9 +40,12 @@ public class HibernateImmutableIntegrationTest {
|
||||
HibernateUtil.getSessionFactory().close();
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void addEvent() {
|
||||
Event event = new Event();
|
||||
event.setId(2L);
|
||||
event.setTitle("Public Event");
|
||||
session.save(event);
|
||||
session.getTransaction().commit();
|
||||
@ -47,8 +55,12 @@ public class HibernateImmutableIntegrationTest {
|
||||
public void updateEvent() {
|
||||
Event event = (Event) session.createQuery("FROM Event WHERE title='New Event'").list().get(0);
|
||||
event.setTitle("Private Event");
|
||||
session.saveOrUpdate(event);
|
||||
session.getTransaction().commit();
|
||||
session.update(event);
|
||||
session.flush();
|
||||
session.refresh(event);
|
||||
|
||||
assertThat(event.getTitle(), equalTo("New Event"));
|
||||
assertThat(event.getId(), equalTo(5L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -80,10 +92,29 @@ public class HibernateImmutableIntegrationTest {
|
||||
session.getTransaction().commit();
|
||||
}
|
||||
|
||||
public static void createEvent() {
|
||||
Event event = new Event();
|
||||
event.setTitle("New Event");
|
||||
event.setGuestList(Sets.newHashSet("guest"));
|
||||
@Test
|
||||
public void updateEventGenerated() {
|
||||
EventGeneratedId eventGeneratedId = (EventGeneratedId) session.createQuery("FROM EventGeneratedId WHERE name LIKE '%John%'").list().get(0);
|
||||
eventGeneratedId.setName("Mike");
|
||||
session.update(eventGeneratedId);
|
||||
session.flush();
|
||||
session.refresh(eventGeneratedId);
|
||||
|
||||
assertThat(eventGeneratedId.getName(), equalTo("John"));
|
||||
assertThat(eventGeneratedId.getId(), equalTo(1L));
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
private static void createEvent() {
|
||||
Event event = new Event(5L, "New Event", Sets.newHashSet("guest"));
|
||||
session.save(event);
|
||||
}
|
||||
|
||||
private static void createEventGenerated() {
|
||||
EventGeneratedId eventGeneratedId = new EventGeneratedId("John", "Doe");
|
||||
eventGeneratedId.setId(4L);
|
||||
session.save(eventGeneratedId);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -21,7 +21,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = MainApplication.class)
|
||||
public class ExamplePostControllerRequestUnitTest {
|
||||
public class ExamplePostControllerRequestIntegrationTest {
|
||||
|
||||
MockMvc mockMvc;
|
||||
@Mock private ExampleService exampleService;
|
@ -23,7 +23,7 @@ import org.baeldung.config.MainApplication;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = MainApplication.class)
|
||||
public class ExamplePostControllerResponseUnitTest {
|
||||
public class ExamplePostControllerResponseIntegrationTest {
|
||||
|
||||
MockMvc mockMvc;
|
||||
@Mock private ExampleService exampleService;
|
@ -1,33 +0,0 @@
|
||||
package com.baeldung.web.log.test;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import com.baeldung.web.log.data.TaxiRide;
|
||||
|
||||
public class TestTaxiFareController {
|
||||
|
||||
private static final String URL = "http://localhost:" + 8082 + "/spring-rest/taxifare/";
|
||||
|
||||
@Test
|
||||
public void givenRequest_whenFetchTaxiFareRateCard_thanOK() {
|
||||
TestRestTemplate testRestTemplate = new TestRestTemplate();
|
||||
ResponseEntity<String> response = testRestTemplate.getForEntity(URL + "get/", String.class);
|
||||
|
||||
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTaxiRide_whenCalculatedFare_thanStatus200() {
|
||||
TestRestTemplate testRestTemplate = new TestRestTemplate();
|
||||
TaxiRide taxiRide = new TaxiRide(true, 10l);
|
||||
String fare = testRestTemplate.postForObject(URL + "calculate/", taxiRide, String.class);
|
||||
|
||||
assertThat(fare, equalTo("200"));
|
||||
}
|
||||
}
|
@ -8,3 +8,4 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com
|
||||
- [Two Login Pages with Spring Security](http://www.baeldung.com/spring-security-two-login-pages)
|
||||
- [Multiple Entry Points in Spring Security](http://www.baeldung.com/spring-security-multiple-entry-points)
|
||||
- [Multiple Authentication Providers in Spring Security](http://www.baeldung.com/spring-security-multiple-auth-providers)
|
||||
- [Granted Authority Versus Role in Spring Security](http://www.baeldung.com/spring-security-granted-authority-vs-role)
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user