Merge remote-tracking branch 'central/master'
This commit is contained in:
@@ -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()));
|
||||
}
|
||||
}
|
||||
@@ -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 );
|
||||
|
||||
}
|
||||
}
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
package com.baeldung.apachecayenne;
|
||||
|
||||
import com.baeldung.apachecayenne.persistent.Author;
|
||||
import org.apache.cayenne.ObjectContext;
|
||||
import org.apache.cayenne.QueryResponse;
|
||||
import org.apache.cayenne.configuration.server.ServerRuntime;
|
||||
import org.apache.cayenne.exp.Expression;
|
||||
import org.apache.cayenne.exp.ExpressionFactory;
|
||||
import org.apache.cayenne.query.*;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static junit.framework.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class CayenneAdvancedOperationTests {
|
||||
private static ObjectContext context = null;
|
||||
|
||||
@BeforeClass
|
||||
public static void setupTheCayenneContext() {
|
||||
ServerRuntime cayenneRuntime = ServerRuntime.builder()
|
||||
.addConfig("cayenne-project.xml")
|
||||
.build();
|
||||
context = cayenneRuntime.newContext();
|
||||
}
|
||||
|
||||
@Before
|
||||
public void saveThreeAuthors() {
|
||||
Author authorOne = context.newObject(Author.class);
|
||||
authorOne.setName("Paul Xavier");
|
||||
Author authorTwo = context.newObject(Author.class);
|
||||
authorTwo.setName("pAuL Smith");
|
||||
Author authorThree = context.newObject(Author.class);
|
||||
authorThree.setName("Vicky Sarra");
|
||||
context.commitChanges();
|
||||
}
|
||||
|
||||
@After
|
||||
public void deleteAllAuthors() {
|
||||
SQLTemplate deleteAuthors = new SQLTemplate(Author.class, "delete from author");
|
||||
context.performGenericQuery(deleteAuthors);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenFindAllSQLTmplt_thenWeGetThreeAuthors() {
|
||||
SQLTemplate select = new SQLTemplate(Author.class, "select * from Author");
|
||||
List<Author> authors = context.performQuery(select);
|
||||
|
||||
assertEquals(authors.size(), 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenFindByNameSQLTmplt_thenWeGetOneAuthor() {
|
||||
SQLTemplate select = new SQLTemplate(Author.class, "select * from Author where name = 'Vicky Sarra'");
|
||||
List<Author> authors = context.performQuery(select);
|
||||
Author author = authors.get(0);
|
||||
|
||||
assertEquals(authors.size(), 1);
|
||||
assertEquals(author.getName(), "Vicky Sarra");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenLikeSltQry_thenWeGetOneAuthor() {
|
||||
Expression qualifier = ExpressionFactory.likeExp(Author.NAME.getName(), "Paul%");
|
||||
SelectQuery query = new SelectQuery(Author.class, qualifier);
|
||||
List<Author> authorsTwo = context.performQuery(query);
|
||||
|
||||
assertEquals(authorsTwo.size(), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenCtnsIgnorCaseSltQry_thenWeGetTwoAuthors() {
|
||||
Expression qualifier = ExpressionFactory.containsIgnoreCaseExp(Author.NAME.getName(), "Paul");
|
||||
SelectQuery query = new SelectQuery(Author.class, qualifier);
|
||||
List<Author> authors = context.performQuery(query);
|
||||
|
||||
assertEquals(authors.size(), 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenCtnsIgnorCaseEndsWSltQry_thenWeGetTwoAuthors() {
|
||||
Expression qualifier = ExpressionFactory.containsIgnoreCaseExp(Author.NAME.getName(), "Paul")
|
||||
.andExp(ExpressionFactory.endsWithExp(Author.NAME.getName(), "h"));
|
||||
SelectQuery query = new SelectQuery(Author.class, qualifier);
|
||||
List<Author> authors = context.performQuery(query);
|
||||
|
||||
Author author = authors.get(0);
|
||||
|
||||
assertEquals(authors.size(), 1);
|
||||
assertEquals(author.getName(), "pAuL Smith");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenAscOrderingSltQry_thenWeGetOrderedAuthors() {
|
||||
SelectQuery query = new SelectQuery(Author.class);
|
||||
query.addOrdering(Author.NAME.asc());
|
||||
|
||||
List<Author> authors = query.select(context);
|
||||
Author firstAuthor = authors.get(0);
|
||||
|
||||
assertEquals(authors.size(), 3);
|
||||
assertEquals(firstAuthor.getName(), "Paul Xavier");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenDescOrderingSltQry_thenWeGetOrderedAuthors() {
|
||||
SelectQuery query = new SelectQuery(Author.class);
|
||||
query.addOrdering(Author.NAME.desc());
|
||||
|
||||
List<Author> authors = query.select(context);
|
||||
Author firstAuthor = authors.get(0);
|
||||
|
||||
assertEquals(authors.size(), 3);
|
||||
assertEquals(firstAuthor.getName(), "pAuL Smith");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_onContainsObjS_thenWeGetOneRecord() {
|
||||
List<Author> authors = ObjectSelect.query(Author.class)
|
||||
.where(Author.NAME.contains("Paul"))
|
||||
.select(context);
|
||||
|
||||
assertEquals(authors.size(), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenLikeObjS_thenWeGetTwoAuthors() {
|
||||
List<Author> authors = ObjectSelect.query(Author.class)
|
||||
.where(Author.NAME.likeIgnoreCase("Paul%"))
|
||||
.select(context);
|
||||
|
||||
assertEquals(authors.size(), 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoAuthor_whenEndsWithObjS_thenWeGetOrderedAuthors() {
|
||||
List<Author> authors = ObjectSelect.query(Author.class)
|
||||
.where(Author.NAME.endsWith("Sarra"))
|
||||
.select(context);
|
||||
Author firstAuthor = authors.get(0);
|
||||
|
||||
assertEquals(authors.size(), 1);
|
||||
assertEquals(firstAuthor.getName(), "Vicky Sarra");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoAuthor_whenInObjS_thenWeGetAuthors() {
|
||||
List<String> names = Arrays.asList("Paul Xavier", "pAuL Smith", "Vicky Sarra");
|
||||
List<Author> authors = ObjectSelect.query(Author.class)
|
||||
.where(Author.NAME.in(names))
|
||||
.select(context);
|
||||
|
||||
assertEquals(authors.size(), 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoAuthor_whenNinObjS_thenWeGetAuthors() {
|
||||
List<String> names = Arrays.asList("Paul Xavier", "pAuL Smith");
|
||||
List<Author> authors = ObjectSelect.query(Author.class)
|
||||
.where(Author.NAME.nin(names))
|
||||
.select(context);
|
||||
Author author = authors.get(0);
|
||||
|
||||
assertEquals(authors.size(), 1);
|
||||
assertEquals(author.getName(), "Vicky Sarra");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoAuthor_whenIsNotNullObjS_thenWeGetAuthors() {
|
||||
List<Author> authors = ObjectSelect.query(Author.class)
|
||||
.where(Author.NAME.isNotNull())
|
||||
.select(context);
|
||||
|
||||
assertEquals(authors.size(), 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenFindAllEJBQL_thenWeGetThreeAuthors() {
|
||||
EJBQLQuery query = new EJBQLQuery("select a FROM Author a");
|
||||
List<Author> authors = context.performQuery(query);
|
||||
|
||||
assertEquals(authors.size(), 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenFindByNameEJBQL_thenWeGetOneAuthor() {
|
||||
EJBQLQuery query = new EJBQLQuery("select a FROM Author a WHERE a.name = 'Vicky Sarra'");
|
||||
List<Author> authors = context.performQuery(query);
|
||||
Author author = authors.get(0);
|
||||
|
||||
assertEquals(authors.size(), 1);
|
||||
assertEquals(author.getName(), "Vicky Sarra");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenUpdadingByNameEJBQL_thenWeGetTheUpdatedAuthor() {
|
||||
EJBQLQuery query = new EJBQLQuery("UPDATE Author AS a SET a.name = 'Vicky Edison' WHERE a.name = 'Vicky Sarra'");
|
||||
QueryResponse queryResponse = context.performGenericQuery(query);
|
||||
|
||||
EJBQLQuery queryUpdatedAuthor = new EJBQLQuery("select a FROM Author a WHERE a.name = 'Vicky Edison'");
|
||||
List<Author> authors = context.performQuery(queryUpdatedAuthor);
|
||||
Author author = authors.get(0);
|
||||
|
||||
assertNotNull(author);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenSeletingNamesEJBQL_thenWeGetListWithSizeThree() {
|
||||
String [] args = {"Paul Xavier", "pAuL Smith", "Vicky Sarra"};
|
||||
List<String> names = Arrays.asList(args);
|
||||
EJBQLQuery query = new EJBQLQuery("select a.name FROM Author a");
|
||||
List<String> nameList = context.performQuery(query);
|
||||
|
||||
Collections.sort(names);
|
||||
Collections.sort(nameList);
|
||||
|
||||
assertEquals(names.size(), 3);
|
||||
assertEquals(nameList.size(), 3);
|
||||
assertEquals(names, nameList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenDeletingAllWithEJB_thenWeGetNoAuthor() {
|
||||
EJBQLQuery deleteQuery = new EJBQLQuery("delete FROM Author");
|
||||
EJBQLQuery findAllQuery = new EJBQLQuery("select a FROM Author a");
|
||||
|
||||
context.performQuery(deleteQuery);
|
||||
List<Author> objects = context.performQuery(findAllQuery);
|
||||
|
||||
assertEquals(objects.size(), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenInsertingSQLExec_thenWeGetNewAuthor() {
|
||||
int inserted = SQLExec
|
||||
.query("INSERT INTO Author (name) VALUES ('Baeldung')")
|
||||
.update(context);
|
||||
|
||||
assertEquals(inserted, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenUpdatingSQLExec_thenItsUpdated() {
|
||||
int updated = SQLExec
|
||||
.query("UPDATE Author SET name = 'Baeldung' WHERE name = 'Vicky Sarra'")
|
||||
.update(context);
|
||||
|
||||
assertEquals(updated, 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
/target
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringTest {
|
||||
|
||||
@Test
|
||||
public void whenCallCodePointAt_thenDecimalUnicodeReturned() {
|
||||
assertEquals(97, "abcd".codePointAt(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCallConcat_thenCorrect() {
|
||||
assertEquals("elephant", "elep".concat("hant"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetBytes_thenCorrect() {
|
||||
byte[] byteArray = "abcd".getBytes();
|
||||
byte[] expected = new byte[] { 97, 98, 99, 100 };
|
||||
assertArrayEquals(expected, byteArray);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
### Sample deeplearning4j Project
|
||||
This is a sample project for the [deeplearning4j](https://deeplearning4j.org) library.
|
||||
|
||||
### Relevant Articles:
|
||||
- [A Guide to deeplearning4j](http://www.baeldung.com/a-guide-to-deeplearning4j/)
|
||||
@@ -0,0 +1,33 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.deeplearning4j</groupId>
|
||||
<artifactId>deeplearning4j</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>deeplearning4j</name>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<dl4j.version>0.9.1</dl4j.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.nd4j</groupId>
|
||||
<artifactId>nd4j-native-platform</artifactId>
|
||||
<version>${dl4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.deeplearning4j</groupId>
|
||||
<artifactId>deeplearning4j-core</artifactId>
|
||||
<version>${dl4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.baeldung.deeplearning4j;
|
||||
|
||||
import org.datavec.api.records.reader.RecordReader;
|
||||
import org.datavec.api.records.reader.impl.csv.CSVRecordReader;
|
||||
import org.datavec.api.split.FileSplit;
|
||||
import org.datavec.api.util.ClassPathResource;
|
||||
import org.deeplearning4j.datasets.datavec.RecordReaderDataSetIterator;
|
||||
import org.deeplearning4j.eval.Evaluation;
|
||||
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
|
||||
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
|
||||
import org.deeplearning4j.nn.conf.layers.DenseLayer;
|
||||
import org.deeplearning4j.nn.conf.layers.OutputLayer;
|
||||
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
|
||||
import org.deeplearning4j.nn.weights.WeightInit;
|
||||
import org.nd4j.linalg.activations.Activation;
|
||||
import org.nd4j.linalg.api.ndarray.INDArray;
|
||||
import org.nd4j.linalg.dataset.DataSet;
|
||||
import org.nd4j.linalg.dataset.SplitTestAndTrain;
|
||||
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
|
||||
import org.nd4j.linalg.dataset.api.preprocessor.DataNormalization;
|
||||
import org.nd4j.linalg.dataset.api.preprocessor.NormalizerStandardize;
|
||||
import org.nd4j.linalg.lossfunctions.LossFunctions;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class IrisClassifier {
|
||||
|
||||
private static final int CLASSES_COUNT = 3;
|
||||
private static final int FEATURES_COUNT = 4;
|
||||
|
||||
public static void main(String[] args) throws IOException, InterruptedException {
|
||||
|
||||
DataSet allData;
|
||||
try (RecordReader recordReader = new CSVRecordReader(0, ',')) {
|
||||
recordReader.initialize(new FileSplit(new ClassPathResource("iris.txt").getFile()));
|
||||
|
||||
DataSetIterator iterator = new RecordReaderDataSetIterator(recordReader, 150, FEATURES_COUNT, CLASSES_COUNT);
|
||||
allData = iterator.next();
|
||||
}
|
||||
|
||||
allData.shuffle(42);
|
||||
|
||||
DataNormalization normalizer = new NormalizerStandardize();
|
||||
normalizer.fit(allData);
|
||||
normalizer.transform(allData);
|
||||
|
||||
SplitTestAndTrain testAndTrain = allData.splitTestAndTrain(0.65);
|
||||
DataSet trainingData = testAndTrain.getTrain();
|
||||
DataSet testData = testAndTrain.getTest();
|
||||
|
||||
MultiLayerConfiguration configuration = new NeuralNetConfiguration.Builder()
|
||||
.iterations(1000)
|
||||
.activation(Activation.TANH)
|
||||
.weightInit(WeightInit.XAVIER)
|
||||
.learningRate(0.1)
|
||||
.regularization(true).l2(0.0001)
|
||||
.list()
|
||||
.layer(0, new DenseLayer.Builder().nIn(FEATURES_COUNT).nOut(3)
|
||||
.build())
|
||||
.layer(1, new DenseLayer.Builder().nIn(3).nOut(3)
|
||||
.build())
|
||||
.layer(2, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
|
||||
.activation(Activation.SOFTMAX)
|
||||
.nIn(3).nOut(CLASSES_COUNT).build())
|
||||
.backprop(true).pretrain(false)
|
||||
.build();
|
||||
|
||||
MultiLayerNetwork model = new MultiLayerNetwork(configuration);
|
||||
model.init();
|
||||
model.fit(trainingData);
|
||||
|
||||
INDArray output = model.output(testData.getFeatureMatrix());
|
||||
|
||||
Evaluation eval = new Evaluation(CLASSES_COUNT);
|
||||
eval.eval(testData.getLabels(), output);
|
||||
System.out.println(eval.stats());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
5.1,3.5,1.4,0.2,0
|
||||
4.9,3.0,1.4,0.2,0
|
||||
4.7,3.2,1.3,0.2,0
|
||||
4.6,3.1,1.5,0.2,0
|
||||
5.0,3.6,1.4,0.2,0
|
||||
5.4,3.9,1.7,0.4,0
|
||||
4.6,3.4,1.4,0.3,0
|
||||
5.0,3.4,1.5,0.2,0
|
||||
4.4,2.9,1.4,0.2,0
|
||||
4.9,3.1,1.5,0.1,0
|
||||
5.4,3.7,1.5,0.2,0
|
||||
4.8,3.4,1.6,0.2,0
|
||||
4.8,3.0,1.4,0.1,0
|
||||
4.3,3.0,1.1,0.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3.0,5.2,2.0,2
|
||||
6.2,3.4,5.4,2.3,2
|
||||
5.9,3.0,5.1,1.8,2
|
||||
@@ -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>
|
||||
-17
@@ -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()));
|
||||
}
|
||||
}
|
||||
-13
@@ -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);
|
||||
}
|
||||
}
|
||||
-14
@@ -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;
|
||||
}
|
||||
}
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.beanvalidation.service;
|
||||
|
||||
public interface EntityService {
|
||||
|
||||
public String toString();
|
||||
|
||||
public void processEntity();
|
||||
}
|
||||
-45
@@ -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 + "]";
|
||||
}
|
||||
}
|
||||
-134
@@ -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("[email protected]");
|
||||
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("[email protected]");
|
||||
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("[email protected]");
|
||||
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("[email protected]");
|
||||
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("[email protected]");
|
||||
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("[email protected]");
|
||||
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("[email protected]");
|
||||
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());
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -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>
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user