commit
d0d3fff94d
|
@ -1,8 +1,8 @@
|
|||
|
||||
The "REST with Spring" Classes
|
||||
==============================
|
||||
This is what I'm working on: <br/>
|
||||
**[>> THE REST WITH SPRING CLASSES](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=25off)**
|
||||
After 5 months of work, here's the Master Class: <br/>
|
||||
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||
|
||||
|
||||
Spring Tutorials
|
||||
|
|
|
@ -0,0 +1,77 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>resteasy-tutorial</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<properties>
|
||||
<resteasy.version>3.0.14.Final</resteasy.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<finalName>RestEasyTutorial</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!-- core library -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.jboss.resteasy</groupId>
|
||||
<artifactId>resteasy-servlet-initializer</artifactId>
|
||||
<version>${resteasy.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.jboss.resteasy</groupId>
|
||||
<artifactId>resteasy-client</artifactId>
|
||||
<version>${resteasy.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Optional library -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.jboss.resteasy</groupId>
|
||||
<artifactId>resteasy-jaxb-provider</artifactId>
|
||||
<version>${resteasy.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.jboss.resteasy</groupId>
|
||||
<artifactId>resteasy-jackson-provider</artifactId>
|
||||
<version>${resteasy.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Junit Library -->
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.4</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.4</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
||||
</project>
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.client;
|
||||
|
||||
import com.baeldung.model.Movie;
|
||||
import javax.ws.rs.*;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.List;
|
||||
|
||||
@Path("/movies")
|
||||
public interface ServicesInterface {
|
||||
|
||||
@GET
|
||||
@Path("/getinfo")
|
||||
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
|
||||
Movie movieByImdbId(@QueryParam("imdbId") String imdbId);
|
||||
|
||||
@GET
|
||||
@Path("/listmovies")
|
||||
@Produces({ "application/json" })
|
||||
List<Movie> listMovies();
|
||||
|
||||
@POST
|
||||
@Path("/addmovie")
|
||||
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
|
||||
Response addMovie(Movie movie);
|
||||
|
||||
@PUT
|
||||
@Path("/updatemovie")
|
||||
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
|
||||
Response updateMovie(Movie movie);
|
||||
|
||||
@DELETE
|
||||
@Path("/deletemovie")
|
||||
Response deleteMovie(@QueryParam("imdbId") String imdbID);
|
||||
|
||||
}
|
|
@ -0,0 +1,66 @@
|
|||
package com.baeldung.model;
|
||||
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
@XmlType(name = "movie", propOrder = { "imdbId", "title" })
|
||||
public class Movie {
|
||||
|
||||
protected String imdbId;
|
||||
protected String title;
|
||||
|
||||
public Movie(String imdbId, String title) {
|
||||
this.imdbId = imdbId;
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public Movie() {}
|
||||
|
||||
public String getImdbId() {
|
||||
return imdbId;
|
||||
}
|
||||
|
||||
public void setImdbId(String imdbId) {
|
||||
this.imdbId = imdbId;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
|
||||
Movie movie = (Movie) o;
|
||||
|
||||
if (imdbId != null ? !imdbId.equals(movie.imdbId) : movie.imdbId != null)
|
||||
return false;
|
||||
return title != null ? title.equals(movie.title) : movie.title == null;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = imdbId != null ? imdbId.hashCode() : 0;
|
||||
result = 31 * result + (title != null ? title.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Movie{" +
|
||||
"imdbId='" + imdbId + '\'' +
|
||||
", title='" + title + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
package com.baeldung.server;
|
||||
|
||||
import com.baeldung.model.Movie;
|
||||
import javax.ws.rs.*;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Path("/movies")
|
||||
public class MovieCrudService {
|
||||
|
||||
private Map<String, Movie> inventory = new HashMap<String, Movie>();
|
||||
|
||||
@GET
|
||||
@Path("/getinfo")
|
||||
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
|
||||
public Movie movieByImdbId(@QueryParam("imdbId") String imdbId) {
|
||||
|
||||
System.out.println("*** Calling getinfo for a given ImdbID***");
|
||||
|
||||
if (inventory.containsKey(imdbId)) {
|
||||
return inventory.get(imdbId);
|
||||
} else
|
||||
return null;
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/addmovie")
|
||||
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
|
||||
public Response addMovie(Movie movie) {
|
||||
|
||||
System.out.println("*** Calling addMovie ***");
|
||||
|
||||
if (null != inventory.get(movie.getImdbId())) {
|
||||
return Response.status(Response.Status.NOT_MODIFIED).entity("Movie is Already in the database.").build();
|
||||
}
|
||||
|
||||
inventory.put(movie.getImdbId(), movie);
|
||||
return Response.status(Response.Status.CREATED).build();
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/updatemovie")
|
||||
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
|
||||
public Response updateMovie(Movie movie) {
|
||||
|
||||
System.out.println("*** Calling updateMovie ***");
|
||||
|
||||
if (null == inventory.get(movie.getImdbId())) {
|
||||
return Response.status(Response.Status.NOT_MODIFIED).entity("Movie is not in the database.\nUnable to Update").build();
|
||||
}
|
||||
|
||||
inventory.put(movie.getImdbId(), movie);
|
||||
return Response.status(Response.Status.OK).build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/deletemovie")
|
||||
public Response deleteMovie(@QueryParam("imdbId") String imdbId) {
|
||||
|
||||
System.out.println("*** Calling deleteMovie ***");
|
||||
|
||||
if (null == inventory.get(imdbId)) {
|
||||
return Response.status(Response.Status.NOT_FOUND).entity("Movie is not in the database.\nUnable to Delete").build();
|
||||
}
|
||||
|
||||
inventory.remove(imdbId);
|
||||
return Response.status(Response.Status.OK).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/listmovies")
|
||||
@Produces({ "application/json" })
|
||||
public List<Movie> listMovies() {
|
||||
|
||||
return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.server;
|
||||
|
||||
import javax.ws.rs.ApplicationPath;
|
||||
import javax.ws.rs.core.Application;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
@ApplicationPath("/rest")
|
||||
public class RestEasyServices extends Application {
|
||||
|
||||
private Set<Object> singletons = new HashSet<Object>();
|
||||
|
||||
public RestEasyServices() {
|
||||
singletons.add(new MovieCrudService());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Object> getSingletons() {
|
||||
return singletons;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Class<?>> getClasses() {
|
||||
return super.getClasses();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> getProperties() {
|
||||
return super.getProperties();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
<configuration scan="true" scanPeriod="10 seconds">
|
||||
|
||||
</configuration>
|
|
@ -0,0 +1,13 @@
|
|||
<?xml version="1.0"?>
|
||||
<jboss-deployment-structure>
|
||||
<deployment>
|
||||
<exclude-subsystems>
|
||||
<subsystem name="resteasy"/>
|
||||
</exclude-subsystems>
|
||||
<exclusions>
|
||||
<module name="javaee.api"/><module name="javax.ws.rs.api"/>
|
||||
<module name="org.jboss.resteasy.resteasy-jaxrs"/>
|
||||
</exclusions>
|
||||
<local-last value="true"/>
|
||||
</deployment>
|
||||
</jboss-deployment-structure>
|
|
@ -0,0 +1,4 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE jboss-web PUBLIC "-//JBoss//DTD Web Application 4.2//EN" "http://www.jboss.org/j2ee/dtd/jboss-web_4_2.dtd">
|
||||
<jboss-web>
|
||||
</jboss-web>
|
|
@ -0,0 +1,13 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
|
||||
|
||||
<display-name>RestEasy Example</display-name>
|
||||
|
||||
<context-param>
|
||||
<param-name>resteasy.servlet.mapping.prefix</param-name>
|
||||
<param-value>/rest</param-value>
|
||||
</context-param>
|
||||
|
||||
</web-app>
|
|
@ -37,7 +37,7 @@
|
|||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit-dep</artifactId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
@ -151,7 +151,7 @@
|
|||
<mysql-connector-java.version>5.1.34</mysql-connector-java.version>
|
||||
|
||||
<!-- marshalling -->
|
||||
<jackson.version>2.4.4</jackson.version>
|
||||
<jackson.version>2.5.5</jackson.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.9</org.slf4j.version>
|
||||
|
@ -166,7 +166,7 @@
|
|||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.11</junit.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
|
||||
<httpcore.version>4.4</httpcore.version>
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
eclipse.preferences.version=1
|
||||
org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled
|
||||
org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
|
||||
org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull
|
||||
org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault
|
||||
|
@ -26,7 +27,7 @@ org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
|
|||
org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.fieldHiding=error
|
||||
org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
|
||||
org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
|
||||
org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
|
||||
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
|
||||
|
@ -35,7 +36,7 @@ org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled
|
|||
org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
|
||||
org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.localVariableHiding=error
|
||||
org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
|
||||
org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
|
||||
org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore
|
||||
|
@ -48,6 +49,7 @@ org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignor
|
|||
org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
|
||||
org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
|
||||
org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning
|
||||
org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error
|
||||
org.eclipse.jdt.core.compiler.problem.nullReference=warning
|
||||
org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error
|
||||
|
@ -68,6 +70,7 @@ org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
|
|||
org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
|
||||
org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error
|
||||
org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled
|
||||
|
@ -82,6 +85,7 @@ org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore
|
|||
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unusedImport=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
|
||||
|
@ -91,6 +95,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=
|
|||
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
|
||||
org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
|
||||
org.eclipse.jdt.core.compiler.source=1.8
|
||||
|
|
|
@ -3,4 +3,8 @@
|
|||
## Core Java 8 Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
// - [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
|
||||
// - [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
|
||||
- [Java – Directory Size](http://www.baeldung.com/java-folder-size)
|
||||
- [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources)
|
||||
- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
|
||||
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
|
||||
|
|
|
@ -98,14 +98,14 @@
|
|||
|
||||
<properties>
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.12</org.slf4j.version>
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.0.13</logback.version>
|
||||
|
||||
<!-- various -->
|
||||
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>18.0</guava.version>
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.4</commons-lang3.version>
|
||||
|
||||
<!-- testing -->
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
public interface Adder {
|
||||
|
||||
String addWithFunction(Function<String, String> f);
|
||||
|
||||
void addWithConsumer(Consumer<Integer> f);
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class AdderImpl implements Adder {
|
||||
|
||||
@Override
|
||||
public String addWithFunction(final Function<String, String> f) {
|
||||
return f.apply("Something ");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addWithConsumer(final Consumer<Integer> f) {
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Bar {
|
||||
|
||||
String method(String string);
|
||||
|
||||
default String defaultMethod() {
|
||||
return "String from Bar";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Baz {
|
||||
|
||||
String method(String string);
|
||||
|
||||
default String defaultMethod() {
|
||||
return "String from Baz";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Foo {
|
||||
|
||||
String method(String string);
|
||||
|
||||
default void defaultMethod() {
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface FooExtended extends Baz, Bar {
|
||||
|
||||
@Override
|
||||
default String defaultMethod() {
|
||||
return Bar.super.defaultMethod();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
public class UseFoo {
|
||||
|
||||
private String value = "Enclosing scope value";
|
||||
|
||||
public String add(final String string, final Foo foo) {
|
||||
return foo.method(string);
|
||||
}
|
||||
|
||||
public String addWithStandardFI(final String string, final Function<String, String> fn) {
|
||||
return fn.apply(string);
|
||||
}
|
||||
|
||||
public String scopeExperiment() {
|
||||
final Foo fooIC = new Foo() {
|
||||
String value = "Inner class value";
|
||||
|
||||
@Override
|
||||
public String method(final String string) {
|
||||
return value;
|
||||
}
|
||||
};
|
||||
final String resultIC = fooIC.method("");
|
||||
|
||||
final Foo fooLambda = parameter -> {
|
||||
final String value = "Lambda value";
|
||||
return this.value;
|
||||
};
|
||||
final String resultLambda = fooLambda.method("");
|
||||
|
||||
return "Results: resultIC = " + resultIC + ", resultLambda = " + resultLambda;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,88 @@
|
|||
package com.baeldung.doublecolon;
|
||||
|
||||
public class Computer {
|
||||
|
||||
private Integer age;
|
||||
private String color;
|
||||
private Integer healty;
|
||||
|
||||
public Computer(final int age, final String color) {
|
||||
this.age = age;
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
public Computer(final Integer age, final String color, final Integer healty) {
|
||||
this.age = age;
|
||||
this.color = color;
|
||||
this.healty = healty;
|
||||
}
|
||||
|
||||
public Computer() {
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(final Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
public void setColor(final String color) {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
public Integer getHealty() {
|
||||
return healty;
|
||||
}
|
||||
|
||||
public void setHealty(final Integer healty) {
|
||||
this.healty = healty;
|
||||
}
|
||||
|
||||
public void turnOnPc() {
|
||||
System.out.println("Computer turned on");
|
||||
}
|
||||
|
||||
public void turnOffPc() {
|
||||
System.out.println("Computer turned off");
|
||||
}
|
||||
|
||||
public Double calculateValue(Double initialValue) {
|
||||
return initialValue / 1.50;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Computer{" + "age=" + age + ", color='" + color + '\'' + ", healty=" + healty + '}';
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final Computer computer = (Computer) o;
|
||||
|
||||
if (age != null ? !age.equals(computer.age) : computer.age != null) {
|
||||
return false;
|
||||
}
|
||||
return color != null ? color.equals(computer.color) : computer.color == null;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = age != null ? age.hashCode() : 0;
|
||||
result = 31 * result + (color != null ? color.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.doublecolon;
|
||||
|
||||
import com.baeldung.doublecolon.function.ComputerPredicate;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ComputerUtils {
|
||||
|
||||
public static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
|
||||
public static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
|
||||
|
||||
public static List<Computer> filter(final List<Computer> inventory, final ComputerPredicate p) {
|
||||
|
||||
final List<Computer> result = new ArrayList<>();
|
||||
inventory.stream().filter(p::filter).forEach(result::add);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void repair(final Computer computer) {
|
||||
if (computer.getHealty() < 50) {
|
||||
computer.setHealty(100);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.doublecolon;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
public class MacbookPro extends Computer {
|
||||
|
||||
public MacbookPro(int age, String color) {
|
||||
super(age, color);
|
||||
}
|
||||
|
||||
public MacbookPro(Integer age, String color, Integer healty) {
|
||||
super(age, color, healty);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void turnOnPc() {
|
||||
System.out.println("MacbookPro turned on");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void turnOffPc() {
|
||||
System.out.println("MacbookPro turned off");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Double calculateValue(Double initialValue) {
|
||||
|
||||
Function<Double, Double> function = super::calculateValue;
|
||||
final Double pcValue = function.apply(initialValue);
|
||||
System.out.println("First value is:" + pcValue);
|
||||
return pcValue + (initialValue / 10);
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.doublecolon.function;
|
||||
|
||||
import com.baeldung.doublecolon.Computer;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ComputerPredicate {
|
||||
|
||||
boolean filter(Computer c);
|
||||
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.doublecolon.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface TriFunction<A, B, C, R> {
|
||||
|
||||
R apply(A a, B b, C c);
|
||||
|
||||
default <V> TriFunction<A, B, C, V> andThen(final Function<? super R, ? extends V> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (final A a, final B b, final C c) -> after.apply(apply(a, b, c));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,89 @@
|
|||
package com.baeldung.doublecolon;
|
||||
|
||||
import com.baeldung.doublecolon.function.TriFunction;
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.BiFunction;
|
||||
|
||||
import static com.baeldung.doublecolon.ComputerUtils.*;
|
||||
|
||||
public class TestComputerUtils {
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConstructorReference() {
|
||||
|
||||
Computer c1 = new Computer(2015, "white");
|
||||
Computer c2 = new Computer(2009, "black");
|
||||
Computer c3 = new Computer(2014, "black");
|
||||
|
||||
BiFunction<Integer, String, Computer> c4Function = Computer::new;
|
||||
Computer c4 = c4Function.apply(2013, "white");
|
||||
BiFunction<Integer, String, Computer> c5Function = Computer::new;
|
||||
Computer c5 = c5Function.apply(2010, "black");
|
||||
BiFunction<Integer, String, Computer> c6Function = Computer::new;
|
||||
Computer c6 = c6Function.apply(2008, "black");
|
||||
|
||||
List<Computer> inventory = Arrays.asList(c1, c2, c3, c4, c5, c6);
|
||||
|
||||
List<Computer> blackComputer = filter(inventory, blackPredicate);
|
||||
Assert.assertEquals("The black Computers are: ", blackComputer.size(), 4);
|
||||
|
||||
List<Computer> after2010Computer = filter(inventory, after2010Predicate);
|
||||
Assert.assertEquals("The Computer bought after 2010 are: ", after2010Computer.size(), 3);
|
||||
|
||||
List<Computer> before2011Computer = filter(inventory, c -> c.getAge() < 2011);
|
||||
Assert.assertEquals("The Computer bought before 2011 are: ", before2011Computer.size(), 3);
|
||||
|
||||
inventory.sort(Comparator.comparing(Computer::getAge));
|
||||
|
||||
Assert.assertEquals("Oldest Computer in inventory", c6, inventory.get(0));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStaticMethodReference() {
|
||||
|
||||
Computer c1 = new Computer(2015, "white", 35);
|
||||
Computer c2 = new Computer(2009, "black", 65);
|
||||
TriFunction<Integer, String, Integer, Computer> c6Function = Computer::new;
|
||||
Computer c3 = c6Function.apply(2008, "black", 90);
|
||||
|
||||
List<Computer> inventory = Arrays.asList(c1, c2, c3);
|
||||
inventory.forEach(ComputerUtils::repair);
|
||||
|
||||
Assert.assertEquals("Computer repaired", new Integer(100), c1.getHealty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInstanceMethodArbitraryObjectParticularType() {
|
||||
|
||||
Computer c1 = new Computer(2015, "white", 35);
|
||||
Computer c2 = new MacbookPro(2009, "black", 65);
|
||||
List<Computer> inventory = Arrays.asList(c1, c2);
|
||||
inventory.forEach(Computer::turnOnPc);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuperMethodReference() {
|
||||
|
||||
final TriFunction<Integer, String, Integer, MacbookPro> integerStringIntegerObjectTriFunction = MacbookPro::new;
|
||||
final MacbookPro macbookPro = integerStringIntegerObjectTriFunction.apply(2010, "black", 100);
|
||||
Double initialValue = new Double(999.99);
|
||||
final Double actualValue = macbookPro.calculateValue(initialValue);
|
||||
Assert.assertEquals(766.659, actualValue, 0.0);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.java8;
|
||||
package com.baeldung.java8;
|
||||
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
@ -30,6 +30,14 @@ public class Java8CollectionCleanupUnitTest {
|
|||
assertThat(listWithoutNulls, hasSize(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListContainsNulls_whenRemovingNullsWithRemoveIf_thenCorrect() {
|
||||
final List<Integer> listWithoutNulls = Lists.newArrayList(null, 1, 2, null, 3, null);
|
||||
listWithoutNulls.removeIf(p -> p == null);
|
||||
|
||||
assertThat(listWithoutNulls, hasSize(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListContainsDuplicates_whenRemovingDuplicatesWithJava8_thenCorrect() {
|
||||
final List<Integer> listWithDuplicates = Lists.newArrayList(1, 1, 2, 2, 3, 3);
|
|
@ -0,0 +1,95 @@
|
|||
package com.baeldung.java8;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.Foo;
|
||||
import com.baeldung.FooExtended;
|
||||
import com.baeldung.UseFoo;
|
||||
|
||||
public class Java8FunctionalInteracesLambdasTest {
|
||||
|
||||
private UseFoo useFoo;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
useFoo = new UseFoo();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void functionalInterfaceInstantiation_whenReturnDefiniteString_thenCorrect() {
|
||||
final Foo foo = parameter -> parameter + "from lambda";
|
||||
final String result = useFoo.add("Message ", foo);
|
||||
|
||||
assertEquals("Message from lambda", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void standardFIParameter_whenReturnDefiniteString_thenCorrect() {
|
||||
final Function<String, String> fn = parameter -> parameter + "from lambda";
|
||||
final String result = useFoo.addWithStandardFI("Message ", fn);
|
||||
|
||||
assertEquals("Message from lambda", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void defaultMethodFromExtendedInterface_whenReturnDefiniteString_thenCorrect() {
|
||||
final FooExtended fooExtended = string -> string;
|
||||
final String result = fooExtended.defaultMethod();
|
||||
|
||||
assertEquals("String from Bar", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void lambdaAndInnerClassInstantiation_whenReturnSameString_thenCorrect() {
|
||||
final Foo foo = parameter -> parameter + "from Foo";
|
||||
|
||||
final Foo fooByIC = new Foo() {
|
||||
@Override
|
||||
public String method(final String string) {
|
||||
return string + "from Foo";
|
||||
}
|
||||
};
|
||||
|
||||
assertEquals(foo.method("Something "), fooByIC.method("Something "));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void accessVariablesFromDifferentScopes_whenReturnPredefinedString_thenCorrect() {
|
||||
assertEquals("Results: resultIC = Inner class value, resultLambda = Enclosing scope value", useFoo.scopeExperiment());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shorteningLambdas_whenReturnEqualsResults_thenCorrect() {
|
||||
final Foo foo = parameter -> buildString(parameter);
|
||||
|
||||
final Foo fooHuge = parameter -> {
|
||||
final String result = "Something " + parameter;
|
||||
// many lines of code
|
||||
return result;
|
||||
};
|
||||
|
||||
assertEquals(foo.method("Something"), fooHuge.method("Something"));
|
||||
}
|
||||
|
||||
private String buildString(final String parameter) {
|
||||
final String result = "Something " + parameter;
|
||||
// many lines of code
|
||||
return result;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mutatingOfEffectivelyFinalVariable_whenNotEquals_thenCorrect() {
|
||||
final int[] total = new int[1];
|
||||
final Runnable r = () -> total[0]++;
|
||||
r.run();
|
||||
|
||||
assertNotEquals(0, total[0]);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.java8;
|
||||
package com.baeldung.java8;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
|
@ -6,10 +6,10 @@ import java.util.Collections;
|
|||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
import org.baeldung.java8.entity.Human;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.java8.entity.Human;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.primitives.Ints;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.java8;
|
||||
package com.baeldung.java8;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
|
@ -15,15 +15,24 @@ import java.util.concurrent.atomic.AtomicLong;
|
|||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class JavaFolderSizeTest {
|
||||
|
||||
private String path;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
final String separator = File.separator;
|
||||
path = "src" + separator + "test" + separator + "resources";
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFolderSizeRecursive_thenCorrect() {
|
||||
final long expectedSize = 136;
|
||||
|
||||
final File folder = new File("src/test/resources");
|
||||
final File folder = new File(path);
|
||||
final long size = getFolderSize(folder);
|
||||
|
||||
assertEquals(expectedSize, size);
|
||||
|
@ -34,7 +43,7 @@ public class JavaFolderSizeTest {
|
|||
final long expectedSize = 136;
|
||||
|
||||
final AtomicLong size = new AtomicLong(0);
|
||||
final Path folder = Paths.get("src/test/resources");
|
||||
final Path folder = Paths.get(path);
|
||||
|
||||
Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
|
||||
@Override
|
||||
|
@ -51,7 +60,7 @@ public class JavaFolderSizeTest {
|
|||
public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException {
|
||||
final long expectedSize = 136;
|
||||
|
||||
final Path folder = Paths.get("src/test/resources");
|
||||
final Path folder = Paths.get(path);
|
||||
final long size = Files.walk(folder).filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum();
|
||||
|
||||
assertEquals(expectedSize, size);
|
||||
|
@ -61,7 +70,7 @@ public class JavaFolderSizeTest {
|
|||
public void whenGetFolderSizeUsingApacheCommonsIO_thenCorrect() {
|
||||
final long expectedSize = 136;
|
||||
|
||||
final File folder = new File("src/test/resources");
|
||||
final File folder = new File(path);
|
||||
final long size = FileUtils.sizeOfDirectory(folder);
|
||||
|
||||
assertEquals(expectedSize, size);
|
||||
|
@ -71,7 +80,7 @@ public class JavaFolderSizeTest {
|
|||
public void whenGetFolderSizeUsingGuava_thenCorrect() {
|
||||
final long expectedSize = 136;
|
||||
|
||||
final File folder = new File("src/test/resources");
|
||||
final File folder = new File(path);
|
||||
|
||||
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
|
||||
final long size = StreamSupport.stream(files.spliterator(), false).filter(f -> f.isFile()).mapToLong(File::length).sum();
|
||||
|
@ -81,7 +90,7 @@ public class JavaFolderSizeTest {
|
|||
|
||||
@Test
|
||||
public void whenGetReadableSize_thenCorrect() {
|
||||
final File folder = new File("src/test/resources");
|
||||
final File folder = new File(path);
|
||||
final long size = getFolderSize(folder);
|
||||
|
||||
final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
|
|
@ -0,0 +1,86 @@
|
|||
package com.baeldung.java8;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.util.Date;
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class JavaTryWithResourcesTest {
|
||||
|
||||
private static final String TEST_STRING_HELLO_WORLD = "Hello World";
|
||||
private Date resource1Date, resource2Date;
|
||||
|
||||
// tests
|
||||
|
||||
/* Example for using Try_with_resources */
|
||||
@Test
|
||||
public void whenWritingToStringWriter_thenCorrectlyWritten() {
|
||||
final StringWriter sw = new StringWriter();
|
||||
try (PrintWriter pw = new PrintWriter(sw, true)) {
|
||||
pw.print(TEST_STRING_HELLO_WORLD);
|
||||
}
|
||||
|
||||
Assert.assertEquals(sw.getBuffer().toString(), TEST_STRING_HELLO_WORLD);
|
||||
}
|
||||
|
||||
/* Example for using multiple resources */
|
||||
@Test
|
||||
public void givenStringToScanner_whenWritingToStringWriter_thenCorrectlyWritten() {
|
||||
|
||||
final StringWriter sw = new StringWriter();
|
||||
try (Scanner sc = new Scanner(TEST_STRING_HELLO_WORLD); PrintWriter pw = new PrintWriter(sw, true)) {
|
||||
while (sc.hasNext()) {
|
||||
pw.print(sc.nextLine());
|
||||
}
|
||||
}
|
||||
|
||||
Assert.assertEquals(sw.getBuffer().toString(), TEST_STRING_HELLO_WORLD);
|
||||
}
|
||||
|
||||
/* Example to show order in which the resources are closed */
|
||||
@Test
|
||||
public void whenFirstAutoClosableResourceIsinitializedFirst_thenFirstAutoClosableResourceIsReleasedFirst() throws Exception {
|
||||
try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst(); AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) {
|
||||
af.doSomething();
|
||||
as.doSomething();
|
||||
}
|
||||
Assert.assertTrue(resource1Date.after(resource2Date));
|
||||
}
|
||||
|
||||
class AutoCloseableResourcesFirst implements AutoCloseable {
|
||||
public AutoCloseableResourcesFirst() {
|
||||
System.out.println("Constructor -> AutoCloseableResources_First");
|
||||
}
|
||||
|
||||
public void doSomething() {
|
||||
System.out.println("Something -> AutoCloseableResources_First");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
System.out.println("Closed AutoCloseableResources_First");
|
||||
resource1Date = new Date();
|
||||
}
|
||||
}
|
||||
|
||||
class AutoCloseableResourcesSecond implements AutoCloseable {
|
||||
public AutoCloseableResourcesSecond() {
|
||||
System.out.println("Constructor -> AutoCloseableResources_Second");
|
||||
}
|
||||
|
||||
public void doSomething() {
|
||||
System.out.println("Something -> AutoCloseableResources_Second");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
System.out.println("Closed AutoCloseableResources_Second");
|
||||
resource2Date = new Date();
|
||||
Thread.sleep(10000);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.java8.base64;
|
||||
package com.baeldung.java8.base64;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.java8.base64;
|
||||
package com.baeldung.java8.base64;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.java8.entity;
|
||||
package com.baeldung.java8.entity;
|
||||
|
||||
public class Human {
|
||||
private String name;
|
|
@ -6,4 +6,10 @@
|
|||
- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
|
||||
- [Java - Reading a Large File Efficiently](http://www.baeldung.com/java-read-lines-large-file)
|
||||
- [Java InputStream to String](http://www.baeldung.com/convert-input-stream-to-string)
|
||||
|
||||
- [Converting between an Array and a List in Java](http://www.baeldung.com/convert-array-to-list-and-list-to-array)
|
||||
- [Converting between an Array and a Set in Java](http://www.baeldung.com/convert-array-to-set-and-set-to-array)
|
||||
- [Converting between a List and a Set in Java](http://www.baeldung.com/convert-list-to-set-and-set-to-list)
|
||||
- [Convert a Map to an Array, List or Set in Java](http://www.baeldung.com/convert-map-values-to-array-list-set)
|
||||
- [Java – Write to File](http://www.baeldung.com/java-write-to-file)
|
||||
- [Java Scanner](http://www.baeldung.com/java-scanner)
|
||||
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
|
||||
|
|
|
@ -79,7 +79,7 @@
|
|||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit-dep</artifactId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
@ -152,22 +152,22 @@
|
|||
<mysql-connector-java.version>5.1.35</mysql-connector-java.version>
|
||||
|
||||
<!-- marshalling -->
|
||||
<jackson.version>2.4.4</jackson.version>
|
||||
<jackson.version>2.5.5</jackson.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.12</org.slf4j.version>
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
|
||||
<!-- various -->
|
||||
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>18.0</guava.version>
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.4</commons-lang3.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.11</junit.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
|
||||
<httpcore.version>4.4.1</httpcore.version>
|
||||
|
|
|
@ -32,7 +32,6 @@ import com.google.common.io.ByteSource;
|
|||
import com.google.common.io.ByteStreams;
|
||||
import com.google.common.io.CharStreams;
|
||||
import com.google.common.io.Files;
|
||||
import com.google.common.io.InputSupplier;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public class JavaInputStreamToXUnitTest {
|
||||
|
@ -75,16 +74,14 @@ public class JavaInputStreamToXUnitTest {
|
|||
final String originalString = randomAlphabetic(DEFAULT_SIZE);
|
||||
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
|
||||
|
||||
final InputSupplier<InputStream> inputSupplier = new InputSupplier<InputStream>() {
|
||||
final ByteSource byteSource = new ByteSource() {
|
||||
@Override
|
||||
public final InputStream getInput() throws IOException {
|
||||
public final InputStream openStream() throws IOException {
|
||||
return inputStream;
|
||||
}
|
||||
};
|
||||
final InputSupplier<InputStreamReader> readerSupplier = CharStreams.newReaderSupplier(inputSupplier, Charsets.UTF_8);
|
||||
|
||||
// When
|
||||
final String text = CharStreams.toString(readerSupplier);
|
||||
final String text = byteSource.asCharSource(Charsets.UTF_8).read();
|
||||
|
||||
assertThat(text, equalTo(originalString));
|
||||
}
|
||||
|
|
|
@ -2,5 +2,6 @@
|
|||
|
||||
## GSON Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
### Relevant Articles:
|
||||
- [Gson Deserialization Cookbook](http://www.baeldung.com/gson-deserialization-guide)
|
||||
|
|
|
@ -53,7 +53,7 @@
|
|||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit-dep</artifactId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
@ -124,19 +124,19 @@
|
|||
<gson.version>2.3</gson.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.12</org.slf4j.version>
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
|
||||
<!-- various -->
|
||||
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>18.0</guava.version>
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.4</commons-lang3.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.11</junit.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
|
||||
<httpcore.version>4.4.1</httpcore.version>
|
||||
|
|
|
@ -9,6 +9,10 @@ public class Foo {
|
|||
this.stringValue = stringValue;
|
||||
}
|
||||
|
||||
public Foo(final String stringValue) {
|
||||
this.stringValue = stringValue;
|
||||
}
|
||||
|
||||
public Foo() {
|
||||
super();
|
||||
}
|
||||
|
@ -19,27 +23,33 @@ public class Foo {
|
|||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + intValue;
|
||||
result = prime * result + ((stringValue == null) ? 0 : stringValue.hashCode());
|
||||
result = (prime * result) + intValue;
|
||||
result = (prime * result) + ((stringValue == null) ? 0 : stringValue.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (this == obj)
|
||||
if (this == obj) {
|
||||
return true;
|
||||
if (obj == null)
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
final Foo other = (Foo) obj;
|
||||
if (intValue != other.intValue)
|
||||
if (intValue != other.intValue) {
|
||||
return false;
|
||||
}
|
||||
if (stringValue == null) {
|
||||
if (other.stringValue != null)
|
||||
if (other.stringValue != null) {
|
||||
return false;
|
||||
} else if (!stringValue.equals(other.stringValue))
|
||||
}
|
||||
} else if (!stringValue.equals(other.stringValue)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,14 @@
|
|||
package org.baeldung.gson.deserialization;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
import com.google.gson.InstanceCreator;
|
||||
|
||||
public class FooInstanceCreator implements InstanceCreator<Foo> {
|
||||
|
||||
@Override
|
||||
public Foo createInstance(Type type) {
|
||||
return new Foo("sample");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package org.baeldung.gson.deserialization;
|
||||
|
||||
public class FooWithInner {
|
||||
public int intValue;
|
||||
public String stringValue;
|
||||
public InnerFoo innerFoo;
|
||||
|
||||
public FooWithInner(int intValue, String stringValue, String name) {
|
||||
super();
|
||||
this.intValue = intValue;
|
||||
this.stringValue = stringValue;
|
||||
this.innerFoo = new InnerFoo(name);
|
||||
}
|
||||
|
||||
public class InnerFoo {
|
||||
public String name;
|
||||
|
||||
public InnerFoo(String name) {
|
||||
super();
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -12,6 +12,8 @@ import java.util.Collection;
|
|||
|
||||
import org.baeldung.gson.deserialization.Foo;
|
||||
import org.baeldung.gson.deserialization.FooDeserializerFromJsonWithDifferentFields;
|
||||
import org.baeldung.gson.deserialization.FooInstanceCreator;
|
||||
import org.baeldung.gson.deserialization.FooWithInner;
|
||||
import org.baeldung.gson.deserialization.GenericFoo;
|
||||
import org.junit.Test;
|
||||
|
||||
|
@ -108,4 +110,29 @@ public class GsonDeserializationTest {
|
|||
assertEquals(targetObject.stringValue, "seven");
|
||||
}
|
||||
|
||||
// new examples
|
||||
|
||||
@Test
|
||||
public void whenDeserializingToNestedObjects_thenCorrect() {
|
||||
final String json = "{\"intValue\":1,\"stringValue\":\"one\",\"innerFoo\":{\"name\":\"inner\"}}";
|
||||
|
||||
final FooWithInner targetObject = new Gson().fromJson(json, FooWithInner.class);
|
||||
|
||||
assertEquals(targetObject.intValue, 1);
|
||||
assertEquals(targetObject.stringValue, "one");
|
||||
assertEquals(targetObject.innerFoo.name, "inner");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeserializingUsingInstanceCreator_thenCorrect() {
|
||||
final String json = "{\"intValue\":1}";
|
||||
|
||||
final GsonBuilder gsonBldr = new GsonBuilder();
|
||||
gsonBldr.registerTypeAdapter(Foo.class, new FooInstanceCreator());
|
||||
final Foo targetObject = gsonBldr.create().fromJson(json, Foo.class);
|
||||
|
||||
assertEquals(targetObject.intValue, 1);
|
||||
assertEquals(targetObject.stringValue, "sample");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -7,7 +7,11 @@
|
|||
- [Guava Collections Cookbook](http://www.baeldung.com/guava-collections)
|
||||
- [Guava Ordering Cookbook](http://www.baeldung.com/guava-order)
|
||||
- [Guava Functional Cookbook](http://www.baeldung.com/guava-functions-predicates)
|
||||
|
||||
- [Hamcrest Collections Cookbook](http://www.baeldung.com/hamcrest-collections-arrays)
|
||||
|
||||
- [Partition a List in Java](http://www.baeldung.com/java-list-split)
|
||||
- [Filtering and Transforming Collections in Guava](http://www.baeldung.com/guava-filter-and-transform-a-collection)
|
||||
- [Guava – Join and Split Collections](http://www.baeldung.com/guava-joiner-and-splitter-tutorial)
|
||||
- [Guava – Write to File, Read from File](http://www.baeldung.com/guava-write-to-file-read-from-file)
|
||||
- [Guava – Lists](http://www.baeldung.com/guava-lists)
|
||||
- [Guava – Sets](http://www.baeldung.com/guava-sets)
|
||||
- [Guava – Maps](http://www.baeldung.com/guava-maps)
|
||||
|
|
|
@ -34,7 +34,7 @@
|
|||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit-dep</artifactId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
@ -102,19 +102,19 @@
|
|||
<mysql-connector-java.version>5.1.35</mysql-connector-java.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.12</org.slf4j.version>
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
|
||||
<!-- various -->
|
||||
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>18.0</guava.version>
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.4</commons-lang3.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.11</junit.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
|
||||
<httpcore.version>4.4.1</httpcore.version>
|
||||
|
|
|
@ -148,6 +148,15 @@ public class GuavaCollectionTypesTest {
|
|||
assertThat(intersection, containsInAnyOrder('b', 'c'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingSetSymmetricDifference_thenCorrect() {
|
||||
final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
|
||||
final Set<Character> second = ImmutableSet.of('b', 'c', 'd');
|
||||
|
||||
final Set<Character> intersection = Sets.symmetricDifference(first, second);
|
||||
assertThat(intersection, containsInAnyOrder('a', 'd'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingPowerSet_thenCorrect() {
|
||||
final Set<Character> chars = ImmutableSet.of('a', 'b');
|
||||
|
|
|
@ -0,0 +1,70 @@
|
|||
package org.baeldung.java;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class CollectionJavaPartitionUnitTest {
|
||||
|
||||
// java8 groupBy
|
||||
@Test
|
||||
public final void givenList_whenParitioningIntoNSublistsUsingGroupingBy_thenCorrect() {
|
||||
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
|
||||
|
||||
final Map<Integer, List<Integer>> groups = intList.stream().collect(Collectors.groupingBy(s -> (s - 1) / 3));
|
||||
final List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());
|
||||
|
||||
// When
|
||||
final List<Integer> lastPartition = subSets.get(2);
|
||||
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
|
||||
assertThat(subSets.size(), equalTo(3));
|
||||
assertThat(lastPartition, equalTo(expectedLastPartition));
|
||||
|
||||
// intList.add(9);
|
||||
// System.out.println(groups.values());
|
||||
}
|
||||
|
||||
// java8 partitionBy
|
||||
@Test
|
||||
public final void givenList_whenParitioningIntoSublistsUsingPartitionBy_thenCorrect() {
|
||||
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
|
||||
|
||||
final Map<Boolean, List<Integer>> groups = intList.stream().collect(Collectors.partitioningBy(s -> s > 6));
|
||||
final List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());
|
||||
|
||||
// When
|
||||
final List<Integer> lastPartition = subSets.get(1);
|
||||
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
|
||||
assertThat(subSets.size(), equalTo(2));
|
||||
assertThat(lastPartition, equalTo(expectedLastPartition));
|
||||
|
||||
// intList.add(9);
|
||||
// System.out.println(groups.values());
|
||||
}
|
||||
|
||||
// java8 split by separator
|
||||
@Test
|
||||
public final void givenList_whenSplittingBySeparator_thenCorrect() {
|
||||
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 0, 4, 5, 6, 0, 7, 8);
|
||||
|
||||
final int[] indexes = Stream.of(IntStream.of(-1), IntStream.range(0, intList.size()).filter(i -> intList.get(i) == 0), IntStream.of(intList.size())).flatMapToInt(s -> s).toArray();
|
||||
final List<List<Integer>> subSets = IntStream.range(0, indexes.length - 1).mapToObj(i -> intList.subList(indexes[i] + 1, indexes[i + 1])).collect(Collectors.toList());
|
||||
|
||||
// When
|
||||
final List<Integer> lastPartition = subSets.get(2);
|
||||
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
|
||||
assertThat(subSets.size(), equalTo(3));
|
||||
assertThat(lastPartition, equalTo(expectedLastPartition));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
=========
|
||||
|
||||
## Guava and Hamcrest Cookbooks and Examples
|
||||
|
||||
|
||||
### Relevant Articles:
|
||||
- [Guava Collections Cookbook](http://www.baeldung.com/guava-collections)
|
||||
- [Guava Ordering Cookbook](http://www.baeldung.com/guava-order)
|
||||
- [Guava Functional Cookbook](http://www.baeldung.com/guava-functions-predicates)
|
||||
- [Hamcrest Collections Cookbook](http://www.baeldung.com/hamcrest-collections-arrays)
|
||||
- [Partition a List in Java](http://www.baeldung.com/java-list-split)
|
||||
- [Guava 18: What’s New?](http://www.baeldung.com/whats-new-in-guava-18)
|
|
@ -0,0 +1,41 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>18.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.3</version>
|
||||
<configuration>
|
||||
<debug>true</debug>
|
||||
<optimize>true</optimize>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<encoding>UTF-8</encoding>
|
||||
<showDeprecation>true</showDeprecation>
|
||||
<showWarnings>true</showWarnings>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.guava.entity;
|
||||
|
||||
import com.google.common.base.MoreObjects;
|
||||
|
||||
public class Administrator extends User{
|
||||
public Administrator(long id, String name, int age) {
|
||||
super(id, name, age);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return MoreObjects.toStringHelper(this)
|
||||
.add("id", getId())
|
||||
.add("name", getName())
|
||||
.add("age", getAge())
|
||||
.toString();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.guava.entity;
|
||||
|
||||
public class Player extends User{
|
||||
public Player(long id, String name, int age) {
|
||||
super(id, name, age);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.guava.entity;
|
||||
|
||||
import com.google.common.base.MoreObjects;
|
||||
|
||||
public class User{
|
||||
private long id;
|
||||
private String name;
|
||||
private int age;
|
||||
|
||||
public User(long id, String name, int age) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return MoreObjects.toStringHelper(User.class)
|
||||
.add("id", id)
|
||||
.add("name", name)
|
||||
.add("age", age)
|
||||
.toString();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,80 @@
|
|||
package com.baeldung.guava;
|
||||
|
||||
import com.baeldung.guava.entity.User;
|
||||
import com.google.common.base.Functions;
|
||||
import com.google.common.base.Joiner;
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.collect.FluentIterable;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
|
||||
public class FluentIterableTest {
|
||||
|
||||
private static final int ADULT_AGE = 18;
|
||||
|
||||
@Test
|
||||
public void whenFilteringByAge_shouldFilterOnlyAdultUsers() throws Exception {
|
||||
List<User> users = new ArrayList<>();
|
||||
users.add(new User(1L, "John", 45));
|
||||
users.add(new User(2L, "Michael", 27));
|
||||
users.add(new User(3L, "Max", 16));
|
||||
users.add(new User(4L, "Bob", 10));
|
||||
users.add(new User(5L, "Bill", 65));
|
||||
|
||||
Predicate<User> byAge = input -> input.getAge() > ADULT_AGE;
|
||||
|
||||
List<String> results = FluentIterable.from(users)
|
||||
.filter(byAge)
|
||||
.transform(Functions.toStringFunction())
|
||||
.toList();
|
||||
|
||||
Assert.assertThat(results.size(), equalTo(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingFluentIterableFromArray_shouldContainAllUsers() throws Exception {
|
||||
User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)};
|
||||
FluentIterable<User> users = FluentIterable.of(usersArray);
|
||||
|
||||
Assert.assertThat(users.size(), equalTo(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAppendingElementsToFluentIterable_shouldContainAllUsers() throws Exception {
|
||||
User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)};
|
||||
|
||||
FluentIterable<User> users = FluentIterable.of(usersArray).append(
|
||||
new User(3L, "Bob", 23),
|
||||
new User(4L, "Bill", 17)
|
||||
);
|
||||
|
||||
Assert.assertThat(users.size(), equalTo(4));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAppendingListToFluentIterable_shouldContainAllUsers() throws Exception {
|
||||
User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)};
|
||||
|
||||
List<User> usersList = new ArrayList<>();
|
||||
usersList.add(new User(3L, "David", 32));
|
||||
|
||||
FluentIterable<User> users = FluentIterable.of(usersArray).append(usersList);
|
||||
|
||||
Assert.assertThat(users.size(), equalTo(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoiningFluentIterableElements_shouldOutputAllUsers() throws Exception {
|
||||
User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)};
|
||||
|
||||
FluentIterable<User> users = FluentIterable.of(usersArray);
|
||||
|
||||
Assert.assertThat(users.join(Joiner.on("; ")),
|
||||
equalTo("User{id=1, name=John, age=45}; User{id=2, name=Max, age=15}"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.guava;
|
||||
|
||||
import com.google.common.hash.HashCode;
|
||||
import com.google.common.hash.Hashing;
|
||||
import com.google.common.net.InetAddresses;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
|
||||
public class GuavaMiscUtilsTest {
|
||||
@Test
|
||||
public void whenHashingData_shouldReturnCorrectHashCode() throws Exception {
|
||||
int receivedData = 123;
|
||||
|
||||
HashCode hashCode = Hashing.crc32c().hashInt(receivedData);
|
||||
Assert.assertThat(hashCode.toString(), equalTo("495be649"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDecrementingIpAddress_shouldReturnOneLessIpAddress() throws Exception {
|
||||
InetAddress address = InetAddress.getByName("127.0.0.5");
|
||||
InetAddress decrementedAddress = InetAddresses.decrement(address);
|
||||
|
||||
Assert.assertThat(decrementedAddress.toString(), equalTo("/127.0.0.4"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenExecutingRunnableInThread_shouldLogThreadExecution() throws Exception {
|
||||
ConcurrentHashMap<String, Boolean> threadExecutions = new ConcurrentHashMap<>();
|
||||
Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true);
|
||||
|
||||
Thread t = new Thread(logThreadRun);
|
||||
t.run();
|
||||
|
||||
Assert.assertTrue(threadExecutions.get("main"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
package com.baeldung.guava;
|
||||
|
||||
import com.google.common.util.concurrent.ListeningExecutorService;
|
||||
import com.google.common.util.concurrent.MoreExecutors;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.*;
|
||||
|
||||
public class MoreExecutorsTest {
|
||||
@Test
|
||||
public void whenExecutingRunnableInThreadPool_shouldLogAllThreadsExecutions() throws Exception {
|
||||
ConcurrentHashMap<String, Boolean> threadExecutions = new ConcurrentHashMap<>();
|
||||
|
||||
Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true);
|
||||
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||
executorService.submit(logThreadRun);
|
||||
executorService.submit(logThreadRun);
|
||||
executorService.shutdown();
|
||||
|
||||
executorService.awaitTermination(100, TimeUnit.MILLISECONDS);
|
||||
|
||||
Assert.assertTrue(threadExecutions.get("pool-1-thread-1"));
|
||||
Assert.assertTrue(threadExecutions.get("pool-1-thread-2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenExecutingRunnableInDirectExecutor_shouldLogThreadExecution() throws Exception {
|
||||
ConcurrentHashMap<String, Boolean> threadExecutions = new ConcurrentHashMap<>();
|
||||
|
||||
Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true);
|
||||
|
||||
Executor executor = MoreExecutors.directExecutor();
|
||||
executor.execute(logThreadRun);
|
||||
|
||||
Assert.assertTrue(threadExecutions.get("main"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenExecutingRunnableInListeningExecutor_shouldLogThreadExecution() throws Exception {
|
||||
ConcurrentHashMap<String, Boolean> threadExecutions = new ConcurrentHashMap<>();
|
||||
|
||||
Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true);
|
||||
|
||||
ListeningExecutorService executor = MoreExecutors.newDirectExecutorService();
|
||||
executor.execute(logThreadRun);
|
||||
|
||||
Assert.assertTrue(threadExecutions.get("main"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.guava;
|
||||
|
||||
import com.baeldung.guava.entity.Administrator;
|
||||
import com.baeldung.guava.entity.Player;
|
||||
import com.baeldung.guava.entity.User;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
|
||||
public class MoreObjectsTest {
|
||||
|
||||
@Test
|
||||
public void whenToString_shouldIncludeAllFields() throws Exception {
|
||||
User user = new User(12L, "John Doe", 25);
|
||||
|
||||
Assert.assertThat(user.toString(), equalTo("User{id=12, name=John Doe, age=25}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPlayerToString_shouldCallParentToString() throws Exception {
|
||||
User user = new Player(12L, "John Doe", 25);
|
||||
|
||||
Assert.assertThat(user.toString(), equalTo("User{id=12, name=John Doe, age=25}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAdministratorToString_shouldExecuteAdministratorToString() throws Exception {
|
||||
User user = new Administrator(12L, "John Doe", 25);
|
||||
|
||||
Assert.assertThat(user.toString(), equalTo("Administrator{id=12, name=John Doe, age=25}"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>19.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-all</artifactId>
|
||||
<version>1.3</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.3</version>
|
||||
<configuration>
|
||||
<debug>true</debug>
|
||||
<optimize>true</optimize>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<encoding>UTF-8</encoding>
|
||||
<showDeprecation>true</showDeprecation>
|
||||
<showWarnings>true</showWarnings>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.guava.entity;
|
||||
|
||||
import com.google.common.base.MoreObjects;
|
||||
|
||||
public class User{
|
||||
private long id;
|
||||
private String name;
|
||||
private int age;
|
||||
|
||||
public User(long id, String name, int age) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return MoreObjects.toStringHelper(User.class)
|
||||
.add("id", id)
|
||||
.add("name", name)
|
||||
.add("age", age)
|
||||
.toString();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.guava;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class CharMatcherTest {
|
||||
@Test
|
||||
public void whenMatchingLetterOrString_ShouldReturnTrueForCorrectString() throws Exception {
|
||||
String inputString = "someString789";
|
||||
boolean result = CharMatcher.javaLetterOrDigit().matchesAllOf(inputString);
|
||||
|
||||
assertTrue(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollapsingString_ShouldReturnStringWithDashesInsteadOfWhitespaces() throws Exception {
|
||||
String inputPhoneNumber = "8 123 456 123";
|
||||
String result = CharMatcher.whitespace().collapseFrom(inputPhoneNumber, '-');
|
||||
|
||||
assertEquals("8-123-456-123", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCountingDigitsInString_ShouldReturnActualCountOfDigits() throws Exception {
|
||||
String inputPhoneNumber = "8 123 456 123";
|
||||
int result = CharMatcher.digit().countIn(inputPhoneNumber);
|
||||
|
||||
assertEquals(10, result);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,88 @@
|
|||
package com.baeldung.guava;
|
||||
|
||||
import com.google.common.base.Throwables;
|
||||
import com.google.common.collect.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
|
||||
import static org.hamcrest.core.AnyOf.anyOf;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class GuavaMiscUtilsTest {
|
||||
|
||||
@Test
|
||||
public void whenGettingLazyStackTrace_ListShouldBeReturned() throws Exception {
|
||||
IllegalArgumentException e = new IllegalArgumentException("Some argument is incorrect");
|
||||
|
||||
List<StackTraceElement> stackTraceElements = Throwables.lazyStackTrace(e);
|
||||
|
||||
assertTrue(stackTraceElements.size() > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void multisetShouldCountHitsOfMultipleDuplicateObjects() throws Exception {
|
||||
List<String> userNames = Arrays.asList("David", "Eugene", "Alex", "Alex", "David", "David", "David");
|
||||
|
||||
Multiset<String> userNamesMultiset = HashMultiset.create(userNames);
|
||||
|
||||
assertEquals(7, userNamesMultiset.size());
|
||||
assertEquals(4, userNamesMultiset.count("David"));
|
||||
assertEquals(2, userNamesMultiset.count("Alex"));
|
||||
assertEquals(1, userNamesMultiset.count("Eugene"));
|
||||
assertThat(userNamesMultiset.elementSet(), anyOf(containsInAnyOrder("Alex", "David", "Eugene")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddingNewConnectedRange_RangesShouldBeMerged() throws Exception {
|
||||
RangeSet<Integer> rangeSet = TreeRangeSet.create();
|
||||
|
||||
rangeSet.add(Range.closed(1, 10));
|
||||
rangeSet.add(Range.closed(5, 15));
|
||||
rangeSet.add(Range.closedOpen(10, 17));
|
||||
|
||||
assertTrue(rangeSet.encloses(Range.closedOpen(1, 17)));
|
||||
assertTrue(rangeSet.encloses(Range.closed(2, 3)));
|
||||
assertTrue(rangeSet.contains(15));
|
||||
assertFalse(rangeSet.contains(17));
|
||||
assertEquals(1, rangeSet.asDescendingSetOfRanges().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cartesianProductShouldReturnAllPossibleCombinations() throws Exception {
|
||||
List<String> first = Lists.newArrayList("value1", "value2");
|
||||
List<String> second = Lists.newArrayList("value3", "value4");
|
||||
|
||||
List<List<String>> cartesianProduct = Lists.cartesianProduct(first, second);
|
||||
|
||||
List<String> pair1 = Lists.newArrayList("value2", "value3");
|
||||
List<String> pair2 = Lists.newArrayList("value2", "value4");
|
||||
List<String> pair3 = Lists.newArrayList("value1", "value3");
|
||||
List<String> pair4 = Lists.newArrayList("value1", "value4");
|
||||
|
||||
assertThat(cartesianProduct, anyOf(containsInAnyOrder(pair1, pair2, pair3, pair4)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void multisetShouldRemoveOccurrencesOfSpecifiedObjects() throws Exception {
|
||||
Multiset<String> multisetToModify = HashMultiset.create();
|
||||
Multiset<String> occurrencesToRemove = HashMultiset.create();
|
||||
|
||||
multisetToModify.add("John");
|
||||
multisetToModify.add("Max");
|
||||
multisetToModify.add("Alex");
|
||||
|
||||
occurrencesToRemove.add("Alex");
|
||||
occurrencesToRemove.add("John");
|
||||
|
||||
Multisets.removeOccurrences(multisetToModify, occurrencesToRemove);
|
||||
|
||||
assertEquals(1, multisetToModify.size());
|
||||
assertTrue(multisetToModify.contains("Max"));
|
||||
assertFalse(multisetToModify.contains("John"));
|
||||
assertFalse(multisetToModify.contains("Alex"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.guava;
|
||||
|
||||
import com.google.common.hash.HashCode;
|
||||
import com.google.common.hash.HashFunction;
|
||||
import com.google.common.hash.Hashing;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class HashingTest {
|
||||
@Test
|
||||
public void whenHashingInSha384_hashFunctionShouldBeReturned() throws Exception {
|
||||
int inputData = 15;
|
||||
|
||||
HashFunction hashFunction = Hashing.sha384();
|
||||
HashCode hashCode = hashFunction.hashInt(inputData);
|
||||
|
||||
assertEquals("0904b6277381dcfbdddd6b6c66e4e3e8f83d4690718d8e6f272c891f24773a12feaf8c449fa6e42240a621b2b5e3cda8",
|
||||
hashCode.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConcatenatingHashFunction_concatenatedHashShouldBeReturned() throws Exception {
|
||||
int inputData = 15;
|
||||
|
||||
HashFunction hashFunction = Hashing.concatenating(Hashing.crc32(), Hashing.crc32());
|
||||
HashFunction crc32Function = Hashing.crc32();
|
||||
|
||||
HashCode hashCode = hashFunction.hashInt(inputData);
|
||||
HashCode crc32HashCode = crc32Function.hashInt(inputData);
|
||||
|
||||
assertEquals(crc32HashCode.toString() + crc32HashCode.toString(), hashCode.toString());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.guava;
|
||||
|
||||
import com.google.common.reflect.TypeToken;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class TypeTokenTest {
|
||||
@Test
|
||||
public void whenCheckingIsAssignableFrom_shouldReturnTrueEvenIfGenericIsSpecified() throws Exception {
|
||||
ArrayList<String> stringList = new ArrayList<>();
|
||||
ArrayList<Integer> intList = new ArrayList<>();
|
||||
boolean isAssignableFrom = stringList.getClass().isAssignableFrom(intList.getClass());
|
||||
|
||||
assertTrue(isAssignableFrom);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingIsSupertypeOf_shouldReturnFalseIfGenericIsSpecified() throws Exception {
|
||||
TypeToken<ArrayList<String>> listString = new TypeToken<ArrayList<String>>() {
|
||||
};
|
||||
TypeToken<ArrayList<Integer>> integerString = new TypeToken<ArrayList<Integer>>() {
|
||||
};
|
||||
|
||||
boolean isSupertypeOf = listString.isSupertypeOf(integerString);
|
||||
|
||||
assertFalse(isSupertypeOf);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingIsSubtypeOf_shouldReturnTrueIfClassIsExtendedFrom() throws Exception {
|
||||
TypeToken<ArrayList<String>> stringList = new TypeToken<ArrayList<String>>() {
|
||||
};
|
||||
TypeToken<List> list = new TypeToken<List>() {
|
||||
};
|
||||
|
||||
boolean isSubtypeOf = stringList.isSubtypeOf(list);
|
||||
|
||||
assertTrue(isSubtypeOf);
|
||||
}
|
||||
}
|
|
@ -19,9 +19,9 @@
|
|||
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
|
||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5">
|
||||
<attributes>
|
||||
<attribute name="owner.project.facets" value="java"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="output" path="target/classes"/>
|
||||
|
|
|
@ -171,41 +171,37 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<java-version>1.7</java-version>
|
||||
<java-version>1.8</java-version>
|
||||
<!-- Spring -->
|
||||
<org.springframework.version>4.1.5.RELEASE</org.springframework.version>
|
||||
<org.springframework.security.version>3.2.5.RELEASE</org.springframework.security.version>
|
||||
<org.springframework.version>4.2.4.RELEASE</org.springframework.version>
|
||||
<org.springframework.security.version>4.0.3.RELEASE</org.springframework.security.version>
|
||||
|
||||
<org.aspectj-version>1.8.1</org.aspectj-version>
|
||||
<javax.servlet.jsp-api.version>2.3.2-b01</javax.servlet.jsp-api.version>
|
||||
|
||||
<!-- Spring -->
|
||||
<org.springframework.version>4.1.5.RELEASE</org.springframework.version>
|
||||
<org.springframework.security.version>3.2.5.RELEASE</org.springframework.security.version>
|
||||
|
||||
<!-- persistence -->
|
||||
<hibernate.version>4.3.10.Final</hibernate.version>
|
||||
<mysql-connector-java.version>5.1.35</mysql-connector-java.version>
|
||||
<spring-data-jpa.version>1.7.2.RELEASE</spring-data-jpa.version>
|
||||
<hibernate.version>4.3.11.Final</hibernate.version>
|
||||
<mysql-connector-java.version>5.1.37</mysql-connector-java.version>
|
||||
<spring-data-jpa.version>1.9.2.RELEASE</spring-data-jpa.version>
|
||||
|
||||
<!-- marshalling -->
|
||||
|
||||
<jackson.version>2.4.4</jackson.version>
|
||||
<jackson.version>2.6.4</jackson.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.12</org.slf4j.version>
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
|
||||
<!-- various -->
|
||||
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
|
||||
<hibernate-validator.version>5.2.2.Final</hibernate-validator.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>18.0</guava.version>
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.4</commons-lang3.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.11</junit.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
|
||||
<httpcore.version>4.4.1</httpcore.version>
|
||||
|
|
|
@ -2,10 +2,10 @@
|
|||
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
|
||||
xmlns:mvc="http://www.springframework.org/schema/mvc"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
|
||||
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
|
||||
http://www.springframework.org/schema/mvc
|
||||
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
|
||||
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd"
|
||||
>
|
||||
<http use-expressions="true">
|
||||
<intercept-url pattern="/login*" access="permitAll"/>
|
||||
|
@ -21,7 +21,7 @@
|
|||
<form-login login-page='/login.html' authentication-failure-url="/login.html?error=true" authentication-success-handler-ref="myAuthenticationSuccessHandler"
|
||||
default-target-url="home.html"/>
|
||||
<session-management invalid-session-url="/invalidSession.html" session-fixation-protection="none"/>
|
||||
<logout invalidate-session="false" logout-success-url="/logout.html?logSucc=true" logout-url="/j_spring_security_logout" delete-cookies="JSESSIONID"/>
|
||||
<logout invalidate-session="false" logout-success-url="/logout.html?logSucc=true" delete-cookies="JSESSIONID"/>
|
||||
|
||||
</http>
|
||||
|
||||
|
|
|
@ -41,15 +41,15 @@
|
|||
<body>
|
||||
<h1><spring:message code="label.form.loginTitle"></spring:message></h1>
|
||||
|
||||
<form name='f' action="j_spring_security_check" method='POST' onsubmit="return validate();">
|
||||
<form name='f' action="login" method='POST' onsubmit="return validate();">
|
||||
<table>
|
||||
<tr>
|
||||
<td><label><spring:message code="label.form.loginEmail"></spring:message></label></td>
|
||||
<td><input type='text' name='j_username' value=''></td>
|
||||
<td><input type='text' name='username' value=''></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><label><spring:message code="label.form.loginPass"></spring:message></label></td>
|
||||
<td><input type='password' name='j_password' /></td>
|
||||
<td><input type='password' name='password' /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><input name="submit" type="submit" value=<spring:message code="label.form.submit"></spring:message> /></td>
|
||||
|
|
|
@ -5,12 +5,15 @@
|
|||
|
||||
### Relevant Articles:
|
||||
|
||||
- [HttpClient 4 – Send Custom Cookie](http://www.baeldung.com/httpclient-4-cookies)
|
||||
- [HttpClient 4 – Get the Status Code](http://www.baeldung.com/httpclient-status-code)
|
||||
- [HttpClient 4 – Cancel / Abort Request](http://www.baeldung.com/httpclient-cancel-request)
|
||||
- [HttpClient 4 – Send Custom Cookie](http://www.baeldung.com/httpclient-4-cookies)
|
||||
- [HttpClient 4 – Get the Status Code](http://www.baeldung.com/httpclient-status-code)
|
||||
- [HttpClient 4 – Cancel / Abort Request](http://www.baeldung.com/httpclient-cancel-request)
|
||||
- [HttpClient 4 Cookbook](http://www.baeldung.com/httpclient4)
|
||||
- [Unshorten URLs with HttpClient](http://www.baeldung.com/unshorten-url-httpclient)
|
||||
- [HttpClient with SSL](http://www.baeldung.com/httpclient-ssl)
|
||||
- [HttpClient 4 – Follow Redirects for POST](http://www.baeldung.com/httpclient-redirect-on-http-post)
|
||||
- [HttpClient – Set Custom Header](http://www.baeldung.com/httpclient-custom-http-header)
|
||||
- [HttpClient 4 – Follow Redirects for POST](http://www.baeldung.com/httpclient-redirect-on-http-post)
|
||||
- [HttpClient – Set Custom Header](http://www.baeldung.com/httpclient-custom-http-header)
|
||||
- [HttpClient Basic Authentication](http://www.baeldung.com/httpclient-4-basic-authentication)
|
||||
- [Multipart Upload with HttpClient 4](http://www.baeldung.com/httpclient-multipart-upload)
|
||||
- [HttpAsyncClient Tutorial](http://www.baeldung.com/httpasyncclient-tutorial)
|
||||
- [HttpClient 4 Tutorial](http://www.baeldung.com/httpclient-guide)
|
||||
|
|
|
@ -89,7 +89,7 @@
|
|||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit-dep</artifactId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
@ -157,19 +157,19 @@
|
|||
<mysql-connector-java.version>5.1.35</mysql-connector-java.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.12</org.slf4j.version>
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
|
||||
<!-- various -->
|
||||
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>18.0</guava.version>
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.4</commons-lang3.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.11</junit.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
|
||||
<httpcore.version>4.4.1</httpcore.version>
|
||||
|
|
|
@ -4,9 +4,15 @@
|
|||
|
||||
### Relevant Articles:
|
||||
- [Jackson Ignore Properties on Marshalling](http://www.baeldung.com/jackson-ignore-properties-on-serialization)
|
||||
- [Jackson – Unmarshall to Collection/Array](http://www.baeldung.com/jackson-collection-array)
|
||||
- [Jackson – Unmarshall to Collection/Array](http://www.baeldung.com/jackson-collection-array)
|
||||
- [Jackson Unmarshalling json with Unknown Properties](http://www.baeldung.com/jackson-deserialize-json-unknown-properties)
|
||||
- [Jackson – Custom Serializer](http://www.baeldung.com/jackson-custom-serialization)
|
||||
- [Jackson – Custom Deserializer](http://www.baeldung.com/jackson-deserialization)
|
||||
|
||||
|
||||
- [Jackson – Custom Serializer](http://www.baeldung.com/jackson-custom-serialization)
|
||||
- [Jackson – Custom Deserializer](http://www.baeldung.com/jackson-deserialization)
|
||||
- [Jackson Exceptions – Problems and Solutions](http://www.baeldung.com/jackson-exception)
|
||||
- [Jackson Date](http://www.baeldung.com/jackson-serialize-dates)
|
||||
- [Jackson – Bidirectional Relationships](http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion)
|
||||
- [Jackson JSON Tutorial](http://www.baeldung.com/jackson)
|
||||
- [Jackson – Working with Maps and nulls](http://www.baeldung.com/jackson-map-null-values-or-null-key)
|
||||
- [Jackson – Decide What Fields Get Serialized/Deserializaed](http://www.baeldung.com/jackson-field-serializable-deserializable-or-not)
|
||||
- [A Guide to Jackson Annotations](http://www.baeldung.com/jackson-annotations)
|
||||
- [Working with Tree Model Nodes in Jackson](http://www.baeldung.com/jackson-json-node-tree-model)
|
||||
|
|
|
@ -72,7 +72,7 @@
|
|||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit-dep</artifactId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
@ -140,22 +140,22 @@
|
|||
<mysql-connector-java.version>5.1.35</mysql-connector-java.version>
|
||||
|
||||
<!-- marshalling -->
|
||||
<jackson.version>2.4.4</jackson.version>
|
||||
<jackson.version>2.7.1-1</jackson.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.12</org.slf4j.version>
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
|
||||
<!-- various -->
|
||||
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>18.0</guava.version>
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.4</commons-lang3.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.11</junit.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
|
||||
<httpcore.version>4.4.1</httpcore.version>
|
||||
|
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"name":
|
||||
{
|
||||
"first": "Tatu",
|
||||
"last": "Saloranta"
|
||||
},
|
||||
|
||||
"title": "Jackson founder",
|
||||
"company": "FasterXML"
|
||||
}
|
|
@ -12,7 +12,7 @@ import com.fasterxml.jackson.databind.JsonDeserializer;
|
|||
|
||||
public class CustomDateDeserializer extends JsonDeserializer<Date> {
|
||||
|
||||
private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
|
||||
private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
|
||||
|
||||
@Override
|
||||
public Date deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException {
|
||||
|
|
|
@ -11,7 +11,7 @@ import com.fasterxml.jackson.databind.SerializerProvider;
|
|||
|
||||
public class CustomDateSerializer extends JsonSerializer<Date> {
|
||||
|
||||
private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
|
||||
private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
|
||||
|
||||
@Override
|
||||
public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException {
|
||||
|
|
|
@ -0,0 +1,41 @@
|
|||
package org.baeldung.jackson.dynamicIgnore;
|
||||
|
||||
|
||||
public class Address implements Hidable {
|
||||
private String city;
|
||||
private String country;
|
||||
private boolean hidden;
|
||||
|
||||
public Address(final String city, final String country, final boolean hidden) {
|
||||
super();
|
||||
this.city = city;
|
||||
this.country = country;
|
||||
this.hidden = hidden;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(final String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(final String country) {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHidden() {
|
||||
return hidden;
|
||||
}
|
||||
|
||||
public void setHidden(final boolean hidden) {
|
||||
this.hidden = hidden;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package org.baeldung.jackson.dynamicIgnore;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
|
||||
@JsonIgnoreProperties("hidden")
|
||||
public interface Hidable {
|
||||
boolean isHidden();
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package org.baeldung.jackson.dynamicIgnore;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
|
||||
public class HidableSerializer extends JsonSerializer<Hidable> {
|
||||
|
||||
private JsonSerializer<Object> defaultSerializer;
|
||||
|
||||
public HidableSerializer(final JsonSerializer<Object> serializer) {
|
||||
defaultSerializer = serializer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(final Hidable value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {
|
||||
if (value.isHidden())
|
||||
return;
|
||||
defaultSerializer.serialize(value, jgen, provider);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty(final SerializerProvider provider, final Hidable value) {
|
||||
return (value == null || value.isHidden());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package org.baeldung.jackson.dynamicIgnore;
|
||||
|
||||
|
||||
public class Person implements Hidable {
|
||||
private String name;
|
||||
private Address address;
|
||||
private boolean hidden;
|
||||
|
||||
public Person(final String name, final Address address, final boolean hidden) {
|
||||
super();
|
||||
this.name = name;
|
||||
this.address = address;
|
||||
this.hidden = hidden;
|
||||
}
|
||||
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(final Address address) {
|
||||
this.address = address;
|
||||
}
|
||||
@Override
|
||||
public boolean isHidden() {
|
||||
return hidden;
|
||||
}
|
||||
|
||||
public void setHidden(final boolean hidden) {
|
||||
this.hidden = hidden;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package org.baeldung.jackson.node;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class ExampleStructure {
|
||||
private static ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
static JsonNode getExampleRoot() throws IOException {
|
||||
InputStream exampleInput = ExampleStructure.class.getClassLoader().getResourceAsStream("node_example.json");
|
||||
JsonNode rootNode = mapper.readTree(exampleInput);
|
||||
return rootNode;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package org.baeldung.jackson.node;
|
||||
|
||||
public class NodeBean {
|
||||
private int id;
|
||||
private String name;
|
||||
|
||||
public NodeBean() {
|
||||
}
|
||||
|
||||
public NodeBean(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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,103 @@
|
|||
package org.baeldung.jackson.node;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
public class NodeOperationTest {
|
||||
private static ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
public void givenAnObject_whenConvertingIntoNode_thenCorrect() {
|
||||
final NodeBean fromValue = new NodeBean(2016, "baeldung.com");
|
||||
|
||||
final JsonNode node = mapper.valueToTree(fromValue);
|
||||
|
||||
assertEquals(2016, node.get("id").intValue());
|
||||
assertEquals("baeldung.com", node.get("name").textValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANode_whenWritingOutAsAJsonString_thenCorrect() throws IOException {
|
||||
final String pathToTestFile = "node_to_json_test.json";
|
||||
final char[] characterBuffer = new char[50];
|
||||
|
||||
final JsonNode node = mapper.createObjectNode();
|
||||
((ObjectNode) node).put("id", 2016);
|
||||
((ObjectNode) node).put("name", "baeldung.com");
|
||||
|
||||
try (FileWriter outputStream = new FileWriter(pathToTestFile)) {
|
||||
mapper.writeValue(outputStream, node);
|
||||
}
|
||||
|
||||
try (FileReader inputStreamForAssertion = new FileReader(pathToTestFile)) {
|
||||
inputStreamForAssertion.read(characterBuffer);
|
||||
}
|
||||
final String textContentOfTestFile = new String(characterBuffer);
|
||||
|
||||
assertThat(textContentOfTestFile, containsString("2016"));
|
||||
assertThat(textContentOfTestFile, containsString("baeldung.com"));
|
||||
|
||||
Files.delete(Paths.get(pathToTestFile));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANode_whenConvertingIntoAnObject_thenCorrect() throws JsonProcessingException {
|
||||
final JsonNode node = mapper.createObjectNode();
|
||||
((ObjectNode) node).put("id", 2016);
|
||||
((ObjectNode) node).put("name", "baeldung.com");
|
||||
|
||||
final NodeBean toValue = mapper.treeToValue(node, NodeBean.class);
|
||||
|
||||
assertEquals(2016, toValue.getId());
|
||||
assertEquals("baeldung.com", toValue.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANode_whenAddingIntoATree_thenCorrect() throws IOException {
|
||||
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
||||
final ObjectNode addedNode = ((ObjectNode) rootNode).putObject("address");
|
||||
addedNode.put("city", "Seattle").put("state", "Washington").put("country", "United States");
|
||||
|
||||
assertFalse(rootNode.path("address").isMissingNode());
|
||||
assertEquals("Seattle", rootNode.path("address").path("city").textValue());
|
||||
assertEquals("Washington", rootNode.path("address").path("state").textValue());
|
||||
assertEquals("United States", rootNode.path("address").path("country").textValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANode_whenModifyingIt_thenCorrect() throws IOException {
|
||||
final String newString = "{\"nick\": \"cowtowncoder\"}";
|
||||
final JsonNode newNode = mapper.readTree(newString);
|
||||
|
||||
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
||||
((ObjectNode) rootNode).set("name", newNode);
|
||||
|
||||
assertFalse(rootNode.path("name").path("nick").isMissingNode());
|
||||
assertEquals("cowtowncoder", rootNode.path("name").path("nick").textValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANode_whenRemovingFromATree_thenCorrect() throws IOException {
|
||||
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
||||
((ObjectNode) rootNode).remove("company");
|
||||
|
||||
assertTrue(rootNode.path("company").isMissingNode());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,100 @@
|
|||
package org.baeldung.jackson.test;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.baeldung.jackson.dynamicIgnore.Address;
|
||||
import org.baeldung.jackson.dynamicIgnore.Hidable;
|
||||
import org.baeldung.jackson.dynamicIgnore.HidableSerializer;
|
||||
import org.baeldung.jackson.dynamicIgnore.Person;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.BeanDescription;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationConfig;
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
|
||||
|
||||
public class JacksonDynamicIgnoreTest {
|
||||
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
mapper.setSerializationInclusion(Include.NON_EMPTY);
|
||||
mapper.registerModule(new SimpleModule() {
|
||||
@Override
|
||||
public void setupModule(final SetupContext context) {
|
||||
super.setupModule(context);
|
||||
context.addBeanSerializerModifier(new BeanSerializerModifier() {
|
||||
@Override
|
||||
public JsonSerializer<?> modifySerializer(final SerializationConfig config, final BeanDescription beanDesc, final JsonSerializer<?> serializer) {
|
||||
if (Hidable.class.isAssignableFrom(beanDesc.getBeanClass())) {
|
||||
return new HidableSerializer((JsonSerializer<Object>) serializer);
|
||||
}
|
||||
return serializer;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNotHidden_thenCorrect() throws JsonProcessingException {
|
||||
final Address ad = new Address("ny", "usa", false);
|
||||
final Person person = new Person("john", ad, false);
|
||||
final String result = mapper.writeValueAsString(person);
|
||||
|
||||
assertTrue(result.contains("name"));
|
||||
assertTrue(result.contains("john"));
|
||||
assertTrue(result.contains("address"));
|
||||
assertTrue(result.contains("usa"));
|
||||
|
||||
System.out.println("Not Hidden = " + result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddressHidden_thenCorrect() throws JsonProcessingException {
|
||||
final Address ad = new Address("ny", "usa", true);
|
||||
final Person person = new Person("john", ad, false);
|
||||
final String result = mapper.writeValueAsString(person);
|
||||
|
||||
assertTrue(result.contains("name"));
|
||||
assertTrue(result.contains("john"));
|
||||
assertFalse(result.contains("address"));
|
||||
assertFalse(result.contains("usa"));
|
||||
|
||||
System.out.println("Address Hidden = " + result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAllHidden_thenCorrect() throws JsonProcessingException {
|
||||
final Address ad = new Address("ny", "usa", false);
|
||||
final Person person = new Person("john", ad, true);
|
||||
final String result = mapper.writeValueAsString(person);
|
||||
|
||||
assertTrue(result.length() == 0);
|
||||
|
||||
System.out.println("All Hidden = " + result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSerializeList_thenCorrect() throws JsonProcessingException {
|
||||
final Address ad1 = new Address("tokyo", "jp", true);
|
||||
final Address ad2 = new Address("london", "uk", false);
|
||||
final Address ad3 = new Address("ny", "usa", false);
|
||||
final Person p1 = new Person("john", ad1, false);
|
||||
final Person p2 = new Person("tom", ad2, true);
|
||||
final Person p3 = new Person("adam", ad3, false);
|
||||
|
||||
final String result = mapper.writeValueAsString(Arrays.asList(p1, p2, p3));
|
||||
|
||||
System.out.println(result);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
|
@ -0,0 +1,7 @@
|
|||
=========
|
||||
|
||||
## Mockito Mocks into Spring Beans
|
||||
|
||||
|
||||
### Relevant Articles:
|
||||
- [Injecting Mockito Mocks into Spring Beans](http://www.baeldung.com/injecting-mocks-in-spring)
|
|
@ -0,0 +1,54 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>mockito-mocks-spring-beans</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>mocks</name>
|
||||
<description>Injecting Mockito Mocks into Spring Beans</description>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.3.1.RELEASE</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<version>1.3.1.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<version>1.3.1.RELEASE</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-all</artifactId>
|
||||
<version>1.10.19</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class MocksApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(MocksApplication.class, args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class NameService {
|
||||
public String getUserName(String id) {
|
||||
return "Real user name";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class UserService {
|
||||
|
||||
private NameService nameService;
|
||||
|
||||
@Autowired
|
||||
public UserService(NameService nameService) {
|
||||
this.nameService = nameService;
|
||||
}
|
||||
|
||||
public String getUserName(String id) {
|
||||
return nameService.getUserName(id);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
|
||||
@Profile("test")
|
||||
@Configuration
|
||||
public class NameServiceTestConfiguration {
|
||||
@Bean
|
||||
@Primary
|
||||
public NameService nameService() {
|
||||
return Mockito.mock(NameService.class);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.SpringApplicationConfiguration;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
@ActiveProfiles("test")
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringApplicationConfiguration(classes = MocksApplication.class)
|
||||
public class UserServiceTest {
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Autowired
|
||||
private NameService nameService;
|
||||
|
||||
@Test
|
||||
public void whenUserIdIsProvided_thenRetrievedNameIsCorrect() {
|
||||
Mockito.when(nameService.getUserName("SomeId")).thenReturn("Mock user name");
|
||||
|
||||
String testName = userService.getUserName("SomeId");
|
||||
|
||||
Assert.assertEquals("Mock user name", testName);
|
||||
}
|
||||
}
|
|
@ -6,4 +6,5 @@
|
|||
### Relevant Articles:
|
||||
- [Mockito Verify Cookbook](http://www.baeldung.com/mockito-verify)
|
||||
- [Mockito When/Then Cookbook](http://www.baeldung.com/mockito-behavior)
|
||||
|
||||
- [Mockito – Using Spies](http://www.baeldung.com/mockito-spy)
|
||||
- [Mockito – @Mock, @Spy, @Captor and @InjectMocks](http://www.baeldung.com/mockito-annotations)
|
||||
|
|
|
@ -28,7 +28,7 @@
|
|||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit-dep</artifactId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
@ -96,19 +96,19 @@
|
|||
<mysql-connector-java.version>5.1.35</mysql-connector-java.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.12</org.slf4j.version>
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
|
||||
<!-- various -->
|
||||
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>18.0</guava.version>
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.4</commons-lang3.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.11</junit.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
|
||||
<httpcore.version>4.4.1</httpcore.version>
|
||||
|
|
|
@ -0,0 +1,102 @@
|
|||
#%RAML 0.8
|
||||
title: Baeldung Foo REST Services API
|
||||
version: v1
|
||||
protocols: [ HTTPS ]
|
||||
baseUri: http://rest-api.baeldung.com/api/{version}
|
||||
mediaType: application/json
|
||||
securitySchemes:
|
||||
- basicAuth:
|
||||
description: Each request must contain the headers necessary for
|
||||
basic authentication
|
||||
type: Basic Authentication
|
||||
describedBy:
|
||||
headers:
|
||||
Authorization:
|
||||
description: Used to send the Base64 encoded "username:password"
|
||||
credentials
|
||||
type: string
|
||||
responses:
|
||||
401:
|
||||
description: |
|
||||
Unauthorized. Either the provided username and password
|
||||
combination is invalid, or the user is not allowed to access
|
||||
the content provided by the requested URL.
|
||||
|
||||
schemas:
|
||||
- foo: !include foo.json
|
||||
- foos: !include foos.json
|
||||
- error: !include error.json
|
||||
|
||||
/foos:
|
||||
get:
|
||||
description: List all Foos matching query criteria, if provided;
|
||||
otherwise list all Foos
|
||||
queryParameters:
|
||||
name:
|
||||
type: string
|
||||
required: false
|
||||
ownerName:
|
||||
type: string
|
||||
required: false
|
||||
responses:
|
||||
200:
|
||||
body:
|
||||
application/json:
|
||||
schema: foos
|
||||
example: !include foos-example.json
|
||||
post:
|
||||
description: Create a new Foo
|
||||
body:
|
||||
application/json:
|
||||
schema: foo
|
||||
example: foo-example.json
|
||||
responses:
|
||||
201:
|
||||
body:
|
||||
application/json:
|
||||
schema: foo
|
||||
example: foo-example.json
|
||||
/{id}:
|
||||
get:
|
||||
description: Get a Foo by id
|
||||
responses:
|
||||
200:
|
||||
body:
|
||||
application/json:
|
||||
schema: foo
|
||||
404:
|
||||
body:
|
||||
application/json:
|
||||
schema: error
|
||||
put:
|
||||
description: Update a Foo by id
|
||||
body:
|
||||
application/json:
|
||||
schema: foo
|
||||
example: foo-example.json
|
||||
responses:
|
||||
200:
|
||||
body:
|
||||
application/json:
|
||||
schema: foo
|
||||
404:
|
||||
body:
|
||||
application/json:
|
||||
schema: error
|
||||
delete:
|
||||
description: Delete a Foo by id
|
||||
responses:
|
||||
204:
|
||||
404:
|
||||
body:
|
||||
application/json:
|
||||
schema: error
|
||||
/name/{name}:
|
||||
get:
|
||||
description: List all Foos with a certain name
|
||||
responses:
|
||||
200:
|
||||
body:
|
||||
application/json:
|
||||
schema: foos
|
||||
example: !include foos-example.json
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"message" : "Not found",
|
||||
"code" : 1001
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
{ "$schema": "http://json-schema.org/schema",
|
||||
"type": "object",
|
||||
"description": "Error message",
|
||||
"properties": {
|
||||
"message": { "type": "string" },
|
||||
"code": { "type": integer }
|
||||
},
|
||||
"required": [
|
||||
"message",
|
||||
"code"
|
||||
]
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"id" : 1,
|
||||
"name" : "First Foo"
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
{ "$schema": "http://json-schema.org/schema",
|
||||
"type": "object",
|
||||
"description": "Foo details",
|
||||
"properties": {
|
||||
"id": { "type": integer },
|
||||
"name": { "type": "string" },
|
||||
"ownerName": { "type": "string" }
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"name"
|
||||
]
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
[
|
||||
{
|
||||
"id" : 1,
|
||||
"name" : "First Foo"
|
||||
},
|
||||
{
|
||||
"id" : 2,
|
||||
"name" : "Second Foo"
|
||||
}
|
||||
]
|
|
@ -0,0 +1,5 @@
|
|||
{ "$schema": "http://json-schema.org/schema",
|
||||
"type": "array",
|
||||
"items": { "$ref": "foo" }
|
||||
"description": "Collection of Foos"
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue