Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA 2017-09-30 12:51:56 +02:00
commit 9a70874e6d
92 changed files with 5663 additions and 701 deletions

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

View File

@ -106,3 +106,4 @@
- [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)

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -550,16 +550,46 @@
<artifactId>functionaljava</artifactId>
<version>4.7</version>
</dependency>
<dependency>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava-java8</artifactId>
<version>4.7</version>
</dependency>
<dependency>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava-quickcheck</artifactId>
<version>4.7</version>
</dependency>
<dependency>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava-java-core</artifactId>
<version>4.7</version>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
<version>${cache.version}</version>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast</artifactId>
<version>${hazelcast.version}</version>
</dependency>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast</artifactId>
<version>${hazelcast.version}</version>
</dependency>
<dependency>
<groupId>com.atlassian.jira</groupId>
<artifactId>jira-rest-java-client-core</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.atlassian.fugue</groupId>
<artifactId>fugue</artifactId>
<version>3.0.0-m007</version>
</dependency>
<dependency>
<groupId>org.jgrapht</groupId>
<artifactId>jgrapht-core</artifactId>
<version>1.0.1</version>
</dependency>
</dependencies>
<repositories>
<repository>
@ -575,6 +605,10 @@
<name>bintray</name>
<url>http://dl.bintray.com/cuba-platform/main</url>
</repository>
<repository>
<id>atlassian-public</id>
<url>https://packages.atlassian.com/maven/repository/public</url>
</repository>
</repositories>
<properties>
<multiverse.version>0.7.0</multiverse.version>
@ -620,6 +654,7 @@
<eclipse-collections.version>8.2.0</eclipse-collections.version>
<streamex.version>0.6.5</streamex.version>
<vavr.version>0.9.0</vavr.version>
<geotools.version>15.2</geotools.version>
<joda-time.version>2.9.9</joda-time.version>
<hirondelle-date4j.version>1.5.1</hirondelle-date4j.version>
<retrofit.version>2.3.0</retrofit.version>
@ -630,4 +665,4 @@
<cache.version>1.0.0</cache.version>
<hazelcast.version>3.8.4</hazelcast.version>
</properties>
</project>
</project>

View File

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

View File

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

View File

@ -41,4 +41,4 @@ public class CacheLoaderTest {
assertEquals("fromCache" + i, value);
}
}
}
}

View File

@ -38,4 +38,4 @@ public class EntryProcessorTest {
this.cache.invoke("key", new SimpleEntryProcessor());
assertEquals("value - modified", cache.get("key"));
}
}
}

View File

@ -53,4 +53,4 @@ public class EventListenerTest {
assertEquals(true, this.listener.getUpdated());
}
}
}

View File

@ -24,4 +24,4 @@ public class JCacheTest {
assertEquals("value2", cache.get("key2"));
cacheManager.close();
}
}
}

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,39 @@
package com.baeldung.pairs;
import static org.junit.Assert.*;
import java.util.AbstractMap;
import org.junit.Test;
public class CoreJavaSimpleEntryUnitTest {
@Test
public void givenSimpleEntry_whenGetValue_thenOk() {
AbstractMap.SimpleEntry<Integer, String> entry = new AbstractMap.SimpleEntry<Integer, String>(1, "one");
Integer key = entry.getKey();
String value = entry.getValue();
assertEquals(key.intValue(), 1);
assertEquals(value, "one");
}
@Test(expected = UnsupportedOperationException.class)
public void givenSimpleImmutableEntry_whenSetValue_thenException() {
AbstractMap.SimpleImmutableEntry<Integer, String> entry = new AbstractMap.SimpleImmutableEntry<Integer, String>(1, "one");
entry.setValue("two");
}
@Test
public void givenSimpleImmutableEntry_whenGetValue_thenOk() {
AbstractMap.SimpleImmutableEntry<Integer, String> entry = new AbstractMap.SimpleImmutableEntry<Integer, String>(1, "one");
Integer key = entry.getKey();
String value = entry.getValue();
assertEquals(key.intValue(), 1);
assertEquals(value, "one");
}
}

View File

@ -28,6 +28,7 @@
</properties>
<modules>
<module>apache-cayenne</module>
<module>aws</module>
<module>akka-streams</module>
<module>algorithms</module>

View File

