Merge remote-tracking branch 'upstream/master' into craedel-spring-cloud-config
This commit is contained in:
commit
756f483348
@ -1,26 +1,27 @@
|
||||
package com.baeldung.dozer;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.dozer.DozerBeanMapper;
|
||||
import org.dozer.loader.api.BeanMappingBuilder;
|
||||
import org.junit.Before;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DozerTest {
|
||||
private final long GMT_DIFFERENCE = 46800000;
|
||||
|
||||
private DozerBeanMapper mapper = new DozerBeanMapper();
|
||||
DozerBeanMapper mapper;
|
||||
|
||||
@Before
|
||||
public void before() throws Exception {
|
||||
mapper = new DozerBeanMapper();
|
||||
}
|
||||
|
||||
private BeanMappingBuilder builder = new BeanMappingBuilder() {
|
||||
BeanMappingBuilder builder = new BeanMappingBuilder() {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
@ -29,7 +30,7 @@ public class DozerTest {
|
||||
|
||||
}
|
||||
};
|
||||
private BeanMappingBuilder builderMinusAge = new BeanMappingBuilder() {
|
||||
BeanMappingBuilder builderMinusAge = new BeanMappingBuilder() {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
@ -41,10 +42,12 @@ public class DozerTest {
|
||||
|
||||
@Test
|
||||
public void givenApiMapper_whenMaps_thenCorrect() {
|
||||
mapper.addMapping(builder);
|
||||
|
||||
Personne frenchAppPerson = new Personne("Sylvester Stallone", "Rambo",
|
||||
70);
|
||||
mapper.addMapping(builder);
|
||||
Person englishAppPerson = mapper.map(frenchAppPerson, Person.class);
|
||||
|
||||
assertEquals(englishAppPerson.getName(), frenchAppPerson.getNom());
|
||||
assertEquals(englishAppPerson.getNickname(),
|
||||
frenchAppPerson.getSurnom());
|
||||
@ -53,9 +56,11 @@ public class DozerTest {
|
||||
|
||||
@Test
|
||||
public void givenApiMapper_whenMapsOnlySpecifiedFields_thenCorrect() {
|
||||
Person englishAppPerson = new Person("Sylvester Stallone", "Rambo", 70);
|
||||
mapper.addMapping(builderMinusAge);
|
||||
|
||||
Person englishAppPerson = new Person("Sylvester Stallone", "Rambo", 70);
|
||||
Personne frenchAppPerson = mapper.map(englishAppPerson, Personne.class);
|
||||
|
||||
assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName());
|
||||
assertEquals(frenchAppPerson.getSurnom(),
|
||||
englishAppPerson.getNickname());
|
||||
@ -64,9 +69,11 @@ public class DozerTest {
|
||||
|
||||
@Test
|
||||
public void givenApiMapper_whenMapsBidirectionally_thenCorrect() {
|
||||
Person englishAppPerson = new Person("Sylvester Stallone", "Rambo", 70);
|
||||
mapper.addMapping(builder);
|
||||
|
||||
Person englishAppPerson = new Person("Sylvester Stallone", "Rambo", 70);
|
||||
Personne frenchAppPerson = mapper.map(englishAppPerson, Personne.class);
|
||||
|
||||
assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName());
|
||||
assertEquals(frenchAppPerson.getSurnom(),
|
||||
englishAppPerson.getNickname());
|
||||
@ -100,12 +107,12 @@ public class DozerTest {
|
||||
|
||||
@Test
|
||||
public void givenSrcAndDestWithDifferentFieldNamesWithCustomMapper_whenMaps_thenCorrect() {
|
||||
List<String> mappingFiles = new ArrayList<>();
|
||||
mappingFiles.add("dozer_mapping.xml");
|
||||
configureMapper("dozer_mapping.xml");
|
||||
|
||||
Personne frenchAppPerson = new Personne("Sylvester Stallone", "Rambo",
|
||||
70);
|
||||
mapper.setMappingFiles(mappingFiles);
|
||||
Person englishAppPerson = mapper.map(frenchAppPerson, Person.class);
|
||||
|
||||
assertEquals(englishAppPerson.getName(), frenchAppPerson.getNom());
|
||||
assertEquals(englishAppPerson.getNickname(),
|
||||
frenchAppPerson.getSurnom());
|
||||
@ -114,38 +121,39 @@ public class DozerTest {
|
||||
|
||||
@Test
|
||||
public void givenSrcAndDestWithDifferentFieldNamesWithCustomMapper_whenMapsBidirectionally_thenCorrect() {
|
||||
List<String> mappingFiles = new ArrayList<>();
|
||||
mappingFiles.add("dozer_mapping.xml");
|
||||
configureMapper("dozer_mapping.xml");
|
||||
|
||||
Person englishAppPerson = new Person("Dwayne Johnson", "The Rock", 44);
|
||||
mapper.setMappingFiles(mappingFiles);
|
||||
Personne frenchAppPerson = mapper.map(englishAppPerson, Personne.class);
|
||||
|
||||
assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName());
|
||||
assertEquals(frenchAppPerson.getSurnom(),
|
||||
englishAppPerson.getNickname());
|
||||
assertEquals(frenchAppPerson.getAge(), englishAppPerson.getAge());
|
||||
}
|
||||
|
||||
// @Test
|
||||
// public void givenMappingFileOutsideClasspath_whenMaps_thenCorrect() {
|
||||
// List<String> mappingFiles = new ArrayList<>();
|
||||
// mappingFiles.add("file:E:\\dozer_mapping.xml");
|
||||
// Person englishAppPerson = new Person("Marshall Bruce Mathers III",
|
||||
// "Eminem", 43);
|
||||
// mapper.setMappingFiles(mappingFiles);
|
||||
// Personne frenchAppPerson = mapper.map(englishAppPerson, Personne.class);
|
||||
// assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName());
|
||||
// assertEquals(frenchAppPerson.getSurnom(),
|
||||
// englishAppPerson.getNickname());
|
||||
// assertEquals(frenchAppPerson.getAge(), englishAppPerson.getAge());
|
||||
// }
|
||||
@Ignore("place dozer_mapping.xml at a location of your choice and copy/paste the path after file: in configureMapper method")
|
||||
@Test
|
||||
public void givenMappingFileOutsideClasspath_whenMaps_thenCorrect() {
|
||||
configureMapper("file:e:/dozer_mapping.xml");
|
||||
|
||||
Person englishAppPerson = new Person("Marshall Bruce Mathers III",
|
||||
"Eminem", 43);
|
||||
Personne frenchAppPerson = mapper.map(englishAppPerson, Personne.class);
|
||||
|
||||
assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName());
|
||||
assertEquals(frenchAppPerson.getSurnom(),
|
||||
englishAppPerson.getNickname());
|
||||
assertEquals(frenchAppPerson.getAge(), englishAppPerson.getAge());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSrcAndDest_whenMapsOnlySpecifiedFields_thenCorrect() {
|
||||
List<String> mappingFiles = new ArrayList<>();
|
||||
mappingFiles.add("dozer_mapping2.xml");
|
||||
configureMapper("dozer_mapping2.xml");
|
||||
|
||||
Person englishAppPerson = new Person("Shawn Corey Carter", "Jay Z", 46);
|
||||
mapper.setMappingFiles(mappingFiles);
|
||||
Personne frenchAppPerson = mapper.map(englishAppPerson, Personne.class);
|
||||
|
||||
assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName());
|
||||
assertEquals(frenchAppPerson.getSurnom(),
|
||||
englishAppPerson.getNickname());
|
||||
@ -177,24 +185,35 @@ public class DozerTest {
|
||||
|
||||
@Test
|
||||
public void givenSrcAndDestWithDifferentFieldTypes_whenAbleToCustomConvert_thenCorrect() {
|
||||
configureMapper("dozer_custom_convertor.xml");
|
||||
|
||||
String dateTime = "2007-06-26T21:22:39Z";
|
||||
long timestamp = new Long("1182882159000");
|
||||
|
||||
Person3 person = new Person3("Rich", dateTime);
|
||||
mapper.setMappingFiles(Arrays
|
||||
.asList(new String[] { "dozer_custom_convertor.xml" }));
|
||||
Personne3 person0 = mapper.map(person, Personne3.class);
|
||||
assertEquals(timestamp, person0.getDtob());
|
||||
|
||||
long timestampToTest = person0.getDtob();
|
||||
assertTrue(timestampToTest == timestamp
|
||||
|| timestampToTest >= timestamp - GMT_DIFFERENCE
|
||||
|| timestampToTest <= timestamp + GMT_DIFFERENCE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSrcAndDestWithDifferentFieldTypes_whenAbleToCustomConvertBidirectionally_thenCorrect() {
|
||||
String dateTime = "2007-06-26T21:22:39Z";
|
||||
long timestamp = new Long("1182882159000");
|
||||
Personne3 person = new Personne3("Rich", timestamp);
|
||||
mapper.setMappingFiles(Arrays
|
||||
.asList(new String[] { "dozer_custom_convertor.xml" }));
|
||||
configureMapper("dozer_custom_convertor.xml");
|
||||
|
||||
Person3 person0 = mapper.map(person, Person3.class);
|
||||
assertEquals(dateTime, person0.getDtob());
|
||||
String timestampTest = person0.getDtob();
|
||||
|
||||
assertTrue(timestampTest.charAt(10) == 'T'
|
||||
&& timestampTest.charAt(19) == 'Z');
|
||||
}
|
||||
|
||||
public void configureMapper(String... mappingFileUrls) {
|
||||
mapper.setMappingFiles(Arrays.asList(mappingFileUrls));
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -16,16 +16,13 @@ public class GuavaMapFromSetTests {
|
||||
@Test
|
||||
public void givenStringSet_whenMapsToElementLength_thenCorrect() {
|
||||
Function<Integer, String> function = new Function<Integer, String>() {
|
||||
|
||||
@Override
|
||||
public String apply(Integer from) {
|
||||
return Integer.toBinaryString(from.intValue());
|
||||
return Integer.toBinaryString(from);
|
||||
}
|
||||
};
|
||||
Set<Integer> set = (Set<Integer>) new TreeSet<Integer>(Arrays.asList(
|
||||
32, 64, 128));
|
||||
Map<Integer, String> map = new GuavaMapFromSet<Integer, String>(set,
|
||||
function);
|
||||
Set<Integer> set = new TreeSet<>(Arrays.asList(32, 64, 128));
|
||||
Map<Integer, String> map = new GuavaMapFromSet<Integer, String>(set, function);
|
||||
assertTrue(map.get(32).equals("100000")
|
||||
&& map.get(64).equals("1000000")
|
||||
&& map.get(128).equals("10000000"));
|
||||
@ -40,13 +37,14 @@ public class GuavaMapFromSetTests {
|
||||
return from.length();
|
||||
}
|
||||
};
|
||||
Set<String> set = (Set<String>) new TreeSet<String>(Arrays.asList(
|
||||
Set<String> set = new TreeSet<>(Arrays.asList(
|
||||
"four", "three", "twelve"));
|
||||
Map<String, Integer> map = new GuavaMapFromSet<String, Integer>(set,
|
||||
function);
|
||||
assertTrue(map.get("four") == 4 && map.get("three") == 5
|
||||
&& map.get("twelve") == 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSet_whenNewSetElementAddedAndMappedLive_thenCorrect() {
|
||||
Function<String, Integer> function = new Function<String, Integer>() {
|
||||
@ -56,7 +54,7 @@ public class GuavaMapFromSetTests {
|
||||
return from.length();
|
||||
}
|
||||
};
|
||||
Set<String> set = (Set<String>) new TreeSet<String>(Arrays.asList(
|
||||
Set<String> set = new TreeSet<>(Arrays.asList(
|
||||
"four", "three", "twelve"));
|
||||
Map<String, Integer> map = new GuavaMapFromSet<String, Integer>(set,
|
||||
function);
|
||||
|
@ -6,3 +6,4 @@
|
||||
### Relevant Articles:
|
||||
- [JMockit 101](http://www.baeldung.com/jmockit-101)
|
||||
- [A Guide to JMockit Expectations](http://www.baeldung.com/jmockit-expectations)
|
||||
- [JMockit Advanced Topics](http://www.baeldung.com/jmockit-advanced-topics)
|
||||
|
@ -0,0 +1,20 @@
|
||||
package org.baeldung.mocks.jmockit;
|
||||
|
||||
public class AdvancedCollaborator {
|
||||
int i;
|
||||
private int privateField = 5;
|
||||
public AdvancedCollaborator(){}
|
||||
public AdvancedCollaborator(String string) throws Exception{
|
||||
i = string.length();
|
||||
}
|
||||
public String methodThatCallsPrivateMethod(int i){
|
||||
return privateMethod() + i;
|
||||
}
|
||||
public int methodThatReturnsThePrivateField(){
|
||||
return privateField;
|
||||
}
|
||||
private String privateMethod(){
|
||||
return "default:";
|
||||
}
|
||||
class InnerAdvancedCollaborator{}
|
||||
}
|
@ -0,0 +1,110 @@
|
||||
package org.baeldung.mocks.jmockit;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.baeldung.mocks.jmockit.AdvancedCollaborator.InnerAdvancedCollaborator;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import mockit.Deencapsulation;
|
||||
import mockit.Expectations;
|
||||
import mockit.Invocation;
|
||||
import mockit.Mock;
|
||||
import mockit.MockUp;
|
||||
import mockit.Mocked;
|
||||
import mockit.Tested;
|
||||
import mockit.integration.junit4.JMockit;
|
||||
|
||||
@RunWith(JMockit.class)
|
||||
public class AdvancedCollaboratorTest<MultiMock extends List<String> & Comparable<List<String>>> {
|
||||
|
||||
@Tested
|
||||
private AdvancedCollaborator mock;
|
||||
|
||||
@Mocked
|
||||
private MultiMock multiMock;
|
||||
|
||||
@Test
|
||||
public void testToMockUpPrivateMethod() {
|
||||
new MockUp<AdvancedCollaborator>() {
|
||||
@Mock
|
||||
private String privateMethod() {
|
||||
return "mocked: ";
|
||||
}
|
||||
};
|
||||
String res = mock.methodThatCallsPrivateMethod(1);
|
||||
assertEquals("mocked: 1", res);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToMockUpDifficultConstructor() throws Exception {
|
||||
new MockUp<AdvancedCollaborator>() {
|
||||
@Mock
|
||||
public void $init(Invocation invocation, String string) {
|
||||
((AdvancedCollaborator) invocation.getInvokedInstance()).i = 1;
|
||||
}
|
||||
};
|
||||
AdvancedCollaborator coll = new AdvancedCollaborator(null);
|
||||
assertEquals(1, coll.i);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToCallPrivateMethodsDirectly() {
|
||||
Object value = Deencapsulation.invoke(mock, "privateMethod");
|
||||
assertEquals("default:", value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToSetPrivateFieldDirectly() {
|
||||
Deencapsulation.setField(mock, "privateField", 10);
|
||||
assertEquals(10, mock.methodThatReturnsThePrivateField());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToGetPrivateFieldDirectly() {
|
||||
int value = Deencapsulation.getField(mock, "privateField");
|
||||
assertEquals(5, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToCreateNewInstanceDirectly() {
|
||||
AdvancedCollaborator coll = Deencapsulation.newInstance(AdvancedCollaborator.class, "foo");
|
||||
assertEquals(3, coll.i);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToCreateNewInnerClassInstanceDirectly() {
|
||||
InnerAdvancedCollaborator innerCollaborator = Deencapsulation.newInnerInstance(InnerAdvancedCollaborator.class, mock);
|
||||
assertNotNull(innerCollaborator);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void testMultipleInterfacesWholeTest() {
|
||||
new Expectations() {
|
||||
{
|
||||
multiMock.get(5); result = "foo";
|
||||
multiMock.compareTo((List<String>) any); result = 0;
|
||||
}
|
||||
};
|
||||
assertEquals("foo", multiMock.get(5));
|
||||
assertEquals(0, multiMock.compareTo(new ArrayList<>()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public <M extends List<String> & Comparable<List<String>>> void testMultipleInterfacesOneMethod(@Mocked M mock) {
|
||||
new Expectations() {
|
||||
{
|
||||
mock.get(5); result = "foo";
|
||||
mock.compareTo((List<String>) any);
|
||||
result = 0; }
|
||||
};
|
||||
assertEquals("foo", mock.get(5));
|
||||
assertEquals(0, mock.compareTo(new ArrayList<>()));
|
||||
}
|
||||
}
|
@ -0,0 +1,57 @@
|
||||
package org.baeldung.mocks.jmockit;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import mockit.Expectations;
|
||||
import mockit.Injectable;
|
||||
import mockit.Mocked;
|
||||
import mockit.Tested;
|
||||
import mockit.Verifications;
|
||||
import mockit.integration.junit4.JMockit;
|
||||
|
||||
@RunWith(JMockit.class)
|
||||
public class ReusingTest {
|
||||
|
||||
@Injectable
|
||||
private Collaborator collaborator;
|
||||
|
||||
@Mocked
|
||||
private Model model;
|
||||
|
||||
@Tested
|
||||
private Performer performer;
|
||||
|
||||
@Before
|
||||
public void setup(){
|
||||
new Expectations(){{
|
||||
model.getInfo(); result = "foo"; minTimes = 0;
|
||||
collaborator.collaborate("foo"); result = true; minTimes = 0;
|
||||
}};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithSetup() {
|
||||
performer.perform(model);
|
||||
verifyTrueCalls(1);
|
||||
}
|
||||
|
||||
protected void verifyTrueCalls(int calls){
|
||||
new Verifications(){{
|
||||
collaborator.receive(true); times = calls;
|
||||
}};
|
||||
}
|
||||
|
||||
final class TrueCallsVerification extends Verifications{
|
||||
public TrueCallsVerification(int calls){
|
||||
collaborator.receive(true); times = calls;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithFinalClass() {
|
||||
performer.perform(model);
|
||||
new TrueCallsVerification(1);
|
||||
}
|
||||
}
|
2
pom.xml
2
pom.xml
@ -16,6 +16,7 @@
|
||||
<module>assertj</module>
|
||||
<module>apache-cxf</module>
|
||||
<module>apache-fop</module>
|
||||
<module>autovalue-tutorial</module>
|
||||
<module>core-java</module>
|
||||
<module>core-java-8</module>
|
||||
<module>couchbase-sdk-intro</module>
|
||||
@ -52,6 +53,7 @@
|
||||
<module>log4j</module>
|
||||
|
||||
<module>spring-all</module>
|
||||
<module>spring-akka</module>
|
||||
<module>spring-apache-camel</module>
|
||||
<module>spring-autowire</module>
|
||||
<module>spring-batch</module>
|
||||
|
80
spring-akka/pom.xml
Normal file
80
spring-akka/pom.xml
Normal file
@ -0,0 +1,80 @@
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-akka</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
|
||||
<name>spring-akka</name>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-actor_2.11</artifactId>
|
||||
<version>${akka.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-framework-bom</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</dependencyManagement>
|
||||
|
||||
<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>
|
||||
|
||||
<properties>
|
||||
<spring.version>4.3.2.RELEASE</spring.version>
|
||||
<akka.version>2.4.8</akka.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
|
||||
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -1,13 +1,12 @@
|
||||
package org.baeldung.akka;
|
||||
|
||||
import akka.actor.UntypedActor;
|
||||
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
|
||||
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)
|
||||
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
|
||||
public class GreetingActor extends UntypedActor {
|
||||
|
||||
private GreetingService greetingService;
|
@ -87,14 +87,6 @@
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Akka -->
|
||||
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-actor_2.11</artifactId>
|
||||
<version>2.4.8</version>
|
||||
</dependency>
|
||||
|
||||
<!-- util -->
|
||||
|
||||
<dependency>
|
||||
|
@ -0,0 +1,37 @@
|
||||
package org.baeldung.controller.config;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRegistration;
|
||||
|
||||
import org.springframework.web.WebApplicationInitializer;
|
||||
import org.springframework.web.context.ContextLoaderListener;
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
import org.springframework.web.context.support.GenericWebApplicationContext;
|
||||
import org.springframework.web.servlet.DispatcherServlet;
|
||||
|
||||
public class StudentControllerConfig implements WebApplicationInitializer {
|
||||
|
||||
|
||||
@Override
|
||||
public void onStartup(ServletContext sc) throws ServletException {
|
||||
AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
|
||||
root.register(WebConfig.class);
|
||||
|
||||
root.refresh();
|
||||
root.setServletContext(sc);
|
||||
|
||||
// Manages the lifecycle of the root application context
|
||||
sc.addListener(new ContextLoaderListener(root));
|
||||
|
||||
|
||||
|
||||
DispatcherServlet dv =new DispatcherServlet(new GenericWebApplicationContext());
|
||||
|
||||
ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc",dv );
|
||||
appServlet.setLoadOnStartup(1);
|
||||
appServlet.addMapping("/test/*");
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,28 @@
|
||||
package org.baeldung.controller.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.ViewResolver;
|
||||
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan(basePackages= {"org.baeldung.controller.controller","org.baeldung.controller.config" })
|
||||
public class WebConfig extends WebMvcConfigurerAdapter {
|
||||
@Override
|
||||
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
|
||||
configurer.enable();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ViewResolver viewResolver() {
|
||||
InternalResourceViewResolver bean = new InternalResourceViewResolver();
|
||||
bean.setPrefix("/WEB-INF/");
|
||||
bean.setSuffix(".jsp");
|
||||
return bean;
|
||||
}
|
||||
}
|
@ -0,0 +1,86 @@
|
||||
package org.baeldung.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.baeldung.controller.config.WebConfig;
|
||||
import org.baeldung.controller.student.Student;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes={WebConfig.class}, loader=AnnotationConfigWebContextLoader.class )
|
||||
public class ControllerAnnotationTest {
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext wac;
|
||||
|
||||
private Student selectedStudent;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
|
||||
|
||||
selectedStudent = new Student();
|
||||
selectedStudent.setId(1);
|
||||
selectedStudent.setName("Peter");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTestController() throws Exception {
|
||||
|
||||
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/"))
|
||||
.andReturn()
|
||||
.getModelAndView();
|
||||
|
||||
// validate modal data
|
||||
Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man");
|
||||
|
||||
// validate view name
|
||||
Assert.assertSame(mv.getViewName(), "welcome");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRestController() throws Exception {
|
||||
|
||||
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1))
|
||||
.andReturn().getResponse()
|
||||
.getContentAsString();
|
||||
|
||||
ObjectMapper reader = new ObjectMapper();
|
||||
|
||||
Student studentDetails = reader.readValue(responseBody, Student.class);
|
||||
|
||||
Assert.assertEquals(selectedStudent, studentDetails);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRestAnnotatedController() throws Exception {
|
||||
|
||||
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1))
|
||||
.andReturn().getResponse()
|
||||
.getContentAsString();
|
||||
|
||||
ObjectMapper reader = new ObjectMapper();
|
||||
|
||||
Student studentDetails = reader.readValue(responseBody, Student.class);
|
||||
|
||||
Assert.assertEquals(selectedStudent, studentDetails);
|
||||
}
|
||||
|
||||
}
|
@ -135,6 +135,27 @@
|
||||
<artifactId>el-api</artifactId>
|
||||
<version>2.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.derby</groupId>
|
||||
<artifactId>derby</artifactId>
|
||||
<version>10.12.1.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.derby</groupId>
|
||||
<artifactId>derbyclient</artifactId>
|
||||
<version>10.12.1.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.derby</groupId>
|
||||
<artifactId>derbynet</artifactId>
|
||||
<version>10.12.1.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.derby</groupId>
|
||||
<artifactId>derbytools</artifactId>
|
||||
<version>10.12.1.1</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -20,7 +20,7 @@ import com.google.common.base.Preconditions;
|
||||
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@PropertySource({ "classpath:persistence-mysql.properties" })
|
||||
@PropertySource({ "classpath:persistence-derby.properties" })
|
||||
@ComponentScan({ "org.baeldung.persistence" })
|
||||
public class Cause1NonTransientConfig {
|
||||
|
||||
|
@ -20,7 +20,7 @@ import com.google.common.base.Preconditions;
|
||||
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@PropertySource({ "classpath:persistence-mysql.properties" })
|
||||
@PropertySource({ "classpath:persistence-derby.properties" })
|
||||
@ComponentScan({ "org.baeldung.persistence" })
|
||||
public class Cause4NonTransientConfig {
|
||||
|
||||
@ -72,5 +72,4 @@ public class Cause4NonTransientConfig {
|
||||
// hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
|
||||
return hibernateProperties;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,10 @@
|
||||
# jdbc.X
|
||||
jdbc.driverClassName=org.apache.derby.jdbc.EmbeddedDriver
|
||||
jdbc.url=jdbc:derby:memory:spring_exceptions;create=true
|
||||
jdbc.user=tutorialuser
|
||||
jdbc.pass=tutorialpass
|
||||
|
||||
# hibernate.X
|
||||
hibernate.dialect=org.hibernate.dialect.DerbyDialect
|
||||
hibernate.show_sql=false
|
||||
hibernate.hbm2ddl.auto=create
|
@ -25,7 +25,12 @@ public class InvalidResourceUsageExceptionTest {
|
||||
|
||||
@Test(expected = InvalidDataAccessResourceUsageException.class)
|
||||
public void whenRetrievingDataUserNoSelectRights_thenInvalidResourceUsageException() {
|
||||
final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource);
|
||||
jdbcTemplate.execute("revoke select from tutorialuser");
|
||||
|
||||
fooService.findAll();
|
||||
|
||||
jdbcTemplate.execute("grant select to tutorialuser");
|
||||
}
|
||||
|
||||
@Test(expected = BadSqlGrammarException.class)
|
||||
|
@ -1,27 +0,0 @@
|
||||
package org.baeldung.ex.nontransientdataaccessexception;
|
||||
|
||||
import org.baeldung.ex.nontransientexception.cause.Cause1NonTransientConfig;
|
||||
import org.baeldung.persistence.model.Foo;
|
||||
import org.baeldung.persistence.service.IFooService;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.dao.PermissionDeniedDataAccessException;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
public class PermissionDeniedException {
|
||||
|
||||
@Autowired
|
||||
private IFooService fooService;
|
||||
|
||||
@Test(expected = PermissionDeniedDataAccessException.class)
|
||||
public void whenRetrievingDataUserNoSelectRights_thenPermissionDeniedException() {
|
||||
final Foo foo = new Foo("foo");
|
||||
fooService.create(foo);
|
||||
}
|
||||
|
||||
}
|
@ -1,16 +1,23 @@
|
||||
package com.baeldung.web.controller;
|
||||
|
||||
import com.baeldung.model.Company;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.ModelMap;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.bind.annotation.MatrixVariable;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import com.baeldung.model.Company;
|
||||
|
||||
@Controller
|
||||
public class CompanyController {
|
||||
@ -22,13 +29,15 @@ public class CompanyController {
|
||||
return new ModelAndView("companyHome", "company", new Company());
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/company/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET)
|
||||
@RequestMapping(value = "/company/{Id}", produces = { "application/json",
|
||||
"application/xml" }, method = RequestMethod.GET)
|
||||
public @ResponseBody Company getCompanyById(@PathVariable final long Id) {
|
||||
return companyMap.get(Id);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/addCompany", method = RequestMethod.POST)
|
||||
public String submit(@ModelAttribute("company") final Company company, final BindingResult result, final ModelMap model) {
|
||||
public String submit(@ModelAttribute("company") final Company company,
|
||||
final BindingResult result, final ModelMap model) {
|
||||
if (result.hasErrors()) {
|
||||
return "error";
|
||||
}
|
||||
@ -42,15 +51,30 @@ public class CompanyController {
|
||||
|
||||
@RequestMapping(value = "/companyEmployee/{company}/employeeData/{employee}", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public ResponseEntity<Map<String, String>> getEmployeeDataFromCompany(@MatrixVariable(pathVar = "employee") final Map<String, String> matrixVars) {
|
||||
public ResponseEntity<Map<String, String>> getEmployeeDataFromCompany(
|
||||
@MatrixVariable(pathVar = "employee") final Map<String, String> matrixVars) {
|
||||
return new ResponseEntity<>(matrixVars, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/companyData/{company}/employeeData/{employee}", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public ResponseEntity<Map<String, String>> getCompanyName(@MatrixVariable(value = "name", pathVar = "company") final String name) {
|
||||
public ResponseEntity<Map<String, String>> getCompanyName(
|
||||
@MatrixVariable(value = "name", pathVar = "company") final String name) {
|
||||
final Map<String, String> result = new HashMap<String, String>();
|
||||
result.put("name", name);
|
||||
return new ResponseEntity<>(result, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/companyResponseBody", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
public Company getCompanyResponseBody() {
|
||||
final Company company = new Company(2, "ABC");
|
||||
return company;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/companyResponseEntity", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<Company> getCompanyResponseEntity() {
|
||||
final Company company = new Company(3, "123");
|
||||
return new ResponseEntity<Company>(company, HttpStatus.OK);
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.web.controller.advice;
|
||||
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;
|
||||
|
||||
@ControllerAdvice
|
||||
public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice {
|
||||
|
||||
public JsonpControllerAdvice() {
|
||||
super("callback");
|
||||
}
|
||||
|
||||
}
|
66
spring-mvc-java/src/main/webapp/WEB-INF/view/index.jsp
Normal file
66
spring-mvc-java/src/main/webapp/WEB-INF/view/index.jsp
Normal file
@ -0,0 +1,66 @@
|
||||
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||
pageEncoding="ISO-8859-1" %>
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="ISO-8859-1">
|
||||
<title>Company Data</title>
|
||||
<script src="https://code.jquery.com/jquery-3.1.0.js"
|
||||
integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk="
|
||||
crossorigin="anonymous"></script>
|
||||
<script>
|
||||
$(document).ready(function(){
|
||||
$('#ResponseBody-button').click(function() {
|
||||
$.ajax({
|
||||
url: 'http://localhost:8080/spring-mvc-java/companyResponseBody?callback=getCompanyData',
|
||||
data: {
|
||||
format: 'json'
|
||||
},
|
||||
type: 'GET',
|
||||
jsonpCallback:'getCompanyData',
|
||||
dataType: 'jsonp',
|
||||
error: function() {
|
||||
$('#infoResponseBody').html('<p>An error has occurred</p>');
|
||||
},
|
||||
success: function(data) {
|
||||
console.log("sucess");
|
||||
}
|
||||
});
|
||||
});
|
||||
$('#ResponseEntity-button').click(function() {
|
||||
console.log("ResponseEntity");
|
||||
$.ajax({
|
||||
url: 'http://localhost:8080/spring-mvc-java/companyResponseEntity?callback=getCompanyData',
|
||||
data: {
|
||||
format: 'json'
|
||||
},
|
||||
type: 'GET',
|
||||
jsonpCallback:'getCompanyData',
|
||||
dataType: 'jsonp',
|
||||
error: function() {
|
||||
$('#infoResponseEntity').html('<p>An error has occurred</p>');
|
||||
},
|
||||
success: function(data) {
|
||||
console.log("sucess");
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function getCompanyData(data) {
|
||||
$("#response").append("<b>ID:</b> "+data.id+"<br/>");
|
||||
$("#response").append("<b>NAME:</b> "+data.name+"<br/>");
|
||||
$("#response").append("<br/>");
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!--Using @ResponseBody -->
|
||||
<button id="ResponseBody-button">Send AJAX JSON-P request!</button>
|
||||
|
||||
<div id="response"></div>
|
||||
|
||||
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,16 @@
|
||||
package org.baeldung.web.controller;
|
||||
|
||||
import org.baeldung.web.dto.Company;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class CompanyController {
|
||||
|
||||
@RequestMapping(value = "/companyRest", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public Company getCompanyRest() {
|
||||
final Company company = new Company(1, "Xpto");
|
||||
return company;
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package org.baeldung.web.controller.advice;
|
||||
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;
|
||||
|
||||
@ControllerAdvice
|
||||
public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice {
|
||||
|
||||
public JsonpControllerAdvice() {
|
||||
super("callback");
|
||||
}
|
||||
|
||||
}
|
38
spring-rest/src/main/java/org/baeldung/web/dto/Company.java
Normal file
38
spring-rest/src/main/java/org/baeldung/web/dto/Company.java
Normal file
@ -0,0 +1,38 @@
|
||||
package org.baeldung.web.dto;
|
||||
|
||||
public class Company {
|
||||
|
||||
private long id;
|
||||
private String name;
|
||||
|
||||
public Company() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Company(final long id, final String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Company [id=" + id + ", name=" + name + "]";
|
||||
}
|
||||
|
||||
}
|
44
spring-rest/src/main/webapp/WEB-INF/company.html
Normal file
44
spring-rest/src/main/webapp/WEB-INF/company.html
Normal file
@ -0,0 +1,44 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="ISO-8859-1">
|
||||
<title>Company Data</title>
|
||||
<script src="https://code.jquery.com/jquery-3.1.0.js"
|
||||
integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk="
|
||||
crossorigin="anonymous"></script>
|
||||
<script>
|
||||
$(document).ready(function(){
|
||||
$('#REST-button').click(function() {
|
||||
$.ajax({
|
||||
url: 'http://localhost:8080/spring-rest/companyRest?callback=getCompanyData',
|
||||
data: {
|
||||
format: 'json'
|
||||
},
|
||||
type: 'GET',
|
||||
jsonpCallback:'getCompanyData',
|
||||
dataType: 'jsonp',
|
||||
error: function() {
|
||||
$('#infoREST').html('<p>An error has occurred</p>');
|
||||
},
|
||||
success: function(data) {
|
||||
console.log("sucess");
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function getCompanyData(data) {
|
||||
document.write("<b>ID:</b> "+data.id+"<br/>");
|
||||
document.write("<b>NAME:</b> "+data.name+"<br/>");
|
||||
document.write("<br/>");
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- Using REST URL-->
|
||||
<button id="REST-button">Test REST JSON-P!</button>
|
||||
<div id="infoREST"></div>
|
||||
|
||||
</body>
|
||||
</html>
|
Loading…
x
Reference in New Issue
Block a user