fix conflict and merger with latest PR

This commit is contained in:
Seun Matt 2017-10-15 13:54:38 +01:00
commit 760ff02f74
252 changed files with 9966 additions and 882 deletions

View File

@ -23,4 +23,4 @@ Any IDE can be used to work with the projects, but if you're using Eclipse, cons
CI - Jenkins
================================
This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/github%20projects%20Jobs/job/tutorials/)**
This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials-unit/)**

View File

@ -3,9 +3,11 @@
- [Dijkstra Algorithm in Java](http://www.baeldung.com/java-dijkstra)
- [Introduction to Cobertura](http://www.baeldung.com/cobertura)
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
- [Validating Input With Finite Automata in Java](http://www.baeldung.com/finite-automata-java)
- [Validating Input With Finite Automata in Java](http://www.baeldung.com/java-finite-automata)
- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics)
- [Check If a Number Is Prime in Java](http://www.baeldung.com/java-prime-numbers)
- [Example of Hill Climbing Algorithm](http://www.baeldung.com/java-hill-climbing-algorithm)
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](http://www.baeldung.com/java-monte-carlo-tree-search)
- [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms)
- [Test a Linked List for Cyclicity](http://www.baeldung.com/java-linked-list-cyclicity)
- [Binary Search Algorithm in Java](http://www.baeldung.com/java-binary-search)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

59
apache-cayenne/pom.xml Normal file
View File

@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-cayenne</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>apache-cayenne</name>
<description>Introduction to Apache Cayenne</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<mysql.connector.version>5.1.44</mysql.connector.version>
<cayenne.version>4.0.M5</cayenne.version>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.cayenne</groupId>
<artifactId>cayenne-server</artifactId>
<version>${cayenne.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.cayenne.plugins</groupId>
<artifactId>cayenne-modeler-maven-plugin</artifactId>
<version>${cayenne.version}</version>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,9 @@
package com.baeldung.apachecayenne.persistent;
import com.baeldung.apachecayenne.persistent.auto._Article;
public class Article extends _Article {
private static final long serialVersionUID = 1L;
}

View File

@ -0,0 +1,9 @@
package com.baeldung.apachecayenne.persistent;
import com.baeldung.apachecayenne.persistent.auto._Author;
public class Author extends _Author {
private static final long serialVersionUID = 1L;
}

View File

@ -0,0 +1,47 @@
package com.baeldung.apachecayenne.persistent.auto;
import org.apache.cayenne.CayenneDataObject;
import org.apache.cayenne.exp.Property;
import com.baeldung.apachecayenne.persistent.Author;
/**
* Class _Article was generated by Cayenne.
* It is probably a good idea to avoid changing this class manually,
* since it may be overwritten next time code is regenerated.
* If you need to make any customizations, please use subclass.
*/
public abstract class _Article extends CayenneDataObject {
private static final long serialVersionUID = 1L;
public static final String ID_PK_COLUMN = "id";
public static final Property<String> CONTENT = Property.create("content", String.class);
public static final Property<String> TITLE = Property.create("title", String.class);
public static final Property<Author> AUTHOR = Property.create("author", Author.class);
public void setContent(String content) {
writeProperty("content", content);
}
public String getContent() {
return (String)readProperty("content");
}
public void setTitle(String title) {
writeProperty("title", title);
}
public String getTitle() {
return (String)readProperty("title");
}
public void setAuthor(Author author) {
setToOneTarget("author", author, true);
}
public Author getAuthor() {
return (Author)readProperty("author");
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.apachecayenne.persistent.auto;
import java.util.List;
import org.apache.cayenne.CayenneDataObject;
import org.apache.cayenne.exp.Property;
import com.baeldung.apachecayenne.persistent.Article;
/**
* Class _Author was generated by Cayenne.
* It is probably a good idea to avoid changing this class manually,
* since it may be overwritten next time code is regenerated.
* If you need to make any customizations, please use subclass.
*/
public abstract class _Author extends CayenneDataObject {
private static final long serialVersionUID = 1L;
public static final String ID_PK_COLUMN = "id";
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 setName(String name) {
writeProperty("name", name);
}
public String getName() {
return (String)readProperty("name");
}
public void addToArticles(Article obj) {
addToManyTarget("articles", obj, true);
}
public void removeFromArticles(Article obj) {
removeToManyTarget("articles", obj, true);
}
@SuppressWarnings("unchecked")
public List<Article> getArticles() {
return (List<Article>)readProperty("articles");
}
}

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<domain project-version="9">
<map name="datamap"/>
<node name="datanode"
factory="org.apache.cayenne.configuration.server.XMLPoolingDataSourceFactory"
schema-update-strategy="org.apache.cayenne.access.dbsync.CreateIfNoSchemaStrategy"
>
<map-ref name="datamap"/>
<data-source>
<driver value="com.mysql.jdbc.Driver"/>
<url value="jdbc:mysql://localhost:3306/intro_cayenne"/>
<connectionPool min="1" max="1"/>
<login userName="root" password="root"/>
</data-source>
</node>
</domain>

View File

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<data-map xmlns="http://cayenne.apache.org/schema/9/modelMap"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://cayenne.apache.org/schema/9/modelMap http://cayenne.apache.org/schema/9/modelMap.xsd"
project-version="9">
<property name="defaultPackage" value="com.baeldung.apachecayenne.persistent"/>
<db-entity name="article" catalog="intro_cayenne">
<db-attribute name="author_id" type="INTEGER" isMandatory="true" length="10"/>
<db-attribute name="content" type="VARCHAR" isMandatory="true" length="254"/>
<db-attribute name="id" type="INTEGER" isPrimaryKey="true" isGenerated="true" isMandatory="true" length="10"/>
<db-attribute name="title" type="VARCHAR" isMandatory="true" length="254"/>
</db-entity>
<db-entity name="author" catalog="intro_cayenne">
<db-attribute name="id" type="INTEGER" isPrimaryKey="true" isGenerated="true" isMandatory="true" length="10"/>
<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="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"/>
</db-relationship>
<db-relationship name="articles" source="author" target="article" toMany="true">
<db-attribute-pair source="id" target="author_id"/>
</db-relationship>
<obj-relationship name="author" source="Article" target="Author" deleteRule="Nullify" db-relationship-path="author"/>
<obj-relationship name="articles" source="Author" target="Article" deleteRule="Deny" db-relationship-path="articles"/>
</data-map>

View File

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

View File

@ -0,0 +1,131 @@
package com.baeldung.apachecayenne;
import com.baeldung.apachecayenne.persistent.Article;
import com.baeldung.apachecayenne.persistent.Author;
import org.apache.cayenne.ObjectContext;
import org.apache.cayenne.configuration.server.ServerRuntime;
import org.apache.cayenne.query.ObjectSelect;
import org.apache.cayenne.query.SQLTemplate;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class CayenneOperationTests {
private static ObjectContext context = null;
@BeforeClass
public static void setupTheCayenneContext() {
ServerRuntime cayenneRuntime = ServerRuntime.builder()
.addConfig("cayenne-project.xml")
.build();
context = cayenneRuntime.newContext();
}
@After
public void deleteAllRecords() {
SQLTemplate deleteArticles = new SQLTemplate(Article.class, "delete from article");
SQLTemplate deleteAuthors = new SQLTemplate(Author.class, "delete from author");
context.performGenericQuery(deleteArticles);
context.performGenericQuery(deleteAuthors);
}
@Test
public void givenAuthor_whenInsert_thenWeGetOneRecordInTheDatabase() {
Author author = context.newObject(Author.class);
author.setName("Paul");
context.commitChanges();
long records = ObjectSelect.dataRowQuery(Author.class).selectCount(context);
assertEquals(1, records);
}
@Test
public void givenAuthor_whenInsert_andQueryByFirstName_thenWeGetTheAuthor() {
Author author = context.newObject(Author.class);
author.setName("Paul");
context.commitChanges();
Author expectedAuthor = ObjectSelect.query(Author.class)
.where(Author.NAME.eq("Paul"))
.selectOne(context);
assertEquals("Paul", expectedAuthor.getName());
}
@Test
public void givenTwoAuthor_whenInsert_andQueryAll_thenWeGetTwoAuthors() {
Author firstAuthor = context.newObject(Author.class);
firstAuthor.setName("Paul");
Author secondAuthor = context.newObject(Author.class);
secondAuthor.setName("Ludovic");
context.commitChanges();
List<Author> authors = ObjectSelect.query(Author.class).select(context);
assertEquals(2, authors.size());
}
@Test
public void givenAuthor_whenUpdating_thenWeGetAnUpatedeAuthor() {
Author author = context.newObject(Author.class);
author.setName("Paul");
context.commitChanges();
Author expectedAuthor = ObjectSelect.query(Author.class)
.where(Author.NAME.eq("Paul"))
.selectOne(context);
expectedAuthor.setName("Garcia");
context.commitChanges();
assertEquals(author.getName(), expectedAuthor.getName());
}
@Test
public void givenAuthor_whenDeleting_thenWeLostHisDetails() {
Author author = context.newObject(Author.class);
author.setName("Paul");
context.commitChanges();
Author savedAuthor = ObjectSelect.query(Author.class)
.where(Author.NAME.eq("Paul")).selectOne(context);
if(savedAuthor != null) {
context.deleteObjects(author);
context.commitChanges();
}
Author expectedAuthor = ObjectSelect.query(Author.class)
.where(Author.NAME.eq("Paul")).selectOne(context);
assertNull(expectedAuthor);
}
@Test
public void givenAuthor_whenAttachingToArticle_thenTheRelationIsMade() {
Author author = context.newObject(Author.class);
author.setName("Paul");
Article article = context.newObject(Article.class);
article.setTitle("My post title");
article.setContent("The content");
article.setAuthor(author);
context.commitChanges();
Author expectedAuthor = ObjectSelect.query(Author.class)
.where(Author.NAME.eq("Paul"))
.selectOne(context);
Article expectedArticle = (expectedAuthor.getArticles()).get(0);
assertEquals(article.getTitle(), expectedArticle.getTitle());
}
}

51
asm/pom.xml Normal file
View File

@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.examples</groupId>
<artifactId>asm</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>5.2</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-util</artifactId>
<version>5.2</version>
</dependency>
</dependencies>
<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>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifestEntries>
<Premain-Class>
com.baeldung.examples.asm.instrumentation.Premain
</Premain-Class>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<argLine>-javaagent:"C:\asm-1.0.jar"</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,160 @@
package com.baeldung.examples.asm;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ASM4;
import static org.objectweb.asm.Opcodes.V1_5;
import org.objectweb.asm.Type;
import org.objectweb.asm.util.TraceClassVisitor;
/**
*
* @author baeldung
* @param <String>
*/
public class CustomClassWriter {
ClassReader reader;
ClassWriter writer;
AddFieldAdapter addFieldAdapter;
AddInterfaceAdapter addInterfaceAdapter;
PublicizeMethodAdapter pubMethAdapter;
final static String CLASSNAME = "java.lang.Integer";
final static String CLONEABLE = "java/lang/Cloneable";
public CustomClassWriter() {
try {
reader = new ClassReader(CLASSNAME);
writer = new ClassWriter(reader, 0);
} catch (IOException ex) {
Logger.getLogger(CustomClassWriter.class.getName()).log(Level.SEVERE, null, ex);
}
}
public CustomClassWriter(byte[] contents) {
reader = new ClassReader(contents);
writer = new ClassWriter(reader, 0);
}
public static void main(String[] args) {
CustomClassWriter ccw = new CustomClassWriter();
ccw.publicizeMethod();
}
public byte[] addField() {
addFieldAdapter = new AddFieldAdapter("aNewBooleanField", org.objectweb.asm.Opcodes.ACC_PUBLIC, writer);
reader.accept(addFieldAdapter, 0);
return writer.toByteArray();
}
public byte[] publicizeMethod() {
pubMethAdapter = new PublicizeMethodAdapter(writer);
reader.accept(pubMethAdapter, 0);
return writer.toByteArray();
}
public byte[] addInterface() {
addInterfaceAdapter = new AddInterfaceAdapter(writer);
reader.accept(addInterfaceAdapter, 0);
return writer.toByteArray();
}
public class AddInterfaceAdapter extends ClassVisitor {
public AddInterfaceAdapter(ClassVisitor cv) {
super(ASM4, cv);
}
@Override
public void visit(int version, int access, String name,
String signature, String superName, String[] interfaces) {
String[] holding = new String[interfaces.length + 1];
holding[holding.length - 1] = CLONEABLE;
System.arraycopy(interfaces, 0, holding, 0, interfaces.length);
cv.visit(V1_5, access, name, signature, superName, holding);
}
}
public class PublicizeMethodAdapter extends ClassVisitor {
final Logger logger = Logger.getLogger("PublicizeMethodAdapter");
TraceClassVisitor tracer;
PrintWriter pw = new PrintWriter(System.out);
public PublicizeMethodAdapter(ClassVisitor cv) {
super(ASM4, cv);
this.cv = cv;
tracer = new TraceClassVisitor(cv, pw);
}
@Override
public MethodVisitor visitMethod(int access,
String name,
String desc,
String signature,
String[] exceptions) {
if (name.equals("toUnsignedString0")) {
logger.info("Visiting unsigned method");
return tracer.visitMethod(ACC_PUBLIC + ACC_STATIC, name, desc, signature, exceptions);
}
return tracer.visitMethod(access, name, desc, signature, exceptions);
}
public void visitEnd() {
tracer.visitEnd();
System.out.println(tracer.p.getText());
}
}
public class AddFieldAdapter extends ClassVisitor {
String fieldName;
int access;
boolean isFieldPresent;
public AddFieldAdapter(String fieldName, int access, ClassVisitor cv) {
super(ASM4, cv);
this.cv = cv;
this.access = access;
this.fieldName = fieldName;
}
@Override
public FieldVisitor visitField(int access, String name, String desc,
String signature, Object value) {
if (name.equals(fieldName)) {
isFieldPresent = true;
}
return cv.visitField(access, name, desc, signature, value);
}
@Override
public void visitEnd() {
if (!isFieldPresent) {
FieldVisitor fv = cv.visitField(access, fieldName, Type.BOOLEAN_TYPE.toString(), null, null);
if (fv != null) {
fv.visitEnd();
}
}
cv.visitEnd();
}
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.examples.asm.instrumentation;
import com.baeldung.examples.asm.CustomClassWriter;
import java.lang.instrument.Instrumentation;
public class Premain {
public static void premain(String agentArgs, Instrumentation inst) {
inst.addTransformer((l, name, c, d, b) -> {
if (name.equals("java/lang/Integer")) {
CustomClassWriter cr = new CustomClassWriter(b);
return cr.addField();
}
return b;
});
}
}

1
atomix/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

46
atomix/pom.xml Normal file
View File

@ -0,0 +1,46 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.atomix.io</groupId>
<artifactId>atomix</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>io.atomix</groupId>
<artifactId>atomix-all</artifactId>
<version>1.0.0-rc9</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

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

View File

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

View File

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

View File

@ -28,5 +28,5 @@
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode)
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)
- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)
- [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception)

View File

@ -17,3 +17,4 @@
- [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams)
- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)

View File

@ -106,3 +106,12 @@
- [Converting a List to String in Java](http://www.baeldung.com/java-list-to-string)
- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string)
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
- [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator)
- [Singletons in Java](http://www.baeldung.com/java-singleton)
- [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws)
- [OutOfMemoryError: GC Overhead Limit Exceeded](http://www.baeldung.com/java-gc-overhead-limit-exceeded)
- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices)
- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer)
- [Number of Digits in an Integer in Java](http://www.baeldung.com/java-number-of-digits-in-int)
- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns)

View File

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

View File

@ -0,0 +1,218 @@
package com.baeldung.string;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.nio.charset.StandardCharsets;
import java.util.IllegalFormatException;
import java.util.regex.PatternSyntaxException;
import org.junit.Test;
public class StringTest {
@Test
public void whenCallCodePointAt_thenDecimalUnicodeReturned() {
assertEquals(97, "abcd".codePointAt(0));
}
@Test(expected = StringIndexOutOfBoundsException.class)
public void whenPassNonExistingIndex_thenExceptionThrown() {
int a = "abcd".codePointAt(4);
}
@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);
}
@Test
public void whenGetBytesUsingASCII_thenCorrect() {
byte[] byteArray = "efgh".getBytes(StandardCharsets.US_ASCII);
byte[] expected = new byte[] { 101, 102, 103, 104 };
assertArrayEquals(expected, byteArray);
}
@Test
public void whenCreateStringUsingByteArray_thenCorrect() {
byte[] array = new byte[] { 97, 98, 99, 100 };
String s = new String(array);
assertEquals("abcd", s);
}
@Test
public void whenCallCharAt_thenCorrect() {
assertEquals('P', "Paul".charAt(0));
}
@Test(expected = IndexOutOfBoundsException.class)
public void whenCharAtOnNonExistingIndex_thenIndexOutOfBoundsExceptionThrown() {
char character = "Paul".charAt(4);
}
@Test
public void whenCallCodePointCount_thenCorrect() {
assertEquals(2, "abcd".codePointCount(0, 2));
}
@Test(expected = IndexOutOfBoundsException.class)
public void whenSecondIndexEqualToLengthOfString_thenIndexOutOfBoundsExceptionThrown() {
char character = "Paul".charAt(4);
}
@Test
public void whenCallContains_thenCorrect() {
String s = "abcd";
assertTrue(s.contains("abc"));
assertFalse(s.contains("cde"));
}
@Test
public void whenCallCopyValueOf_thenStringConstructed() {
char[] array = new char[] { 'a', 'b', 'c', 'd' };
assertEquals("abcd", String.copyValueOf(array));
}
@Test
public void whenCallEndsWith_thenCorrect() {
String s1 = "test";
assertTrue(s1.endsWith("t"));
}
@Test
public void whenFormat_thenCorrect() {
String value = "Baeldung";
String formatted = String.format("Welcome to %s!", value);
assertEquals("Welcome to Baeldung!", formatted);
}
@Test(expected = IllegalFormatException.class)
public void whenInvalidFormatSyntax_thenIllegalFormatExceptionThrown() {
String value = "Baeldung";
String formatted = String.format("Welcome to %x!", value);
}
@Test
public void whenCallIndexOf_thenCorrect() {
assertEquals(1, "foo".indexOf("o"));
}
@Test
public void whenCallIsEmpty_thenCorrect() {
String s1 = "";
assertTrue(s1.isEmpty());
}
@Test
public void whenCallLastIndexOf_thenCorrect() {
assertEquals(2, "foo".lastIndexOf("o"));
}
@Test
public void whenCallRegionMatches_thenCorrect() {
assertTrue("welcome to baeldung".regionMatches(false, 11, "baeldung", 0, 8));
}
@Test
public void whenCallStartsWith_thenCorrect() {
assertTrue("foo".startsWith("f"));
}
@Test
public void whenTrim_thenCorrect() {
assertEquals("foo", " foo ".trim());
}
@Test
public void whenSplit_thenCorrect() {
String s = "Welcome to Baeldung";
String[] array = new String[] { "Welcome", "to", "Baeldung" };
assertArrayEquals(array, s.split(" "));
}
@Test(expected = PatternSyntaxException.class)
public void whenPassInvalidParameterToSplit_thenPatternSyntaxExceptionThrown() {
String s = "Welcome*to Baeldung";
String[] result = s.split("*");
}
@Test
public void whenCallSubSequence_thenCorrect() {
String s = "Welcome to Baeldung";
assertEquals("Welcome", s.subSequence(0, 7));
}
@Test
public void whenCallSubstring_thenCorrect() {
String s = "Welcome to Baeldung";
assertEquals("Welcome", s.substring(0, 7));
}
@Test(expected = IndexOutOfBoundsException.class)
public void whenSecondIndexEqualToLengthOfString_thenCorrect() {
String s = "Welcome to Baeldung";
String sub = s.substring(0, 20);
}
@Test
public void whenConvertToUpperCase_thenCorrect() {
String s = "Welcome to Baeldung!";
assertEquals("WELCOME TO BAELDUNG!", s.toUpperCase());
}
@Test
public void whenConvertToLowerCase_thenCorrect() {
String s = "WELCOME to BAELDUNG!";
assertEquals("welcome to baeldung!", s.toLowerCase());
}
@Test
public void whenCallReplace_thenCorrect() {
String s = "I learn Spanish";
assertEquals("I learn French", s.replaceAll("Spanish", "French"));
}
@Test
public void whenIntern_thenCorrect() {
String s1 = "abc";
String s2 = new String("abc");
String s3 = new String("foo");
String s4 = s1.intern();
String s5 = s2.intern();
assertFalse(s3 == s4);
assertTrue(s1 == s5);
}
@Test
public void whenCallValueOf_thenCorrect() {
long l = 200L;
assertEquals("200", String.valueOf(l));
}
}

View File

@ -3,8 +3,9 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>kotlin</artifactId>
<artifactId>core-kotlin</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
@ -20,6 +21,24 @@
</repositories>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit4.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
@ -116,16 +135,51 @@
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.19.1</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>junit5</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<includes>
<include>**/*Test5.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<kotlin-maven-plugin.version>1.1.2</kotlin-maven-plugin.version>
<kotlin-test-junit.version>1.1.2</kotlin-test-junit.version>
<kotlin-stdlib.version>1.1.2</kotlin-stdlib.version>
<kotlin-reflect.version>1.1.2</kotlin-reflect.version>
<kotlinx.version>0.15</kotlinx.version>
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
<junit.jupiter.version>5.0.0</junit.jupiter.version>
<junit.platform.version>1.0.0</junit.platform.version>
<junit.vintage.version>4.12.0</junit.vintage.version>
<junit4.version>4.12</junit4.version>
</properties>
</project>
</project>

View File

@ -0,0 +1,17 @@
package com.baeldung.kotlin.junit5
class Calculator {
fun add(a: Int, b: Int) = a + b
fun divide(a: Int, b: Int) = if (b == 0) {
throw DivideByZeroException(a)
} else {
a / b
}
fun square(a: Int) = a * a
fun squareRoot(a: Int) = Math.sqrt(a.toDouble())
fun log(base: Int, value: Int) = Math.log(value.toDouble()) / Math.log(base.toDouble())
}

View File

@ -0,0 +1,82 @@
package com.baeldung.kotlin.junit5
import org.junit.jupiter.api.*
import org.junit.jupiter.api.function.Executable
class CalculatorTest5 {
private val calculator = Calculator()
@Test
fun testAddition() {
Assertions.assertEquals(4, calculator.add(1, 3))
}
@Test
fun testDivideByZero() {
val exception = Assertions.assertThrows(DivideByZeroException::class.java) {
calculator.divide(5, 0)
}
Assertions.assertEquals(5, exception.numerator)
}
@Test
fun testSquares() {
Assertions.assertAll(
Executable { Assertions.assertEquals(1, calculator.square(1)) },
Executable { Assertions.assertEquals(4, calculator.square(2)) },
Executable { Assertions.assertEquals(9, calculator.square(3)) }
)
}
@TestFactory
fun testSquaresFactory() = listOf(
DynamicTest.dynamicTest("1 squared") { Assertions.assertEquals(1,calculator.square(1))},
DynamicTest.dynamicTest("2 squared") { Assertions.assertEquals(4,calculator.square(2))},
DynamicTest.dynamicTest("3 squared") { Assertions.assertEquals(9,calculator.square(3))}
)
@TestFactory
fun testSquaresFactory2() = listOf(
1 to 1,
2 to 4,
3 to 9,
4 to 16,
5 to 25)
.map { (input, expected) ->
DynamicTest.dynamicTest("$input squared") {
Assertions.assertEquals(expected, calculator.square(input))
}
}
private val squaresTestData = listOf(
1 to 1,
2 to 4,
3 to 9,
4 to 16,
5 to 25)
@TestFactory
fun testSquaresFactory3() = squaresTestData
.map { (input, expected) ->
DynamicTest.dynamicTest("$input squared") {
Assertions.assertEquals(expected, calculator.square(input))
}
}
@TestFactory
fun testSquareRootsFactory3() = squaresTestData
.map { (expected, input) ->
DynamicTest.dynamicTest("Square root of $input") {
Assertions.assertEquals(expected.toDouble(), calculator.squareRoot(input))
}
}
@Tags(
Tag("slow"),
Tag("logarithms")
)
@Test
fun testLogarithms() {
Assertions.assertEquals(3.0, calculator.log(2, 8))
}
}

View File

@ -0,0 +1,3 @@
package com.baeldung.kotlin.junit5
class DivideByZeroException(val numerator: Int) : Exception()

View File

@ -0,0 +1,21 @@
package com.baeldung.kotlin.junit5
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
class SimpleTest5 {
@Test
fun testEmpty() {
val list = listOf<String>()
Assertions.assertTrue(list::isEmpty)
}
@Test
@Disabled
fun testMessage() {
Assertions.assertEquals(3, 4) {
"Three does not equal four"
}
}
}

5
deeplearning4j/README.md Normal file
View File

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

33
deeplearning4j/pom.xml Normal file
View File

@ -0,0 +1,33 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.deeplearning4j</groupId>
<artifactId>deeplearning4j</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>deeplearning4j</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<dl4j.version>0.9.1</dl4j.version>
</properties>
<dependencies>
<dependency>
<groupId>org.nd4j</groupId>
<artifactId>nd4j-native-platform</artifactId>
<version>${dl4j.version}</version>
</dependency>
<dependency>
<groupId>org.deeplearning4j</groupId>
<artifactId>deeplearning4j-core</artifactId>
<version>${dl4j.version}</version>
</dependency>
</dependencies>
</project>

View File

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

View File

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

View File

@ -2,3 +2,4 @@
- [Guide to EJB Set-up](http://www.baeldung.com/ejb-intro)
- [Java EE Session Beans](http://www.baeldung.com/ejb-session-beans)
- [Introduction to EJB JNDI Lookup on WildFly Application Server](http://www.baeldung.com/wildfly-ejb-jndi)

View File

@ -1,4 +1,4 @@
## EthereumJ
### Relevant Articles:
- [Introduction to EthereumJ](http://www.baeldung.com/intro-to-ethereumj)
- [Introduction to EthereumJ](http://www.baeldung.com/ethereumj)

3
geotools/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant Articles
[Introduction to GeoTools](http://www.baeldung.com/geo-tools)

View File

@ -0,0 +1,3 @@
Manifest-Version: 1.0
Class-Path:

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

View File

@ -0,0 +1,9 @@
package com.stackify;
import org.glassfish.jersey.server.ResourceConfig;
public class ApplicationInitializer extends ResourceConfig {
public ApplicationInitializer() {
packages("com.stackify.services");
}
}

View File

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

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

View File

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

View File

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

View File

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

View File

@ -1,42 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.beanvalidation</groupId>
<artifactId>beanvalidation</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>beanvalidation</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.2.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
</dependencies>
</project>

View File

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

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