@ -3,7 +3,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>rxjava</artifactId>
<version>1.0-SNAPSHOT</version>
@ -31,10 +30,35 @@
<artifactId>awaitility</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>com.github.davidmoten</groupId>
<artifactId>rxjava-jdbc</artifactId>
<version>${rx.java.jdbc.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>22.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<assertj.version>3.8.0</assertj.version>
<rx.java.version>1.2.5</rx.java.version>
<rx.java.jdbc.version>0.7.11</rx.java.jdbc.version>
<h2.version>1.4.196</h2.version>
</properties>

View File

@ -0,0 +1,13 @@
package com.baeldung.rxjava.jdbc;
import com.github.davidmoten.rx.jdbc.ConnectionProvider;
import com.github.davidmoten.rx.jdbc.ConnectionProviderFromUrl;
class Connector {
static final String DB_CONNECTION = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1";
static final String DB_USER = "";
static final String DB_PASSWORD = "";
static final ConnectionProvider connectionProvider = new ConnectionProviderFromUrl(DB_CONNECTION, DB_USER, DB_PASSWORD);
}

View File

@ -0,0 +1,13 @@
package com.baeldung.rxjava.jdbc;
import com.github.davidmoten.rx.jdbc.annotations.Column;
public interface Employee {
@Column("id")
int id();
@Column("name")
String name();
}

View File

@ -0,0 +1,28 @@
package com.baeldung.rxjava.jdbc;
public class Manager {
private int id;
private String name;
public Manager(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.rxjava.jdbc;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import org.apache.commons.io.IOUtils;
class Utils {
static String getStringFromInputStream(InputStream input) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(input, writer, "UTF-8");
return writer.toString();
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,235 @@
package com.baeldung.rxjava;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import rx.Observable;
import rx.Scheduler;
import rx.observers.TestSubscriber;
import rx.schedulers.Schedulers;
import rx.schedulers.TestScheduler;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.Executors.newFixedThreadPool;
import static org.hamcrest.Matchers.hasItems;
import static org.junit.Assert.assertThat;
public class SchedulersTest {
private String result = "";
private String result1 = "";
private String result2 = "";
@Test
public void givenScheduledWorker_whenScheduleAnAction_thenResultAction() throws InterruptedException {
System.out.println("scheduling");
Scheduler scheduler = Schedulers.immediate();
Scheduler.Worker worker = scheduler.createWorker();
worker.schedule(() -> result += "action");
Assert.assertTrue(result.equals("action"));
}
@Test
public void givenScheduledWorker_whenUnsubscribeOnWorker_thenResultFirstAction() throws InterruptedException {
System.out.println("canceling");
Scheduler scheduler = Schedulers.newThread();
Scheduler.Worker worker = scheduler.createWorker();
worker.schedule(() -> {
result += "First_Action";
worker.unsubscribe();
});
worker.schedule(() -> result += "Second_Action");
Thread.sleep(500);
Assert.assertTrue(result.equals("First_Action"));
}
@Ignore //it's not safe, not every time is running correctly
@Test
public void givenWorker_whenScheduledOnNewThread_thenResultIsBoundToNewThread() throws InterruptedException {
System.out.println("newThread_1");
Scheduler scheduler = Schedulers.newThread();
Scheduler.Worker worker = scheduler.createWorker();
worker.schedule(() -> {
result += Thread.currentThread().getName() + "_Start";
worker.schedule(() -> result += "_worker_");
result += "_End";
});
Thread.sleep(2000);
Assert.assertTrue(result.equals("RxNewThreadScheduler-1_Start_End_worker_"));
}
@Test
public void givenObservable_whenObserveOnNewThread_thenRunOnDifferentThreadEachTime() throws InterruptedException {
System.out.println("newThread_2");
Observable.just("Hello")
.observeOn(Schedulers.newThread())
.doOnNext(s ->
result2 += Thread.currentThread().getName()
)
.observeOn(Schedulers.newThread())
.subscribe(s ->
result1 += Thread.currentThread().getName()
);
Thread.sleep(500);
Assert.assertTrue(result1.equals("RxNewThreadScheduler-1"));
Assert.assertTrue(result2.equals("RxNewThreadScheduler-2"));
}
@Test
public void givenWorker_whenScheduledOnImmediate_thenResultIsBoundToThread() throws InterruptedException {
System.out.println("immediate_1");
Scheduler scheduler = Schedulers.immediate();
Scheduler.Worker worker = scheduler.createWorker();
worker.schedule(() -> {
result += Thread.currentThread().getName() + "_Start";
worker.schedule(() -> result += "_worker_");
result += "_End";
});
Thread.sleep(500);
Assert.assertTrue(result.equals("main_Start_worker__End"));
}
@Test
public void givenObservable_whenImmediateScheduled_thenExecuteOnMainThread() throws InterruptedException {
System.out.println("immediate_2");
Observable.just("Hello")
.subscribeOn(Schedulers.immediate())
.subscribe(s ->
result += Thread.currentThread().getName()
);
Thread.sleep(500);
Assert.assertTrue(result.equals("main"));
}
@Test
public void givenObservable_whenTrampolineScheduled_thenExecuteOnMainThread() throws InterruptedException {
System.out.println("trampoline_1");
Observable.just(2, 4, 6, 8)
.subscribeOn(Schedulers.trampoline())
.subscribe(i -> result += "" + i);
Observable.just(1, 3, 5, 7, 9)
.subscribeOn(Schedulers.trampoline())
.subscribe(i -> result += "" + i);
Thread.sleep(500);
Assert.assertTrue(result.equals("246813579"));
}
@Test
public void givenWorker_whenScheduledOnTrampoline_thenComposeResultAsBlocking() throws InterruptedException {
System.out.println("trampoline_2");
Scheduler scheduler = Schedulers.trampoline();
Scheduler.Worker worker = scheduler.createWorker();
worker.schedule(() -> {
result += Thread.currentThread().getName() + "Start";
worker.schedule(() -> {
result += "_middleStart";
worker.schedule(() ->
result += "_worker_"
);
result += "_middleEnd";
});
result += "_mainEnd";
});
Thread.sleep(500);
Assert.assertTrue(result
.equals("mainStart_mainEnd_middleStart_middleEnd_worker_"));
}
private ThreadFactory threadFactory(String pattern) {
return new ThreadFactoryBuilder()
.setNameFormat(pattern)
.build();
}
@Test
public void givenExecutors_whenSchedulerFromCreatedExecutors_thenReturnElementsOnEacheThread() throws InterruptedException {
System.out.println("from");
ExecutorService poolA = newFixedThreadPool(10, threadFactory("Sched-A-%d"));
Scheduler schedulerA = Schedulers.from(poolA);
ExecutorService poolB = newFixedThreadPool(10, threadFactory("Sched-B-%d"));
Scheduler schedulerB = Schedulers.from(poolB);
Observable<String> observable = Observable.create(subscriber -> {
subscriber.onNext("Alfa");
subscriber.onNext("Beta");
subscriber.onCompleted();
});
;
observable
.subscribeOn(schedulerA)
.subscribeOn(schedulerB)
.subscribe(
x -> result += Thread.currentThread().getName() + x + "_",
Throwable::printStackTrace,
() -> result += "_Completed"
);
Thread.sleep(2000);
Assert.assertTrue(result.equals("Sched-A-0Alfa_Sched-A-0Beta__Completed"));
}
@Test
public void givenObservable_whenIoScheduling_thenReturnThreadName() throws InterruptedException {
System.out.println("io");
Observable.just("io")
.subscribeOn(Schedulers.io())
.subscribe(i -> result += Thread.currentThread().getName());
Thread.sleep(500);
Assert.assertTrue(result.equals("RxIoScheduler-2"));
}
@Test
public void givenObservable_whenComputationScheduling_thenReturnThreadName() throws InterruptedException {
System.out.println("computation");
Observable.just("computation")
.subscribeOn(Schedulers.computation())
.subscribe(i -> result += Thread.currentThread().getName());
Thread.sleep(500);
Assert.assertTrue(result.equals("RxComputationScheduler-1"));
}
@Test
public void givenLetters_whenTestScheduling_thenReturnValuesControllingAdvanceTime() throws InterruptedException {
List<String> letters = Arrays.asList("A", "B", "C");
TestScheduler scheduler = Schedulers.test();
TestSubscriber<String> subscriber = new TestSubscriber<>();
Observable<Long> tick = Observable.interval(1, TimeUnit.SECONDS, scheduler);
Observable.from(letters)
.zipWith(tick, (string, index) -> index + "-" + string)
.subscribeOn(scheduler)
.subscribe(subscriber);
subscriber.assertNoValues();
subscriber.assertNotCompleted();
scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
subscriber.assertNoErrors();
subscriber.assertValueCount(1);
subscriber.assertValues("0-A");
scheduler.advanceTimeTo(3, TimeUnit.SECONDS);
subscriber.assertCompleted();
subscriber.assertNoErrors();
subscriber.assertValueCount(3);
assertThat(subscriber.getOnNextEvents(), hasItems("0-A", "1-B", "2-C"));
}
@Test
public void givenLetters_whenDelay_thenReturne() throws InterruptedException {
ExecutorService poolA = newFixedThreadPool(10, threadFactory("Sched1-"));
Scheduler schedulerA = Schedulers.from(poolA);
Observable.just('A', 'B')
.delay(1, TimeUnit.SECONDS, schedulerA)
.subscribe(i -> result += Thread.currentThread().getName() + i + " ");
Thread.sleep(2000);
Assert.assertTrue(result.equals("Sched1-A Sched1-B "));
}
}

View File

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

View File

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

View File

@ -7,6 +7,7 @@ import rx.Observable;
import rx.Observer;
import rx.exceptions.OnErrorNotImplementedException;
import rx.schedulers.Schedulers;
import rx.schedulers.Timestamped;
import java.util.concurrent.TimeUnit;
@ -14,9 +15,9 @@ import static org.junit.Assert.assertTrue;
public class UtilityOperatorsTest {
int emittedTotal = 0;
int receivedTotal = 0;
String result = "";
private int emittedTotal = 0;
private int receivedTotal = 0;
private String result = "";
@Rule
public ExpectedException thrown = ExpectedException.none();
@ -44,7 +45,6 @@ public class UtilityOperatorsTest {
assertTrue(receivedTotal == 15000);
}
@Test
public void givenObservable_whenObserveOnBeforeOnNext_thenEmitsEventsOnComputeScheduler() throws InterruptedException {
@ -68,7 +68,6 @@ public class UtilityOperatorsTest {
assertTrue(receivedTotal == 15000);
}
@Test
public void givenObservable_whenSubscribeOn_thenEmitsEventsOnComputeScheduler() throws InterruptedException {
@ -92,7 +91,6 @@ public class UtilityOperatorsTest {
assertTrue(receivedTotal == 15000);
}
@Test
public void givenObservableWithOneEvent_whenSingle_thenEmitEvent() {
@ -197,15 +195,13 @@ public class UtilityOperatorsTest {
@Test
public void givenObservables_whenDelay_thenEventsStartAppearAfterATime() throws InterruptedException {
Observable source
= Observable.interval(1, TimeUnit.SECONDS)
Observable<Timestamped<Long>> source = Observable.interval(1, TimeUnit.SECONDS)
.take(5)
.timestamp();
Observable delay
= source.delaySubscription(2, TimeUnit.SECONDS);
Observable<Timestamped<Long>> delay = source.delaySubscription(2, TimeUnit.SECONDS);
source.subscribe(
source.<Long>subscribe(
value -> System.out.println("source :" + value),
t -> System.out.println("source error"),
() -> System.out.println("source completed"));
@ -231,14 +227,12 @@ public class UtilityOperatorsTest {
Observable<Character> values = Observable.using(
() -> "resource",
r -> {
return Observable.create(o -> {
for (Character c : r.toCharArray()) {
o.onNext(c);
}
o.onCompleted();
});
},
r -> Observable.create(o -> {
for (Character c : r.toCharArray()) {
o.onNext(c);
}
o.onCompleted();
}),
r -> System.out.println("Disposed: " + r)
);
values.subscribe(
@ -248,7 +242,6 @@ public class UtilityOperatorsTest {
assertTrue(result.equals("resource"));
}
@Test
public void givenObservableCached_whenSubscribesWith2Actions_thenEmitsCachedValues() {
@ -269,5 +262,4 @@ public class UtilityOperatorsTest {
});
assertTrue(receivedTotal == 8);
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.rxjava.jdbc;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class AutomapClassIntegrationTest {
private Database db = Database.from(Connector.connectionProvider);
private Observable<Integer> create = null;
private Observable<Integer> insert1, insert2 = null;
@Before
public void setup() {
create = db.update("CREATE TABLE IF NOT EXISTS MANAGER(id int primary key, name varchar(255))")
.count();
insert1 = db.update("INSERT INTO MANAGER(id, name) VALUES(1, 'Alan')")
.dependsOn(create)
.count();
insert2 = db.update("INSERT INTO MANAGER(id, name) VALUES(2, 'Sarah')")
.dependsOn(create)
.count();
}
@Test
public void whenSelectManagersAndAutomap_thenCorrect() {
List<Manager> managers = db.select("select id, name from MANAGER")
.dependsOn(create)
.dependsOn(insert1)
.dependsOn(insert2)
.autoMap(Manager.class)
.toList()
.toBlocking()
.single();
assertThat(managers.get(0)
.getId()).isEqualTo(1);
assertThat(managers.get(0)
.getName()).isEqualTo("Alan");
assertThat(managers.get(1)
.getId()).isEqualTo(2);
assertThat(managers.get(1)
.getName()).isEqualTo("Sarah");
}
@After
public void close() {
db.update("DROP TABLE MANAGER")
.dependsOn(create);
Connector.connectionProvider.close();
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.rxjava.jdbc;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class AutomapInterfaceIntegrationTest {
private Database db = Database.from(Connector.connectionProvider);
private Observable<Integer> create = null;
private Observable<Integer> insert1, insert2 = null;
@Before
public void setup() {
create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))")
.count();
insert1 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'Alan')")
.dependsOn(create)
.count();
insert2 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(2, 'Sarah')")
.dependsOn(create)
.count();
}
@Test
public void whenSelectFromTableAndAutomap_thenCorrect() {
List<Employee> employees = db.select("select id, name from EMPLOYEE")
.dependsOn(create)
.dependsOn(insert1)
.dependsOn(insert2)
.autoMap(Employee.class)
.toList()
.toBlocking()
.single();
assertThat(employees.get(0)
.id()).isEqualTo(1);
assertThat(employees.get(0)
.name()).isEqualTo("Alan");
assertThat(employees.get(1)
.id()).isEqualTo(2);
assertThat(employees.get(1)
.name()).isEqualTo("Sarah");
}
@After
public void close() {
db.update("DROP TABLE EMPLOYEE")
.dependsOn(create);
Connector.connectionProvider.close();
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.rxjava.jdbc;
import com.github.davidmoten.rx.jdbc.Database;
import org.junit.After;
import org.junit.Test;
import rx.Observable;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class BasicQueryTypesIntegrationTest {
private Database db = Database.from(Connector.connectionProvider);
private Observable<Integer> create;
@Test
public void whenCreateTableAndInsertRecords_thenCorrect() {
create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))")
.count();
Observable<Integer> insert1 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'John')")
.dependsOn(create)
.count();
Observable<Integer> update = db.update("UPDATE EMPLOYEE SET name = 'Alan' WHERE id = 1")
.dependsOn(create)
.count();
Observable<Integer> insert2 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(2, 'Sarah')")
.dependsOn(create)
.count();
Observable<Integer> insert3 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(3, 'Mike')")
.dependsOn(create)
.count();
Observable<Integer> delete = db.update("DELETE FROM EMPLOYEE WHERE id = 2")
.dependsOn(create)
.count();
List<String> names = db.select("select name from EMPLOYEE where id < ?")
.parameter(3)
.dependsOn(create)
.dependsOn(insert1)
.dependsOn(insert2)
.dependsOn(insert3)
.dependsOn(update)
.dependsOn(delete)
.getAs(String.class)
.toList()
.toBlocking()
.single();
assertEquals(Arrays.asList("Alan"), names);
}
@After
public void close() {
db.update("DROP TABLE EMPLOYEE")
.dependsOn(create);
Connector.connectionProvider.close();
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.rxjava.jdbc;
import com.github.davidmoten.rx.jdbc.Database;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import rx.Observable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import static org.junit.Assert.assertEquals;
public class InsertBlobIntegrationTest {
private Database db = Database.from(Connector.connectionProvider);
private String expectedDocument = null;
private String actualDocument = null;
private Observable<Integer> create, insert = null;
@Before
public void setup() throws IOException {
create = db.update("CREATE TABLE IF NOT EXISTS SERVERLOG (id int primary key, document BLOB)")
.count();
InputStream actualInputStream = new FileInputStream("src/test/resources/actual_clob");
this.actualDocument = Utils.getStringFromInputStream(actualInputStream);
byte[] bytes = this.actualDocument.getBytes(StandardCharsets.UTF_8);
InputStream expectedInputStream = new FileInputStream("src/test/resources/expected_clob");
this.expectedDocument = Utils.getStringFromInputStream(expectedInputStream);
this.insert = db.update("insert into SERVERLOG(id,document) values(?,?)")
.parameter(1)
.parameter(Database.toSentinelIfNull(bytes))
.dependsOn(create)
.count();
}
@Test
public void whenInsertBLOB_thenCorrect() throws IOException {
db.select("select document from SERVERLOG where id = 1")
.dependsOn(create)
.dependsOn(insert)
.getAs(String.class)
.toList()
.toBlocking()
.single();
assertEquals(expectedDocument, actualDocument);
}
@After
public void close() {
db.update("DROP TABLE SERVERLOG")
.dependsOn(create);
Connector.connectionProvider.close();
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.rxjava.jdbc;
import com.github.davidmoten.rx.jdbc.Database;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import rx.Observable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import static org.junit.Assert.assertEquals;
public class InsertClobIntegrationTest {
private Database db = Database.from(Connector.connectionProvider);
private String expectedDocument = null;
private String actualDocument = null;
private Observable<Integer> create, insert = null;
@Before
public void setup() throws IOException {
create = db.update("CREATE TABLE IF NOT EXISTS SERVERLOG (id int primary key, document CLOB)")
.count();
InputStream actualInputStream = new FileInputStream("src/test/resources/actual_clob");
this.actualDocument = Utils.getStringFromInputStream(actualInputStream);
InputStream expectedInputStream = new FileInputStream("src/test/resources/expected_clob");
this.expectedDocument = Utils.getStringFromInputStream(expectedInputStream);
this.insert = db.update("insert into SERVERLOG(id,document) values(?,?)")
.parameter(1)
.parameter(Database.toSentinelIfNull(actualDocument))
.dependsOn(create)
.count();
}
@Test
public void whenSelectCLOB_thenCorrect() throws IOException {
db.select("select document from SERVERLOG where id = 1")
.dependsOn(create)
.dependsOn(insert)
.getAs(String.class)
.toList()
.toBlocking()
.single();
assertEquals(expectedDocument, actualDocument);
}
@After
public void close() {
db.update("DROP TABLE SERVERLOG")
.dependsOn(create);
Connector.connectionProvider.close();
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.rxjava.jdbc;
import com.github.davidmoten.rx.jdbc.Database;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import rx.Observable;
import static org.assertj.core.api.Assertions.assertThat;
public class ReturnKeysIntegrationTest {
private Observable<Integer> createStatement;
private Database db = Database.from(Connector.connectionProvider);
@Before
public void setup() {
Observable<Boolean> begin = db.beginTransaction();
createStatement = db
.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int auto_increment primary key, name varchar(255))")
.dependsOn(begin)
.count();
}
@Test
public void whenInsertAndReturnGeneratedKey_thenCorrect() {
Integer key = db.update("INSERT INTO EMPLOYEE(name) VALUES('John')")
.dependsOn(createStatement)
.returnGeneratedKeys()
.getAs(Integer.class)
.count()
.toBlocking()
.single();
assertThat(key).isEqualTo(1);
}
@After
public void close() {
db.update("DROP TABLE EMPLOYEE");
Connector.connectionProvider.close();
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.rxjava.jdbc;
import com.github.davidmoten.rx.jdbc.Database;
import org.junit.After;
import org.junit.Test;
import rx.Observable;
import static org.junit.Assert.assertEquals;
public class TransactionIntegrationTest {
private Database db = Database.from(Connector.connectionProvider);
@Test
public void whenCommitTransaction_thenRecordUpdated() {
Observable<Boolean> begin = db.beginTransaction();
Observable<Integer> createStatement = db
.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))")
.dependsOn(begin)
.count();
Observable<Integer> insertStatement = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'John')")
.dependsOn(createStatement)
.count();
Observable<Integer> updateStatement = db.update("UPDATE EMPLOYEE SET name = 'Tom' WHERE id = 1")
.dependsOn(insertStatement)
.count();
Observable<Boolean> commit = db.commit(updateStatement);
String name = db.select("select name from EMPLOYEE WHERE id = 1")
.dependsOn(commit)
.getAs(String.class)
.toBlocking()
.single();
assertEquals("Tom", name);
}
@After
public void close() {
db.update("DROP TABLE EMPLOYEE");
Connector.connectionProvider.close();
}
}

View File

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

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -3,8 +3,7 @@ package org.baeldung.controller.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
/**
@ -16,23 +15,23 @@ import org.springframework.web.servlet.ModelAndView;
*/
@Controller
public class PassParametersController {
@RequestMapping(value = "/showViewPage", method = RequestMethod.GET)
@GetMapping("/showViewPage")
public String passParametersWithModel(Model model) {
model.addAttribute("message", "Baeldung");
return "viewPage";
}
@RequestMapping(value = "/printViewPage", method = RequestMethod.GET)
@GetMapping("/printViewPage")
public String passParametersWithModelMap(ModelMap map) {
map.addAttribute("welcomeMessage", "welcome");
map.addAttribute("message", "Baeldung");
return "viewPage";
}
@RequestMapping(value = "/goToViewPage", method = RequestMethod.GET)
@GetMapping("/goToViewPage")
public ModelAndView passParametersWithModelAndView() {
ModelAndView modelAndView = new ModelAndView("viewPage");
modelAndView.addObject("message", "Baeldung");
return modelAndView;
}
}
}

View File

@ -15,6 +15,7 @@
<module>spring-cloud-ribbon-client</module>
<module>spring-cloud-rest</module>
<module>spring-cloud-zookeeper</module>
<module>spring-cloud-gateway</module>
</modules>
<packaging>pom</packaging>

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Explore the new Spring Cloud Gateway](http://www.baeldung.com/spring-cloud-gateway)

View File

@ -0,0 +1,79 @@
<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>gateway-service</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Spring Cloud Gateway Service</name>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-gateway</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<properties>
<version>2.0.0.M2</version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
<version>${version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<version>${version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway-core</artifactId>
<version>${version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>${version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-cdi</artifactId>
<version>6.0.2.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.0.Final</version>
</dependency>
<dependency>
<groupId>io.projectreactor.ipc</groupId>
<artifactId>reactor-netty</artifactId>
<version>0.7.0.M1</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>

View File

@ -0,0 +1,12 @@
package com.baeldung.spring.cloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}

View File

@ -0,0 +1,13 @@
server:
port: 80
spring:
cloud:
gateway:
routes:
- id: baeldung_route
uri: http://www.baeldung.com
predicates:
- Path=/baeldung
management:
security:
enabled: false

View File

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-gateway</artifactId>
<version>1.0.0-SNAPSHOT</version>
<modules>
<module>gateway-service</module>
</modules>
<packaging>pom</packaging>
<name>Spring Cloud Gateway</name>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<spring-boot-maven-plugin.version>1.4.2.RELEASE</spring-boot-maven-plugin.version>
</properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

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

View File

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

View File

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

View File

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

View File

@ -1,7 +1,7 @@
# jdbc.X
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
jdbc.user=sa
jdbc.eventGeneratedId=sa
jdbc.pass=sa
# hibernate.X

View File

@ -1,7 +1,7 @@
# jdbc.X
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate5_01?createDatabaseIfNotExist=true
jdbc.user=tutorialuser
jdbc.eventGeneratedId=tutorialuser
jdbc.pass=tutorialmy5ql
# hibernate.X

View File

@ -1,6 +1,7 @@
package com.baeldung.hibernate.immutable;
import com.baeldung.hibernate.immutable.entities.Event;
import com.baeldung.hibernate.immutable.entities.EventGeneratedId;
import com.baeldung.hibernate.immutable.util.HibernateUtil;
import com.google.common.collect.Sets;
import org.hibernate.CacheMode;
@ -10,6 +11,9 @@ import org.junit.rules.ExpectedException;
import javax.persistence.PersistenceException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
public class HibernateImmutableIntegrationTest {
private static Session session;
@ -22,6 +26,7 @@ public class HibernateImmutableIntegrationTest {
session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
createEvent();
createEventGenerated();
session.setCacheMode(CacheMode.REFRESH);
}
@ -35,9 +40,12 @@ public class HibernateImmutableIntegrationTest {
HibernateUtil.getSessionFactory().close();
}
//
@Test
public void addEvent() {
Event event = new Event();
event.setId(2L);
event.setTitle("Public Event");
session.save(event);
session.getTransaction().commit();
@ -47,8 +55,12 @@ public class HibernateImmutableIntegrationTest {
public void updateEvent() {
Event event = (Event) session.createQuery("FROM Event WHERE title='New Event'").list().get(0);
event.setTitle("Private Event");
session.saveOrUpdate(event);
session.getTransaction().commit();
session.update(event);
session.flush();
session.refresh(event);
assertThat(event.getTitle(), equalTo("New Event"));
assertThat(event.getId(), equalTo(5L));
}
@Test
@ -80,10 +92,29 @@ public class HibernateImmutableIntegrationTest {
session.getTransaction().commit();
}
public static void createEvent() {
Event event = new Event();
event.setTitle("New Event");
event.setGuestList(Sets.newHashSet("guest"));
@Test
public void updateEventGenerated() {
EventGeneratedId eventGeneratedId = (EventGeneratedId) session.createQuery("FROM EventGeneratedId WHERE name LIKE '%John%'").list().get(0);
eventGeneratedId.setName("Mike");
session.update(eventGeneratedId);
session.flush();
session.refresh(eventGeneratedId);
assertThat(eventGeneratedId.getName(), equalTo("John"));
assertThat(eventGeneratedId.getId(), equalTo(1L));
}
//
private static void createEvent() {
Event event = new Event(5L, "New Event", Sets.newHashSet("guest"));
session.save(event);
}
private static void createEventGenerated() {
EventGeneratedId eventGeneratedId = new EventGeneratedId("John", "Doe");
eventGeneratedId.setId(4L);
session.save(eventGeneratedId);
}
}

View File

@ -21,7 +21,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MainApplication.class)
public class ExamplePostControllerRequestUnitTest {
public class ExamplePostControllerRequestIntegrationTest {
MockMvc mockMvc;
@Mock private ExampleService exampleService;

View File

@ -23,7 +23,7 @@ import org.baeldung.config.MainApplication;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MainApplication.class)
public class ExamplePostControllerResponseUnitTest {
public class ExamplePostControllerResponseIntegrationTest {
MockMvc mockMvc;
@Mock private ExampleService exampleService;

View File

@ -1,33 +0,0 @@
package com.baeldung.web.log.test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import com.baeldung.web.log.data.TaxiRide;
public class TestTaxiFareController {
private static final String URL = "http://localhost:" + 8082 + "/spring-rest/taxifare/";
@Test
public void givenRequest_whenFetchTaxiFareRateCard_thanOK() {
TestRestTemplate testRestTemplate = new TestRestTemplate();
ResponseEntity<String> response = testRestTemplate.getForEntity(URL + "get/", String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenTaxiRide_whenCalculatedFare_thanStatus200() {
TestRestTemplate testRestTemplate = new TestRestTemplate();
TaxiRide taxiRide = new TaxiRide(true, 10l);
String fare = testRestTemplate.postForObject(URL + "calculate/", taxiRide, String.class);
assertThat(fare, equalTo("200"));
}
}

View File

@ -8,3 +8,4 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com
- [Two Login Pages with Spring Security](http://www.baeldung.com/spring-security-two-login-pages)
- [Multiple Entry Points in Spring Security](http://www.baeldung.com/spring-security-multiple-entry-points)
- [Multiple Authentication Providers in Spring Security](http://www.baeldung.com/spring-security-multiple-auth-providers)
- [Granted Authority Versus Role in Spring Security](http://www.baeldung.com/spring-security-granted-authority-vs-role)

View File

@ -5,4 +5,4 @@
- [Property Testing Example With Vavr](http://www.baeldung.com/javaslang-property-testing)
- [Exceptions in Lambda Expression Using Vavr](http://www.baeldung.com/exceptions-using-vavr)
- [Vavr (ex-Javaslang) Support in Spring Data](http://www.baeldung.com/spring-vavr)
- [Collection Factory Methods for Vavr](http://www.baeldung.com/vavr-collection-factory-methods)

View File

@ -74,7 +74,7 @@
<properties>
<java.version>1.8</java.version>
<vavr.version>0.9.0</vavr.version>
<vavr.version>0.9.1</vavr.version>
<junit.version>4.12</junit.version>
<awaitility.version>3.0.0</awaitility.version>
</properties>

View File

@ -5,17 +5,23 @@ import static io.vavr.API.Case;
import static io.vavr.API.Match;
import static io.vavr.Predicates.exists;
import static io.vavr.Predicates.forAll;
import static org.awaitility.Awaitility.await;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.CancellationException;
import java.util.function.Consumer;
import java.util.function.Predicate;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.internal.verification.VerificationModeFactory;
import org.mockito.verification.Timeout;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import io.vavr.collection.List;
import io.vavr.concurrent.Future;
import io.vavr.control.Try;
public class FutureUnitTest {
@ -26,8 +32,7 @@ public class FutureUnitTest {
public void givenFunctionReturnInteger_WhenCallWithFuture_ShouldReturnFunctionValue() {
Future<Integer> future = Future.of(() -> 1);
assertEquals(1, future.get()
.intValue());
assertEquals(1, future.get().intValue());
}
@Test
@ -57,33 +62,29 @@ public class FutureUnitTest {
@Test
public void givenFunction_WhenCallWithFutureAndRegisterConsumerForSuccess_ShouldCallConsumerToStoreValue() {
final int[] store = new int[] { 0 };
Future<Integer> future = Future.of(() -> 1);
future.onSuccess(i -> {
store[0] = i;
});
await().until(() -> store[0] == 1);
MockConsumer consumer = Mockito.mock(MockConsumer.class);
future.onSuccess(consumer);
Mockito.verify(consumer, new Timeout(1000, VerificationModeFactory.times(1))).accept(1);
}
@Test
public void givenFunctionThrowException_WhenCallWithFutureAndRegisterConsumerForFailer_ShouldCallConsumerToStoreException() {
final Throwable[] store = new Throwable[] { null };
Future<String> future = Future.of(() -> getResourceThrowException(""));
future.onFailure(err -> store[0] = err);
await().until(() -> RuntimeException.class.isInstance(store[0]));
MockThrowableConsumer consumer = Mockito.mock(MockThrowableConsumer.class);
future.onFailure(consumer);
Mockito.verify(consumer, new Timeout(1000, VerificationModeFactory.times(1))).accept(Mockito.any());
}
@Test
public void givenAFuture_WhenAddAndThenConsumer_ShouldCallConsumerWithResultOfFutureAction() {
int[] store1 = new int[1];
int[] store2 = new int[1];
MockTryConsumer consumer1 = Mockito.mock(MockTryConsumer.class);
MockTryConsumer consumer2 = Mockito.mock(MockTryConsumer.class);
Future<Integer> future = Future.of(() -> 1);
Future<Integer> andThenFuture = future.andThen(i -> store1[0] = i.get() + 1)
.andThen(i -> store2[0] = store1[0] + 1);
Future<Integer> andThenFuture = future.andThen(consumer1).andThen(consumer2);
andThenFuture.await();
assertEquals(2, store1[0]);
assertEquals(3, store2[0]);
Mockito.verify(consumer1, VerificationModeFactory.times(1)).accept(Try.success(1));
Mockito.verify(consumer2, VerificationModeFactory.times(1)).accept(Try.success(1));
}
@Test
@ -91,8 +92,7 @@ public class FutureUnitTest {
Future<Integer> future = Future.failed(new RuntimeException());
Future<Integer> future2 = future.orElse(Future.of(() -> 2));
assertEquals(2, future2.get()
.intValue());
assertEquals(2, future2.get().intValue());
}
@Test(expected = CancellationException.class)
@ -124,17 +124,46 @@ public class FutureUnitTest {
Future<String> future = Future.failed(new RuntimeException());
Future<String> fallbackFuture = Future.of(() -> expectedResult);
Future<String> futureResult = future.fallbackTo(fallbackFuture);
futureResult.await();
assertEquals(expectedResult, futureResult.get());
}
@Test
public void givenAFuture_WhenTransformByAddingOne_ShouldReturn() {
Future<Object> future = Future.of(() -> 1).transformValue(f -> Try.of(() -> "Hello: " + f.get()));
assertEquals("Hello: 1", future.get());
}
@Test
public void givenAFutureOfInt_WhenMapToString_ShouldCombineAndReturn() {
Future<String> future = Future.of(()->1).map(i -> "Hello: " + i);
assertEquals("Hello: 1", future.get());
}
@Test
public void givenAFutureOfInt_WhenFlatMapToString_ShouldCombineAndReturn() {
Future<Object> futureMap = Future.of(() -> 1).flatMap((i) -> Future.of(() -> "Hello: " + i));
assertEquals("Hello: 1", futureMap.get());
}
@Test
public void givenAFutureOf2String_WhenZip_ShouldReturnTupleOf2String() {
Future<Tuple2<String, String>> future = Future.of(() -> "hello").zip(Future.of(() -> "world"));
assertEquals(Tuple.of("hello", "world"), future.get());
}
@Test
public void givenGetResourceWithFuture_WhenWaitAndMatchWithPredicate_ShouldReturnSuccess() {
String url = "http://resource";
Future<String> future = Future.of(() -> getResource(url));
future.await();
String s = Match(future).of(Case($(future0 -> future0.isSuccess()), SUCCESS), Case($(), FAILURE));
String s = Match(future).of(
Case($(future0 -> future0.isSuccess()), SUCCESS),
Case($(), FAILURE));
assertEquals(SUCCESS, s);
}
@ -143,7 +172,9 @@ public class FutureUnitTest {
public void givenAFailedFuture_WhenWaitAndMatchWithPredicateCheckSuccess_ShouldReturnFailed() {
Future<Integer> future = Future.failed(new RuntimeException());
future.await();
String s = Match(future).of(Case($(future0 -> future0.isSuccess()), SUCCESS), Case($(), FAILURE));
String s = Match(future).of(
Case($(future0 -> future0.isSuccess()), SUCCESS),
Case($(), FAILURE));
assertEquals(FAILURE, s);
}
@ -155,7 +186,10 @@ public class FutureUnitTest {
return 1;
});
Predicate<Future<Integer>> predicate = f -> f.exists(i -> i % 2 == 1);
String s = Match(future).of(Case($(predicate), "Even"), Case($(), "Odd"));
String s = Match(future).of(
Case($(predicate), "Even"),
Case($(), "Odd"));
assertEquals("Even", s);
}
@ -164,7 +198,9 @@ public class FutureUnitTest {
public void givenAListOfFutureReturnFist3Integers_WhenMatchWithExistEvenNumberPredicate_ShouldReturnSuccess() {
List<Future<Integer>> futures = getFutureOfFirst3Number();
Predicate<Future<Integer>> predicate0 = future -> future.exists(i -> i % 2 == 0);
String s = Match(futures).of(Case($(exists(predicate0)), "Even"), Case($(), "Odd"));
String s = Match(futures).of(
Case($(exists(predicate0)), "Even"),
Case($(), "Odd"));
assertEquals("Even", s);
}
@ -173,7 +209,9 @@ public class FutureUnitTest {
public void givenAListOfFutureReturnFist3Integers_WhenMatchWithForAllNumberBiggerThanZeroPredicate_ShouldReturnSuccess() {
List<Future<Integer>> futures = getFutureOfFirst3Number();
Predicate<Future<Integer>> predicate0 = future -> future.exists(i -> i > 0);
String s = Match(futures).of(Case($(forAll(predicate0)), "Positive numbers"), Case($(), "None"));
String s = Match(futures).of(
Case($(forAll(predicate0)), "Positive numbers"),
Case($(), "None"));
assertEquals("Positive numbers", s);
}
@ -182,13 +220,19 @@ public class FutureUnitTest {
public void givenAListOfFutureReturnFist3Integers_WhenMatchWithForAllNumberSmallerThanZeroPredicate_ShouldReturnFailed() {
List<Future<Integer>> futures = getFutureOfFirst3Number();
Predicate<Future<Integer>> predicate0 = future -> future.exists(i -> i < 0);
String s = Match(futures).of(Case($(forAll(predicate0)), "Negative numbers"), Case($(), "None"));
String s = Match(futures).of(
Case($(forAll(predicate0)), "Negative numbers"),
Case($(), "None"));
assertEquals("None", s);
}
private String getResource(String url) throws InterruptedException {
Thread.sleep(10);
private String getResource(String url) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return "Content from " + url;
}
@ -200,4 +244,46 @@ public class FutureUnitTest {
List<Future<Integer>> futures = List.of(Future.of(() -> 1), Future.of(() -> 2), Future.of(() -> 3));
return futures;
}
private static void checkOnSuccessFunction() {
Future<Integer> future = Future.of(() -> 1);
future.onSuccess(i -> System.out.println("Future finish with result: " + i));
}
private static void checkOnFailureFunction() {
Future<Integer> future = Future.of(() -> {throw new RuntimeException("Failed");});
future.onFailure(t -> System.out.println("Future failures with exception: " + t));
}
private static void runAndThenConsumer() {
Future<Integer> future = Future.of(() -> 1);
future.andThen(i -> System.out.println("Do side-effect action 1 with input: " + i.get())).
andThen((i) -> System.out.println("Do side-effect action 2 with input: " + i.get()));
}
public static void main(String[] args) throws InterruptedException {
checkOnSuccessFunction();
checkOnFailureFunction();
runAndThenConsumer();
Thread.sleep(1000);
}
}
class MockConsumer implements Consumer<Integer> {
@Override
public void accept(Integer t) {
}
}
class MockTryConsumer implements Consumer<Try<Integer>> {
@Override
public void accept(Try<Integer> t) {
}
}
class MockThrowableConsumer implements Consumer<Throwable> {
@Override
public void accept(Throwable t) {
}
}