merged Alex changes

This commit is contained in:
egimaben 2016-07-31 17:34:02 +03:00
commit afb340d928
186 changed files with 3234 additions and 1493 deletions

1
apache-cxf/cxf-spring/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
target/

View File

@ -8,18 +8,42 @@
<artifactId>apache-cxf</artifactId> <artifactId>apache-cxf</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</parent> </parent>
<properties>
<cxf.version>3.1.6</cxf.version> <dependencies>
<spring.version>4.3.1.RELEASE</spring.version> <dependency>
<surefire.version>2.19.1</surefire.version> <groupId>org.apache.cxf</groupId>
</properties> <artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<artifactId>maven-war-plugin</artifactId> <artifactId>maven-war-plugin</artifactId>
<version>2.6</version> <version>2.6</version>
<configuration> <configuration>
<webXml>src/main/webapp/WEB-INF/web.xml</webXml> <failOnMissingWebXml>false</failOnMissingWebXml>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
@ -33,6 +57,7 @@
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<profiles> <profiles>
<profile> <profile>
<id>integration</id> <id>integration</id>
@ -41,16 +66,16 @@
<plugin> <plugin>
<groupId>org.codehaus.cargo</groupId> <groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId> <artifactId>cargo-maven2-plugin</artifactId>
<version>1.5.0</version> <version>1.4.19</version>
<configuration> <configuration>
<container> <container>
<containerId>jetty9x</containerId> <containerId>tomcat8x</containerId>
<type>embedded</type> <type>embedded</type>
</container> </container>
<configuration> <configuration>
<properties> <properties>
<cargo.hostname>localhost</cargo.hostname> <cargo.hostname>localhost</cargo.hostname>
<cargo.servlet.port>8080</cargo.servlet.port> <cargo.servlet.port>8081</cargo.servlet.port>
</properties> </properties>
</configuration> </configuration>
</configuration> </configuration>
@ -71,6 +96,7 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.version}</version> <version>${surefire.version}</version>
@ -91,27 +117,13 @@
</plugins> </plugins>
</build> </build>
</profile> </profile>
</profiles> </profiles>
<dependencies>
<dependency> <properties>
<groupId>org.apache.cxf</groupId> <cxf.version>3.1.6</cxf.version>
<artifactId>cxf-rt-frontend-jaxws</artifactId> <spring.version>4.3.1.RELEASE</spring.version>
<version>${cxf.version}</version> <surefire.version>2.19.1</surefire.version>
</dependency> </properties>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
</project> </project>

View File

@ -0,0 +1,21 @@
package com.baeldung.cxf.spring;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
public class AppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(ServiceConfiguration.class);
container.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new CXFServlet());
dispatcher.addMapping("/services/*");
}
}

View File

@ -5,5 +5,6 @@ import javax.jws.WebService;
@WebService @WebService
public interface Baeldung { public interface Baeldung {
String hello(String name); String hello(String name);
String register(Student student); String register(Student student);
} }

View File

@ -0,0 +1,21 @@
package com.baeldung.cxf.spring;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ClientConfiguration {
@Bean(name = "client")
public Object generateProxy() {
return proxyFactoryBean().create();
}
@Bean
public JaxWsProxyFactoryBean proxyFactoryBean() {
JaxWsProxyFactoryBean proxyFactory = new JaxWsProxyFactoryBean();
proxyFactory.setServiceClass(Baeldung.class);
proxyFactory.setAddress("http://localhost:8081/services/baeldung");
return proxyFactory;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.cxf.spring;
import javax.xml.ws.Endpoint;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ServiceConfiguration {
@Bean(name = Bus.DEFAULT_BUS_ID)
public SpringBus springBus() {
return new SpringBus();
}
@Bean
public Endpoint endpoint() {
EndpointImpl endpoint = new EndpointImpl(springBus(), new BaeldungImpl());
endpoint.publish("http://localhost:8081/services/baeldung");
return endpoint;
}
}

View File

@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schema/jaxws.xsd">
<bean id="client" factory-bean="clientFactory" factory-method="create" />
<bean id="clientFactory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
<property name="serviceClass" value="com.baeldung.cxf.spring.Baeldung" />
<property name="address" value="http://localhost:8080/services/baeldung" />
</bean>
</beans>

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<jaxws:endpoint id="baeldung"
implementor="com.baeldung.cxf.spring.BaeldungImpl" address="http://localhost:8080/services/baeldung" />
</beans>

View File

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="3.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>cxf</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>cxf</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
</web-app>

View File

@ -3,15 +3,12 @@ package com.baeldung.cxf.spring;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import org.junit.Test; import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class StudentTest { public class StudentTest {
private ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "client-beans.xml" }); private ApplicationContext context = new AnnotationConfigApplicationContext(ClientConfiguration.class);
private Baeldung baeldungProxy; private Baeldung baeldungProxy = (Baeldung) context.getBean("client");
{
baeldungProxy = (Baeldung) context.getBean("client");
}
@Test @Test
public void whenUsingHelloMethod_thenCorrect() { public void whenUsingHelloMethod_thenCorrect() {

View File

@ -1,6 +1,5 @@
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
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> <modelVersion>4.0.0</modelVersion>
@ -9,7 +8,7 @@
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging> <packaging>war</packaging>
<name>Resource vs Inject vs Autowired</name> <name>dependency-injection</name>
<description>Accompanying the demonstration of the use of the annotations related to injection mechanisms, namely <description>Accompanying the demonstration of the use of the annotations related to injection mechanisms, namely
Resource, Inject, and Autowired Resource, Inject, and Autowired
</description> </description>
@ -54,6 +53,7 @@
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
@ -71,13 +71,29 @@
</includes> </includes>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>
<properties>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
</properties>
<repositories> <repositories>
<repository> <repository>
<id>java.net</id> <id>java.net</id>
<url>https://maven.java.net/content/repositories/releases/</url> <url>https://maven.java.net/content/repositories/releases/</url>
</repository> </repository>
</repositories> </repositories>
</project> </project>

View File

@ -16,15 +16,20 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
public class DozerTest { public class DozerTest {
<<<<<<< HEAD
DozerBeanMapper mapper = new DozerBeanMapper(); DozerBeanMapper mapper = new DozerBeanMapper();
private final long GMT_DIFFERENCE=46800000; private final long GMT_DIFFERENCE=46800000;
=======
private DozerBeanMapper mapper = new DozerBeanMapper();
>>>>>>> 6f2ccdf18729969951fc37e635d24c30dd9b43d5
@Before @Before
public void before() throws Exception { public void before() throws Exception {
mapper = new DozerBeanMapper(); mapper = new DozerBeanMapper();
} }
BeanMappingBuilder builder = new BeanMappingBuilder() { private BeanMappingBuilder builder = new BeanMappingBuilder() {
@Override @Override
protected void configure() { protected void configure() {
@ -33,7 +38,7 @@ public class DozerTest {
} }
}; };
BeanMappingBuilder builderMinusAge = new BeanMappingBuilder() { private BeanMappingBuilder builderMinusAge = new BeanMappingBuilder() {
@Override @Override
protected void configure() { protected void configure() {

80
hystrix/pom.xml Normal file
View File

@ -0,0 +1,80 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>hystrix</artifactId>
<version>1.0</version>
<name>hystrix</name>
<properties>
<!-- General -->
<java.version>1.8</java.version>
<!-- Hystrix -->
<hystrix-core.version>1.4.10</hystrix-core.version>
<rxjava-core.version>0.20.7</rxjava-core.version>
<!-- Testing -->
<hamcrest-all.version>1.3</hamcrest-all.version>
<junit.version>4.12</junit.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<version>${hystrix-core.version}</version>
</dependency>
<dependency>
<groupId>com.netflix.rxjava</groupId>
<artifactId>rxjava-core</artifactId>
<version>${rxjava-core.version}</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>${hamcrest-all.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,15 @@
package com.baeldung.hystrix;
public class RemoteServiceSimulator {
public String checkSomething(final long timeout) throws InterruptedException {
System.out.print(String.format("Waiting %sms. ", timeout));
// to simulate a real world delay in processing.
Thread.sleep(timeout);
return "Done waiting.";
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.hystrix;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
class CommandHelloWorld extends HystrixCommand<String> {
private final String name;
CommandHelloWorld(String name) {
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
this.name = name;
}
@Override
protected String run() {
return "Hello " + name + "!";
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.hystrix;
import com.netflix.hystrix.*;
import com.netflix.hystrix.collapser.RequestCollapserFactory;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
public class HystrixTimeoutTest {
private static HystrixCommand.Setter config;
private static HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter();
@Rule
public final ExpectedException exception = ExpectedException.none();
@Before
public void setup() {
config = HystrixCommand
.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup1"));
}
@Test
public void givenInputBob_andDefaultSettings_thenReturnHelloBob(){
assertThat(new CommandHelloWorld("Bob").execute(), equalTo("Hello Bob!"));
}
@Test
public void givenTimeoutEqualTo100_andDefaultSettings_thenReturnSuccess() throws InterruptedException {
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(100)).execute(), equalTo("Success"));
}
@Test
public void givenTimeoutEqualTo10000_andDefaultSettings_thenExpectHystrixRuntimeException() throws InterruptedException {
exception.expect(HystrixRuntimeException.class);
new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(10_000)).execute();
}
@Test
public void givenTimeoutEqualTo5000_andExecutionTimeoutEqualTo10000_thenReturnSuccess() throws InterruptedException {
commandProperties.withExecutionTimeoutInMilliseconds(10_000);
config.andCommandPropertiesDefaults(commandProperties);
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(5_000)).execute(), equalTo("Success"));
}
@Test
public void givenTimeoutEqualTo15000_andExecutionTimeoutEqualTo10000_thenExpectHystrixRuntimeException() throws InterruptedException {
exception.expect(HystrixRuntimeException.class);
commandProperties.withExecutionTimeoutInMilliseconds(10_000);
config.andCommandPropertiesDefaults(commandProperties);
new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(15_000)).execute();
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.hystrix;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
class RemoteServiceTestCommand extends HystrixCommand<String> {
private final RemoteServiceTestSimulator remoteService;
RemoteServiceTestCommand(Setter config, RemoteServiceTestSimulator remoteService) {
super(config);
this.remoteService = remoteService;
}
@Override
protected String run() throws Exception {
return remoteService.execute();
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.hystrix;
class RemoteServiceTestSimulator {
private long wait;
RemoteServiceTestSimulator(long wait) throws InterruptedException {
this.wait = wait;
}
String execute() throws InterruptedException {
Thread.sleep(wait);
return "Success";
}
}

50
immutables/pom.xml Normal file
View File

@ -0,0 +1,50 @@
<?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>immutables</artifactId>
<version>1.0.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.immutables</groupId>
<artifactId>value</artifactId>
<version>2.2.10</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.5.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mutabilitydetector</groupId>
<artifactId>MutabilityDetector</artifactId>
<version>0.9.5</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,9 @@
package com.baeldung.immutable;
import org.immutables.value.Value;
@Value.Immutable
public interface Address {
String getStreetName();
Integer getNumber();
}

View File

@ -0,0 +1,9 @@
package com.baeldung.immutable;
import org.immutables.value.Value;
@Value.Immutable
public abstract class Person {
abstract String getName();
abstract Integer getAge();
}

View File

@ -0,0 +1,13 @@
package com.baeldung.immutable.auxiliary;
import org.immutables.value.Value;
@Value.Immutable
public abstract class Person {
abstract String getName();
abstract Integer getAge();
@Value.Auxiliary
abstract String getAuxiliaryField();
}

View File

@ -0,0 +1,14 @@
package com.baeldung.immutable.default_;
import org.immutables.value.Value;
@Value.Immutable(prehash = true)
public abstract class Person {
abstract String getName();
@Value.Default
Integer getAge() {
return 42;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.immutable.parameter;
import org.immutables.value.Value;
@Value.Immutable
public abstract class Person {
@Value.Parameter
abstract String getName();
@Value.Parameter
abstract Integer getAge();
}

View File

@ -0,0 +1,9 @@
package com.baeldung.immutable.prehash;
import org.immutables.value.Value;
@Value.Immutable(prehash = true)
public abstract class Person {
abstract String getName();
abstract Integer getAge();
}

View File

@ -0,0 +1,27 @@
package com.baeldung.immutable;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mutabilitydetector.unittesting.MutabilityAssert.assertImmutable;
public class ImmutablePersonTest {
@Test
public void whenModifying_shouldCreateNewInstance() throws Exception {
final ImmutablePerson john = ImmutablePerson.builder()
.age(42)
.name("John")
.build();
final ImmutablePerson john43 = john.withAge(43);
assertThat(john)
.isNotSameAs(john43);
assertThat(john.getAge())
.isEqualTo(42);
assertImmutable(ImmutablePerson.class);
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.immutable.auxiliary;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ImmutablePersonAuxiliaryTest {
@Test
public void whenComparing_shouldIgnore() throws Exception {
final ImmutablePerson john1 = ImmutablePerson.builder()
.name("John")
.age(42)
.auxiliaryField("Value1")
.build();
final ImmutablePerson john2 = ImmutablePerson.builder()
.name("John")
.age(42)
.auxiliaryField("Value2")
.build();
assertThat(john1.equals(john2))
.isTrue();
assertThat(john1.toString())
.isEqualTo(john2.toString());
assertThat(john1.hashCode())
.isEqualTo(john2.hashCode());
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.immutable.default_;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ImmutablePersonDefaultTest {
@Test
public void whenInstantiating_shouldUseDefaultValue() throws Exception {
final ImmutablePerson john = ImmutablePerson.builder().name("John").build();
assertThat(john.getAge()).isEqualTo(42);
}
}

View File

@ -7,9 +7,19 @@ import java.util.List;
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
public class CustomListDeserializer extends JsonDeserializer<List<ItemWithSerializer>> { public class CustomListDeserializer extends StdDeserializer<List<ItemWithSerializer>> {
private static final long serialVersionUID = 1095767961632979804L;
public CustomListDeserializer() {
this(null);
}
public CustomListDeserializer(final Class<?> vc) {
super(vc);
}
@Override @Override
public List<ItemWithSerializer> deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException { public List<ItemWithSerializer> deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException {

View File

@ -6,11 +6,20 @@ import java.util.List;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class CustomListSerializer extends JsonSerializer<List<ItemWithSerializer>> { public class CustomListSerializer extends StdSerializer<List<ItemWithSerializer>> {
private static final long serialVersionUID = 3698763098000900856L;
public CustomListSerializer() {
this(null);
}
public CustomListSerializer(final Class<List<ItemWithSerializer>> t) {
super(t);
}
@Override @Override
public void serialize(final List<ItemWithSerializer> items, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException { public void serialize(final List<ItemWithSerializer> items, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException {
final List<Integer> ids = new ArrayList<Integer>(); final List<Integer> ids = new ArrayList<Integer>();

View File

@ -8,12 +8,21 @@ import java.util.Date;
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
public class CustomDateDeserializer extends JsonDeserializer<Date> { public class CustomDateDeserializer extends StdDeserializer<Date> {
private static final long serialVersionUID = -5451717385630622729L;
private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
public CustomDateDeserializer() {
this(null);
}
public CustomDateDeserializer(final Class<?> vc) {
super(vc);
}
@Override @Override
public Date deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException { public Date deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException {
final String date = jsonparser.getText(); final String date = jsonparser.getText();

View File

@ -6,13 +6,22 @@ import java.util.Date;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class CustomDateSerializer extends JsonSerializer<Date> { public class CustomDateSerializer extends StdSerializer<Date> {
private static final long serialVersionUID = -2894356342227378312L;
private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
public CustomDateSerializer() {
this(null);
}
public CustomDateSerializer(final Class<Date> t) {
super(t);
}
@Override @Override
public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException { public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException {
gen.writeString(formatter.format(value)); gen.writeString(formatter.format(value));

View File

@ -8,10 +8,20 @@ import org.joda.time.format.DateTimeFormatter;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class CustomDateTimeSerializer extends JsonSerializer<DateTime> { public class CustomDateTimeSerializer extends StdSerializer<DateTime> {
private static final long serialVersionUID = -3927232057990121460L;
public CustomDateTimeSerializer() {
this(null);
}
public CustomDateTimeSerializer(final Class<DateTime> t) {
super(t);
}
private static DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"); private static DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");

View File

@ -6,13 +6,23 @@ import java.time.format.DateTimeFormatter;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class CustomLocalDateTimeSerializer extends JsonSerializer<LocalDateTime> { public class CustomLocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
private static final long serialVersionUID = -7449444168934819290L;
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
public CustomLocalDateTimeSerializer() {
this(null);
}
public CustomLocalDateTimeSerializer(final Class<LocalDateTime> t) {
super(t);
}
@Override @Override
public void serialize(final LocalDateTime value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException { public void serialize(final LocalDateTime value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException {
gen.writeString(formatter.format(value)); gen.writeString(formatter.format(value));

View File

@ -2,17 +2,26 @@ package com.baeldung.jackson.deserialization;
import java.io.IOException; import java.io.IOException;
import com.baeldung.jackson.dtos.User;
import com.baeldung.jackson.dtos.Item; import com.baeldung.jackson.dtos.Item;
import com.baeldung.jackson.dtos.User;
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.node.IntNode; import com.fasterxml.jackson.databind.node.IntNode;
public class ItemDeserializer extends JsonDeserializer<Item> { public class ItemDeserializer extends StdDeserializer<Item> {
private static final long serialVersionUID = 1883547683050039861L;
public ItemDeserializer() {
this(null);
}
public ItemDeserializer(final Class<?> vc) {
super(vc);
}
/** /**
* {"id":1,"itemNr":"theItem","owner":2} * {"id":1,"itemNr":"theItem","owner":2}

View File

@ -4,15 +4,24 @@ import java.io.IOException;
import com.baeldung.jackson.dtos.ItemWithSerializer; import com.baeldung.jackson.dtos.ItemWithSerializer;
import com.baeldung.jackson.dtos.User; import com.baeldung.jackson.dtos.User;
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.node.IntNode; import com.fasterxml.jackson.databind.node.IntNode;
public class ItemDeserializerOnClass extends JsonDeserializer<ItemWithSerializer> { public class ItemDeserializerOnClass extends StdDeserializer<ItemWithSerializer> {
private static final long serialVersionUID = 5579141241817332594L;
public ItemDeserializerOnClass() {
this(null);
}
public ItemDeserializerOnClass(final Class<?> vc) {
super(vc);
}
/** /**
* {"id":1,"itemNr":"theItem","owner":2} * {"id":1,"itemNr":"theItem","owner":2}

View File

@ -4,10 +4,20 @@ import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class TypeSerializer extends JsonSerializer<TypeEnumWithCustomSerializer> { public class TypeSerializer extends StdSerializer<TypeEnumWithCustomSerializer> {
private static final long serialVersionUID = -7650668914169390772L;
public TypeSerializer() {
this(null);
}
public TypeSerializer(final Class<TypeEnumWithCustomSerializer> t) {
super(t);
}
@Override @Override
public void serialize(final TypeEnumWithCustomSerializer value, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException { public void serialize(final TypeEnumWithCustomSerializer value, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException {

View File

@ -7,18 +7,26 @@ import org.slf4j.LoggerFactory;
import com.baeldung.jackson.objectmapper.dto.Car; import com.baeldung.jackson.objectmapper.dto.Car;
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
public class CustomCarDeserializer extends JsonDeserializer<Car> { public class CustomCarDeserializer extends StdDeserializer<Car> {
private static final long serialVersionUID = -5918629454846356161L;
private final Logger Logger = LoggerFactory.getLogger(getClass()); private final Logger Logger = LoggerFactory.getLogger(getClass());
public CustomCarDeserializer() { public CustomCarDeserializer() {
this(null);
} }
public CustomCarDeserializer(final Class<?> vc) {
super(vc);
}
@Override @Override
public Car deserialize(final JsonParser parser, final DeserializationContext deserializer) throws IOException { public Car deserialize(final JsonParser parser, final DeserializationContext deserializer) throws IOException {
final Car car = new Car(); final Car car = new Car();

View File

@ -1,16 +1,25 @@
package com.baeldung.jackson.objectmapper; package com.baeldung.jackson.objectmapper;
import java.io.IOException;
import com.baeldung.jackson.objectmapper.dto.Car; import com.baeldung.jackson.objectmapper.dto.Car;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException; public class CustomCarSerializer extends StdSerializer<Car>
public class CustomCarSerializer extends JsonSerializer<Car>
{ {
public CustomCarSerializer() { }
private static final long serialVersionUID = 1396140685442227917L;
public CustomCarSerializer() {
this(null);
}
public CustomCarSerializer(final Class<Car> t) {
super(t);
}
@Override @Override
public void serialize(final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializer) throws IOException, JsonProcessingException public void serialize(final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializer) throws IOException, JsonProcessingException

View File

@ -3,13 +3,22 @@ package com.baeldung.jackson.serialization;
import java.io.IOException; import java.io.IOException;
import com.baeldung.jackson.dtos.Item; import com.baeldung.jackson.dtos.Item;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class ItemSerializer extends JsonSerializer<Item> { public class ItemSerializer extends StdSerializer<Item> {
private static final long serialVersionUID = 6739170890621978901L;
public ItemSerializer() {
this(null);
}
public ItemSerializer(final Class<Item> t) {
super(t);
}
@Override @Override
public final void serialize(final Item value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { public final void serialize(final Item value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {

View File

@ -3,13 +3,22 @@ package com.baeldung.jackson.serialization;
import java.io.IOException; import java.io.IOException;
import com.baeldung.jackson.dtos.ItemWithSerializer; import com.baeldung.jackson.dtos.ItemWithSerializer;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class ItemSerializerOnClass extends JsonSerializer<ItemWithSerializer> { public class ItemSerializerOnClass extends StdSerializer<ItemWithSerializer> {
private static final long serialVersionUID = -1760959597313610409L;
public ItemSerializerOnClass() {
this(null);
}
public ItemSerializerOnClass(final Class<ItemWithSerializer> t) {
super(t);
}
@Override @Override
public final void serialize(final ItemWithSerializer value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { public final void serialize(final ItemWithSerializer value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {

View File

@ -4,10 +4,20 @@ import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class MyDtoNullKeySerializer extends JsonSerializer<Object> { public class MyDtoNullKeySerializer extends StdSerializer<Object> {
private static final long serialVersionUID = -4478531309177369056L;
public MyDtoNullKeySerializer() {
this(null);
}
public MyDtoNullKeySerializer(final Class<Object> t) {
super(t);
}
@Override @Override
public void serialize(final Object value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { public void serialize(final Object value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {

View File

@ -6,10 +6,19 @@ import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
public class RestLoaderRequestDeserializer extends JsonDeserializer<RestLoaderRequest<IEntity>> { public class RestLoaderRequestDeserializer extends StdDeserializer<RestLoaderRequest<IEntity>> {
private static final long serialVersionUID = -4245207329377196889L;
public RestLoaderRequestDeserializer() {
this(null);
}
public RestLoaderRequestDeserializer(final Class<?> vc) {
super(vc);
}
@Override @Override
public RestLoaderRequest<IEntity> deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { public RestLoaderRequest<IEntity> deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {

7
json/README.md Normal file
View File

@ -0,0 +1,7 @@
=========
## Fast-Json
### Relevant Articles:
- [Introduction to JSON Schema in Java](http://www.baeldung.com/introduction-to-json-schema-in-java)
- [A Guide to FastJson](http://www.baeldung.com/????????)

View File

@ -13,6 +13,12 @@
<version>1.3.0</version> <version>1.3.0</version>
</dependency> </dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.13</version>
</dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>

View File

@ -1,6 +1,7 @@
package org.baeldung.json.schema; package com.baeldung.json.schema;
import org.everit.json.schema.Schema; import org.everit.json.schema.Schema;
import org.everit.json.schema.ValidationException;
import org.everit.json.schema.loader.SchemaLoader; import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONObject; import org.json.JSONObject;
@ -9,7 +10,7 @@ import org.junit.Test;
public class JSONSchemaTest { public class JSONSchemaTest {
@Test @Test(expected = ValidationException.class)
public void givenInvalidInput_whenValidating_thenInvalid() { public void givenInvalidInput_whenValidating_thenInvalid() {
JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/schema.json"))); JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/schema.json")));

View File

@ -0,0 +1,104 @@
package fast_json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.BeanContext;
import com.alibaba.fastjson.serializer.ContextValueFilter;
import com.alibaba.fastjson.serializer.NameFilter;
import com.alibaba.fastjson.serializer.SerializeConfig;
import org.junit.Before;
import org.junit.Test;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class FastJsonTests {
private List<Person> listOfPersons;
@Before
public void setUp() {
listOfPersons = new ArrayList<Person>();
Calendar calendar = Calendar.getInstance();
calendar.set(2016, 6, 24);
listOfPersons.add(new Person(15, "John", "Doe", calendar.getTime()));
listOfPersons.add(new Person(20, "Janette", "Doe", calendar.getTime()));
}
@Test
public void whenJavaList_thanConvertToJsonCorrect() {
String personJsonFormat = JSON.toJSONString(listOfPersons);
assertEquals(
personJsonFormat,
"[{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"John\",\"DATE OF BIRTH\":"
+ "\"24/07/2016\"},{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"Janette\",\"DATE OF BIRTH\":"
+ "\"24/07/2016\"}]");
}
@Test
public void whenJson_thanConvertToObjectCorrect() {
String personJsonFormat = JSON.toJSONString(listOfPersons.get(0));
Person newPerson = JSON.parseObject(personJsonFormat, Person.class);
assertEquals(newPerson.getAge(), 0); // serialize is set to false for age attribute
assertEquals(newPerson.getFirstName(), listOfPersons.get(0).getFirstName());
assertEquals(newPerson.getLastName(), listOfPersons.get(0).getLastName());
}
@Test
public void whenGenerateJson_thanGenerationCorrect() throws ParseException {
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < 2; i++) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("FIRST NAME", "John" + i);
jsonObject.put("LAST NAME", "Doe" + i);
jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12");
jsonArray.add(jsonObject);
}
assertEquals(
jsonArray.toString(),
"[{\"LAST NAME\":\"Doe0\",\"DATE OF BIRTH\":"
+ "\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John0\"},{\"LAST NAME\":\"Doe1\","
+ "\"DATE OF BIRTH\":\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John1\"}]");
}
@Test
public void givenContextFilter_whenJavaObject_thanJsonCorrect() {
ContextValueFilter valueFilter = new ContextValueFilter() {
public Object process(BeanContext context, Object object,
String name, Object value) {
if (name.equals("DATE OF BIRTH")) {
return "NOT TO DISCLOSE";
}
if (value.equals("John") || value.equals("Doe")) {
return ((String) value).toUpperCase();
} else {
return null;
}
}
};
JSON.toJSONString(listOfPersons, valueFilter);
}
@Test
public void givenSerializeConfig_whenJavaObject_thanJsonCorrect() {
NameFilter formatName = new NameFilter() {
public String process(Object object, String name, Object value) {
return name.toLowerCase().replace(" ", "_");
}
};
SerializeConfig.getGlobalInstance().addFilter(Person.class, formatName);
String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons,
"yyyy-MM-dd");
assertEquals(
jsonOutput,
"[{\"first_name\":\"Doe\",\"last_name\":\"John\","
+ "\"date_of_birth\":\"2016-07-24\"},{\"first_name\":\"Doe\",\"last_name\":"
+ "\"Janette\",\"date_of_birth\":\"2016-07-24\"}]");
// resetting custom serializer
SerializeConfig.getGlobalInstance().put(Person.class, null);
}
}

View File

@ -0,0 +1,70 @@
package fast_json;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.Date;
public class Person {
@JSONField(name = "AGE", serialize = false, deserialize = false)
private int age;
@JSONField(name = "LAST NAME", ordinal = 2)
private String lastName;
@JSONField(name = "FIRST NAME", ordinal = 1)
private String firstName;
@JSONField(name = "DATE OF BIRTH", format = "dd/MM/yyyy", ordinal = 3)
private Date dateOfBirth;
public Person() {
}
public Person(int age, String lastName, String firstName, Date dateOfBirth) {
super();
this.age = age;
this.lastName = lastName;
this.firstName = firstName;
this.dateOfBirth = dateOfBirth;
}
@Override
public String toString() {
return "Person [age=" + age + ", lastName=" + lastName + ", firstName="
+ firstName + ", dateOfBirth=" + dateOfBirth + "]";
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}

View File

@ -5,3 +5,4 @@
### Relevant Articles: ### Relevant Articles:
- [JMockit 101](http://www.baeldung.com/jmockit-101) - [JMockit 101](http://www.baeldung.com/jmockit-101)
- [A Guide to JMockit Expectations](http://www.baeldung.com/jmockit-expectations)

View File

@ -1,9 +1,11 @@
package org.baeldung.mocks.jmockit; package org.baeldung.mocks.jmockit;
public class Collaborator { public class Collaborator {
public boolean collaborate(String string){ public boolean collaborate(String string){
return false; return false;
} }
public void receive(boolean bool){ public void receive(boolean bool){
//NOOP //NOOP
} }

View File

@ -1,7 +1,7 @@
package org.baeldung.mocks.jmockit; package org.baeldung.mocks.jmockit;
public class Model { public class Model {
public String getInfo(){ public String getInfo() {
return "info"; return "info";
} }
} }

View File

@ -1,21 +1,20 @@
package org.baeldung.mocks.jmockit; package org.baeldung.mocks.jmockit;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.junit.Test;
import org.junit.runner.RunWith;
import mockit.Delegate; import mockit.Delegate;
import mockit.Expectations; import mockit.Expectations;
import mockit.Mocked; import mockit.Mocked;
import mockit.StrictExpectations; import mockit.StrictExpectations;
import mockit.Verifications; import mockit.Verifications;
import mockit.integration.junit4.JMockit; import mockit.integration.junit4.JMockit;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
@RunWith(JMockit.class) @RunWith(JMockit.class)
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -23,71 +22,56 @@ public class ExpectationsTest {
@Test @Test
public void testForAny(@Mocked ExpectationsCollaborator mock) throws Exception { public void testForAny(@Mocked ExpectationsCollaborator mock) throws Exception {
new Expectations() { new Expectations() {{
{ mock.methodForAny1(anyString, anyInt, anyBoolean);
mock.methodForAny1(anyString, anyInt, anyBoolean); result = "any";
result = "any"; }};
}
};
assertEquals("any", mock.methodForAny1("barfooxyz", 0, Boolean.FALSE)); assertEquals("any", mock.methodForAny1("barfooxyz", 0, Boolean.FALSE));
mock.methodForAny2(2L, new ArrayList<>()); mock.methodForAny2(2L, new ArrayList<>());
new Verifications() { new Verifications() {{
{ mock.methodForAny2(anyLong, (List<String>) any);
mock.methodForAny2(anyLong, (List<String>) any); }};
}
};
} }
@Test @Test
public void testForWith(@Mocked ExpectationsCollaborator mock) throws Exception { public void testForWith(@Mocked ExpectationsCollaborator mock) throws Exception {
new Expectations() { new Expectations() {{
{ mock.methodForWith1(withSubstring("foo"), withNotEqual(1));
mock.methodForWith1(withSubstring("foo"), withNotEqual(1)); result = "with";
result = "with"; }};
}
};
assertEquals("with", mock.methodForWith1("barfooxyz", 2)); assertEquals("with", mock.methodForWith1("barfooxyz", 2));
mock.methodForWith2(Boolean.TRUE, new ArrayList<>()); mock.methodForWith2(Boolean.TRUE, new ArrayList<>());
new Verifications() { new Verifications() {{
{ mock.methodForWith2(withNotNull(), withInstanceOf(List.class));
mock.methodForWith2(withNotNull(), withInstanceOf(List.class)); }};
}
};
} }
@Test @Test
public void testWithNulls(@Mocked ExpectationsCollaborator mock) { public void testWithNulls(@Mocked ExpectationsCollaborator mock) {
new Expectations() { new Expectations() {{
{ mock.methodForNulls1(anyString, null);
mock.methodForNulls1(anyString, null); result = "null";
result = "null"; }};
}
};
assertEquals("null", mock.methodForNulls1("blablabla", new ArrayList<String>())); assertEquals("null", mock.methodForNulls1("blablabla", new ArrayList<String>()));
mock.methodForNulls2("blablabla", null); mock.methodForNulls2("blablabla", null);
new Verifications() { new Verifications() {{
{ mock.methodForNulls2(anyString, (List<String>) withNull());
mock.methodForNulls2(anyString, (List<String>) withNull()); }};
}
};
} }
@Test @Test
public void testWithTimes(@Mocked ExpectationsCollaborator mock) { public void testWithTimes(@Mocked ExpectationsCollaborator mock) {
new Expectations() { new Expectations() {{
{ mock.methodForTimes1();
// exactly 2 invocations are expected times = 2;
mock.methodForTimes1(); mock.methodForTimes2();
times = 2; }};
mock.methodForTimes2(); // "minTimes = 1" is implied
}
};
mock.methodForTimes1(); mock.methodForTimes1();
mock.methodForTimes1(); mock.methodForTimes1();
@ -96,56 +80,44 @@ public class ExpectationsTest {
mock.methodForTimes3(); mock.methodForTimes3();
mock.methodForTimes3(); mock.methodForTimes3();
new Verifications() { new Verifications() {{
{ mock.methodForTimes3();
// we expect from 1 to 3 invocations minTimes = 1;
mock.methodForTimes3(); maxTimes = 3;
minTimes = 1; }};
maxTimes = 3;
}
};
} }
@Test @Test
public void testCustomArgumentMatching(@Mocked ExpectationsCollaborator mock) { public void testCustomArgumentMatching(@Mocked ExpectationsCollaborator mock) {
new Expectations() { new Expectations() {{
{ mock.methodForArgThat(withArgThat(new BaseMatcher<Object>() {
mock.methodForArgThat(withArgThat(new BaseMatcher<Object>() { @Override
@Override public boolean matches(Object item) {
public boolean matches(Object item) { return item instanceof Model && "info".equals(((Model) item).getInfo());
return item instanceof Model && "info".equals(((Model) item).getInfo()); }
}
@Override @Override
public void describeTo(Description description) { public void describeTo(Description description) {
// NOOP }
} }));
})); }};
}
};
mock.methodForArgThat(new Model()); mock.methodForArgThat(new Model());
} }
@Test @Test
public void testResultAndReturns(@Mocked ExpectationsCollaborator mock) { public void testResultAndReturns(@Mocked ExpectationsCollaborator mock) {
new StrictExpectations() { new StrictExpectations() {{
{ mock.methodReturnsString();
// return "foo", an exception and lastly "bar" result = "foo";
mock.methodReturnsString(); result = new Exception();
result = "foo"; result = "bar";
result = new Exception(); mock.methodReturnsInt();
result = "bar"; result = new int[]{1, 2, 3};
// return 1, 2, 3 mock.methodReturnsString();
mock.methodReturnsInt(); returns("foo", "bar");
result = new int[] { 1, 2, 3 }; mock.methodReturnsInt();
// return "foo" and "bar" result = 1;
mock.methodReturnsString(); }};
returns("foo", "bar");
// return only 1
mock.methodReturnsInt();
result = 1;
}
};
assertEquals("Should return foo", "foo", mock.methodReturnsString()); assertEquals("Should return foo", "foo", mock.methodReturnsString());
try { try {
@ -164,27 +136,23 @@ public class ExpectationsTest {
@Test @Test
public void testDelegate(@Mocked ExpectationsCollaborator mock) { public void testDelegate(@Mocked ExpectationsCollaborator mock) {
new StrictExpectations() { new Expectations() {{
{ mock.methodForDelegate(anyInt);
// return "foo", an exception and lastly "bar" result = new Delegate() {
mock.methodForDelegate(anyInt); public int delegate(int i) throws Exception {
times = 2; if (i < 3) {
result = new Delegate() { return 5;
public int delegate(int i) throws Exception { } else {
if (i < 3) { throw new Exception();
return 5;
} else {
throw new Exception();
}
} }
}; }
} };
}; }};
assertEquals("Should return 5", 5, mock.methodForDelegate(1)); assertEquals("Should return 5", 5, mock.methodForDelegate(1));
try { try {
mock.methodForDelegate(3); mock.methodForDelegate(3);
} catch (Exception e) { } catch (Exception e) {
// NOOP
} }
} }
} }

View File

@ -21,7 +21,9 @@ public class PerformerTest {
model.getInfo();result = "bar"; model.getInfo();result = "bar";
collaborator.collaborate("bar"); result = true; collaborator.collaborate("bar"); result = true;
}}; }};
performer.perform(model); performer.perform(model);
new Verifications() {{ new Verifications() {{
collaborator.receive(true); collaborator.receive(true);
}}; }};

26
pom.xml
View File

@ -15,39 +15,56 @@
<modules> <modules>
<module>assertj</module> <module>assertj</module>
<module>apache-cxf</module> <module>apache-cxf</module>
<module>apache-fop</module>
<module>core-java</module> <module>core-java</module>
<module>core-java-8</module> <module>core-java-8</module>
<module>couchbase-sdk-intro</module>
<module>couchbase-sdk-spring-service</module>
<module>dependency-injection</module>
<module>gatling</module>
<module>gson</module> <module>gson</module>
<!-- <module>gson-jackson-performance</module> --> <module>gson-jackson-performance</module>
<module>guava</module> <module>guava</module>
<module>guava18</module> <module>guava18</module>
<module>guava19</module> <module>guava19</module>
<module>handling-spring-static-resources</module> <module>handling-spring-static-resources</module>
<module>httpclient</module> <module>httpclient</module>
<module>immutables</module>
<module>jackson</module> <module>jackson</module>
<module>javaxval</module> <module>javaxval</module>
<module>jjwt</module> <module>jjwt</module>
<module>jooq-spring</module> <module>jooq-spring</module>
<module>jpa-storedprocedure</module>
<module>json</module>
<module>json-path</module> <module>json-path</module>
<module>junit5</module>
<module>mockito</module> <module>mockito</module>
<module>mocks</module> <module>mocks</module>
<module>jee7schedule</module> <module>jee7schedule</module>
<!-- <module>jpa-storedprocedure</module> --> <!-- <module>jpa-storedprocedure</module> -->
<module>querydsl</module> <module>querydsl</module>
<!-- <module>raml</module> --> <!-- <module>raml</module> -->
<module>rest-assured</module>
<module>rest-testing</module> <module>rest-testing</module>
<module>resteasy</module> <module>resteasy</module>
<module>log4j</module> <module>log4j</module>
<module>spring-all</module> <module>spring-all</module>
<module>spring-apache-camel</module> <module>spring-apache-camel</module>
<module>spring-autowire</module>
<module>spring-batch</module> <module>spring-batch</module>
<module>spring-boot</module> <module>spring-boot</module>
<module>spring-controller</module> <module>spring-cucumber</module>
<module>spring-data-cassandra</module> <module>spring-data-cassandra</module>
<module>spring-data-couchbase-2</module>
<module>spring-data-couchbase-2b</module>
<module>spring-data-elasticsearch</module> <module>spring-data-elasticsearch</module>
<module>spring-data-neo4j</module>
<module>spring-data-mongodb</module> <module>spring-data-mongodb</module>
<module>spring-data-redis</module> <module>spring-data-redis</module>
<module>spring-data-rest</module>
<module>spring-exceptions</module> <module>spring-exceptions</module>
<module>spring-freemarker</module> <module>spring-freemarker</module>
<module>spring-hibernate3</module> <module>spring-hibernate3</module>
@ -61,9 +78,12 @@
<module>spring-openid</module> <module>spring-openid</module>
<module>spring-protobuf</module> <module>spring-protobuf</module>
<module>spring-quartz</module> <module>spring-quartz</module>
<module>spring-spel</module>
<module>spring-rest</module> <module>spring-rest</module>
<module>spring-rest-docs</module>
<module>spring-security-basic-auth</module> <module>spring-security-basic-auth</module>
<module>spring-security-custom-permission</module>
<module>spring-security-mvc-custom</module> <module>spring-security-mvc-custom</module>
<module>spring-security-mvc-digest-auth</module> <module>spring-security-mvc-digest-auth</module>
<module>spring-security-mvc-ldap</module> <module>spring-security-mvc-ldap</module>
@ -81,9 +101,11 @@
<module>xml</module> <module>xml</module>
<module>lombok</module> <module>lombok</module>
<module>redis</module> <module>redis</module>
<module>webjars</module>
<module>mutation-testing</module> <module>mutation-testing</module>
<module>spring-mvc-velocity</module> <module>spring-mvc-velocity</module>
<module>xstream</module>
</modules> </modules>
</project> </project>

View File

@ -2,7 +2,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>rest-assured-tutorial</artifactId> <artifactId>rest-assured</artifactId>
<version>1.0</version> <version>1.0</version>
<name>rest-assured</name> <name>rest-assured</name>
<build> <build>
@ -12,8 +12,8 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version> <version>3.3</version>
<configuration> <configuration>
<source>7</source> <source>8</source>
<target>7</target> <target>8</target>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>

View File

@ -45,7 +45,7 @@ public class RestAssuredTest {
} }
@Test @Test
public void givenUrl_whenSuccessOnGetsResponse_andJsonHasRequiredKV_thenCorrect() { public void givenUrl_whenSuccessOnGetsResponseAndJsonHasRequiredKV_thenCorrect() {
get("/events?id=390").then().statusCode(200).assertThat() get("/events?id=390").then().statusCode(200).assertThat()
.body("id", equalTo("390")); .body("id", equalTo("390"));
@ -99,7 +99,7 @@ public class RestAssuredTest {
} }
private static String getEventJson() { private static String getEventJson() {
return Util.inputStreamToString(new RestAssuredTest().getClass() return Util.inputStreamToString(RestAssuredTest.class
.getResourceAsStream("/event_0.json")); .getResourceAsStream("/event_0.json"));
} }

View File

@ -1,12 +1,11 @@
## Logger configure file for myproject ## Logger configure
log.dir=C:/ProgramData/radixbase/
datestamp=yyyy-MM-dd HH:mm:ss datestamp=yyyy-MM-dd HH:mm:ss
log4j.rootLogger=TRACE, file, console log4j.rootLogger=TRACE, file, console
log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.maxFileSize=1GB log4j.appender.file.maxFileSize=1GB
log4j.appender.file.maxBackupIndex=5 log4j.appender.file.maxBackupIndex=5
log4j.appender.file.File=log/mydebug.log log4j.appender.file.File=log/rest-assured.log
log4j.appender.file.threshold=TRACE log4j.appender.file.threshold=TRACE
log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{${datestamp}} %5p: [%c] - %m%n log4j.appender.file.layout.ConversionPattern=%d{${datestamp}} %5p: [%c] - %m%n

View File

@ -1,12 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src/main/webapp"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.WebProject">
<attributes>
<attribute name="hide" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.baseBrowserLibrary"/>
<classpathentry kind="output" path=""/>
</classpath>

View File

@ -1,95 +0,0 @@
eclipse.preferences.version=1
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
org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable
org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
org.eclipse.jdt.core.compiler.problem.deadCode=warning
org.eclipse.jdt.core.compiler.problem.deprecation=warning
org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
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.finalParameterBound=warning
org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
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.methodWithConstructorName=warning
org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore
org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore
org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore
org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
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.nullAnnotationInferenceConflict=error
org.eclipse.jdt.core.compiler.problem.nullReference=warning
org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error
org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning
org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore
org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore
org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore
org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
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.syntheticAccessEmulation=ignore
org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error
org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled
org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning
org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore
org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
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.unusedImport=warning
org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore
org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
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.unusedWarningToken=warning
org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
org.eclipse.jdt.core.compiler.source=1.8

View File

@ -1,55 +0,0 @@
#Sat Jan 21 23:04:06 EET 2012
eclipse.preferences.version=1
editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
sp_cleanup.add_default_serial_version_id=true
sp_cleanup.add_generated_serial_version_id=false
sp_cleanup.add_missing_annotations=true
sp_cleanup.add_missing_deprecated_annotations=true
sp_cleanup.add_missing_methods=false
sp_cleanup.add_missing_nls_tags=false
sp_cleanup.add_missing_override_annotations=true
sp_cleanup.add_missing_override_annotations_interface_methods=true
sp_cleanup.add_serial_version_id=false
sp_cleanup.always_use_blocks=true
sp_cleanup.always_use_parentheses_in_expressions=true
sp_cleanup.always_use_this_for_non_static_field_access=false
sp_cleanup.always_use_this_for_non_static_method_access=false
sp_cleanup.convert_to_enhanced_for_loop=true
sp_cleanup.correct_indentation=true
sp_cleanup.format_source_code=true
sp_cleanup.format_source_code_changes_only=true
sp_cleanup.make_local_variable_final=true
sp_cleanup.make_parameters_final=true
sp_cleanup.make_private_fields_final=false
sp_cleanup.make_type_abstract_if_missing_method=false
sp_cleanup.make_variable_declarations_final=true
sp_cleanup.never_use_blocks=false
sp_cleanup.never_use_parentheses_in_expressions=false
sp_cleanup.on_save_use_additional_actions=true
sp_cleanup.organize_imports=true
sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
sp_cleanup.qualify_static_member_accesses_with_declaring_class=true
sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
sp_cleanup.remove_private_constructors=true
sp_cleanup.remove_trailing_whitespaces=true
sp_cleanup.remove_trailing_whitespaces_all=true
sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
sp_cleanup.remove_unnecessary_casts=true
sp_cleanup.remove_unnecessary_nls_tags=false
sp_cleanup.remove_unused_imports=true
sp_cleanup.remove_unused_local_variables=false
sp_cleanup.remove_unused_private_fields=true
sp_cleanup.remove_unused_private_members=false
sp_cleanup.remove_unused_private_methods=true
sp_cleanup.remove_unused_private_types=true
sp_cleanup.sort_members=false
sp_cleanup.sort_members_all=false
sp_cleanup.use_blocks=false
sp_cleanup.use_blocks_only_for_return_and_throw=false
sp_cleanup.use_parentheses_in_expressions=false
sp_cleanup.use_this_for_non_static_field_access=true
sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
sp_cleanup.use_this_for_non_static_method_access=true
sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true

View File

@ -1,4 +0,0 @@
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

View File

@ -1,2 +0,0 @@
eclipse.preferences.version=1
org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false

View File

@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="spring-all">
<wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/>
<wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
<property name="context-root" value="spring-all"/>
<property name="java-output-path" value="/spring-all/target/classes"/>
</wb-module>
</project-modules>

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<installed facet="wst.jsdt.web" version="1.0"/>
<installed facet="java" version="1.8"/>
<installed facet="jst.web" version="3.1"/>
</faceted-project>

View File

@ -1 +0,0 @@
org.eclipse.wst.jsdt.launching.baseBrowserLibrary

View File

@ -1,15 +0,0 @@
DELEGATES_PREFERENCE=delegateValidatorList
USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator;
USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator;
USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.402.v201212031633
disabled=06target
eclipse.preferences.version=1
override=true
suspend=false
vals/org.eclipse.jst.jsf.ui.JSFAppConfigValidator/global=FF01
vals/org.eclipse.jst.jsp.core.JSPBatchValidator/global=FF01
vals/org.eclipse.jst.jsp.core.JSPContentValidator/global=FF01
vals/org.eclipse.jst.jsp.core.TLDValidator/global=FF01
vals/org.eclipse.wst.dtd.core.dtdDTDValidator/global=FF01
vals/org.eclipse.wst.jsdt.web.core.JsBatchValidator/global=TF02
vf.version=3

View File

@ -1,2 +0,0 @@
eclipse.preferences.version=1
org.eclipse.wst.ws.service.policy.projectEnabled=false

View File

@ -14,6 +14,10 @@
</parent> </parent>
<dependencies> <dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- Spring --> <!-- Spring -->
@ -41,11 +45,6 @@
<artifactId>spring-aspects</artifactId> <artifactId>spring-aspects</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<!-- persistence --> <!-- persistence -->
<dependency> <dependency>
@ -88,6 +87,14 @@
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<!-- Akka -->
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-actor_2.11</artifactId>
<version>2.4.8</version>
</dependency>
<!-- util --> <!-- util -->
<dependency> <dependency>

View File

@ -0,0 +1,26 @@
package org.baeldung.akka;
import akka.actor.ActorSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import static org.baeldung.akka.SpringExtension.SPRING_EXTENSION_PROVIDER;
@Configuration
@ComponentScan
public class AppConfiguration {
@Autowired
private ApplicationContext applicationContext;
@Bean
public ActorSystem actorSystem() {
ActorSystem system = ActorSystem.create("akka-spring-demo");
SPRING_EXTENSION_PROVIDER.get(system).initialize(applicationContext);
return system;
}
}

View File

@ -0,0 +1,43 @@
package org.baeldung.akka;
import akka.actor.UntypedActor;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE;
@Component
@Scope(SCOPE_PROTOTYPE)
public class GreetingActor extends UntypedActor {
private GreetingService greetingService;
public GreetingActor(GreetingService greetingService) {
this.greetingService = greetingService;
}
@Override
public void onReceive(Object message) throws Throwable {
if (message instanceof Greet) {
String name = ((Greet) message).getName();
getSender().tell(greetingService.greet(name), getSelf());
} else {
unhandled(message);
}
}
public static class Greet {
private String name;
public Greet(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}

View File

@ -0,0 +1,12 @@
package org.baeldung.akka;
import org.springframework.stereotype.Component;
@Component
public class GreetingService {
public String greet(String name) {
return "Hello, " + name;
}
}

View File

@ -0,0 +1,28 @@
package org.baeldung.akka;
import akka.actor.Actor;
import akka.actor.IndirectActorProducer;
import org.springframework.context.ApplicationContext;
public class SpringActorProducer implements IndirectActorProducer {
private ApplicationContext applicationContext;
private String beanActorName;
public SpringActorProducer(ApplicationContext applicationContext, String beanActorName) {
this.applicationContext = applicationContext;
this.beanActorName = beanActorName;
}
@Override
public Actor produce() {
return (Actor) applicationContext.getBean(beanActorName);
}
@Override
public Class<? extends Actor> actorClass() {
return (Class<? extends Actor>) applicationContext.getType(beanActorName);
}
}

View File

@ -0,0 +1,33 @@
package org.baeldung.akka;
import akka.actor.AbstractExtensionId;
import akka.actor.ExtendedActorSystem;
import akka.actor.Extension;
import akka.actor.Props;
import org.springframework.context.ApplicationContext;
public class SpringExtension extends AbstractExtensionId<SpringExtension.SpringExt> {
public static final SpringExtension SPRING_EXTENSION_PROVIDER = new SpringExtension();
@Override
public SpringExt createExtension(ExtendedActorSystem system) {
return new SpringExt();
}
public static class SpringExt implements Extension {
private volatile ApplicationContext applicationContext;
public void initialize(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public Props props(String actorBeanName) {
return Props.create(SpringActorProducer.class, applicationContext, actorBeanName);
}
}
}

View File

@ -1,6 +1,6 @@
package com.baledung.controller; package org.baeldung.controller.controller;
import com.baledung.student.Student; import org.baeldung.controller.student.Student;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;

View File

@ -1,6 +1,6 @@
package com.baledung.controller; package org.baeldung.controller.controller;
import com.baledung.student.Student; import org.baeldung.controller.student.Student;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;

View File

@ -2,7 +2,7 @@
/** /**
* @author Prashant Dutta * @author Prashant Dutta
*/ */
package com.baledung.controller; package org.baeldung.controller.controller;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;

View File

@ -1,4 +1,4 @@
package com.baledung.student; package org.baeldung.controller.student;
public class Student { public class Student {
private String name; private String name;

View File

@ -10,7 +10,7 @@
http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.baledung.controller" /> <context:component-scan base-package="org.baeldung.controller.controller" />
<mvc:annotation-driven /> <mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

View File

@ -0,0 +1,48 @@
package org.baeldung.akka;
import java.util.concurrent.TimeUnit;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.util.Timeout;
import org.baeldung.akka.GreetingActor.Greet;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import scala.concurrent.Await;
import scala.concurrent.Future;
import scala.concurrent.duration.FiniteDuration;
import static akka.pattern.Patterns.ask;
import static org.baeldung.akka.SpringExtension.SPRING_EXTENSION_PROVIDER;
@ContextConfiguration(classes = AppConfiguration.class)
public class SpringAkkaTest extends AbstractJUnit4SpringContextTests {
@Autowired
private ActorSystem system;
@Test
public void whenCallingGreetingActor_thenActorGreetsTheCaller() throws Exception {
ActorRef greeter = system.actorOf(
SPRING_EXTENSION_PROVIDER.get(system)
.props("greetingActor"), "greeter");
FiniteDuration duration = FiniteDuration.create(1, TimeUnit.SECONDS);
Timeout timeout = Timeout.durationToTimeout(duration);
Future<Object> result = ask(greeter, new Greet("John"), timeout);
Assert.assertEquals("Hello, John", Await.result(result, duration));
}
@After
public void tearDown() {
system.shutdown();
system.awaitTermination();
}
}

View File

@ -1,4 +1,4 @@
package com.baledung.test; package org.baeldung.controller;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
@ -14,7 +14,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import com.baledung.student.Student; import org.baeldung.controller.student.Student;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)

View File

@ -1,56 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>spring-controller</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
</dependencies>
</project>

89
spring-cucumber/pom.xml Normal file
View File

@ -0,0 +1,89 @@
<?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>spring-cucumber</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-cucumber</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<cucumber.java.version>1.2.4</cucumber.java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-core</artifactId>
<version>${cucumber.java.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumber.java.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>${cucumber.java.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-spring</artifactId>
<version>${cucumber.java.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-io -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,22 @@
package com.baeldung;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class BaeldungController {
@RequestMapping(method={RequestMethod.GET},value={"/hello"})
public String sayHello(HttpServletResponse response){
return "hello";
}
@RequestMapping(method={RequestMethod.POST},value={"/baeldung"})
public String sayHelloPost(HttpServletResponse response){
return "hello";
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
@SpringBootApplication
public class SpringDemoApplication extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(SpringDemoApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application){
return application.sources(SpringDemoApplication.class);
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class VersionController {
@RequestMapping(method={RequestMethod.GET},value={"/version"})
public String getVersion(){
return "1.0";
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test/resources")
public class CucumberTest{
}

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