Merge remote-tracking branch 'upstream/master'

Conflicts:
	hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java
This commit is contained in:
sbalachandran 2016-08-15 22:40:33 -04:00
commit f7995e42ae
542 changed files with 9449 additions and 5324 deletions

3
.gitmodules vendored Normal file
View File

@ -0,0 +1,3 @@
[submodule "testgitrepo"]
path = testgitrepo
url = /home/prd/Development/projects/idea/tutorials/spring-boot/src/main/resources/testgitrepo/

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType">
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="false"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_DISABLED_BUILDER" value="org.eclipse.wst.jsdt.core.javascriptValidator"/>
<mapAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
</launchConfiguration>

52
cdi/pom.xml Normal file
View File

@ -0,0 +1,52 @@
<?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>cdi</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<spring.version>4.3.1.RELEASE</spring.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.weld.se/weld-se-core -->
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-core</artifactId>
<version>2.3.5.Final</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,12 @@
package com.baeldung.interceptor;
import javax.interceptor.InterceptorBinding;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@InterceptorBinding
@Target( {ElementType.METHOD, ElementType.TYPE } )
@Retention(RetentionPolicy.RUNTIME )
public @interface Audited {}

View File

@ -0,0 +1,19 @@
package com.baeldung.interceptor;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import java.lang.reflect.Method;
@Audited @Interceptor
public class AuditedInterceptor {
public static boolean calledBefore = false;
public static boolean calledAfter = false;
@AroundInvoke
public Object auditMethod(InvocationContext ctx) throws Exception {
calledBefore = true;
Object result = ctx.proceed();
calledAfter = true;
return result;
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.service;
import com.baeldung.interceptor.Audited;
public class SuperService {
@Audited
public String deliverService(String uid) {
return uid;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.spring.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import javax.inject.Inject;
import java.util.List;
@Aspect
public class SpringTestAspect {
@Autowired
private List<String> accumulator;
@Around("execution(* com.baeldung.spring.service.SpringSuperService.*(..))")
public Object advice(ProceedingJoinPoint jp) throws Throwable {
String methodName = jp.getSignature().getName();
accumulator.add("Call to "+methodName);
Object obj = jp.proceed();
accumulator.add("Method called successfully: "+methodName);
return obj;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.spring.configuration;
import com.baeldung.spring.aspect.SpringTestAspect;
import com.baeldung.spring.service.SpringSuperService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableAspectJAutoProxy
public class AppConfig {
@Bean
public SpringSuperService springSuperService() {
return new SpringSuperService();
}
@Bean
public SpringTestAspect springTestAspect(){
return new SpringTestAspect();
}
@Bean
public List<String> getAccumulator(){
return new ArrayList<String>();
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.spring.service;
public class SpringSuperService {
public String getInfoFromService(String code){
return code;
}
}

View File

@ -0,0 +1,8 @@
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/beans_1_2.xsd">
<interceptors>
<class>com.baeldung.interceptor.AuditedInterceptor</class>
</interceptors>
</beans>

View File

@ -0,0 +1,42 @@
package com.baeldung.test;
import com.baeldung.interceptor.Audited;
import com.baeldung.interceptor.AuditedInterceptor;
import com.baeldung.service.SuperService;
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.InterceptionType;
import javax.enterprise.inject.spi.Interceptor;
import javax.enterprise.util.AnnotationLiteral;
import static javafx.beans.binding.Bindings.select;
public class TestInterceptor {
Weld weld;
WeldContainer container;
@Before
public void init(){
weld = new Weld();
container = weld.initialize();
}
@After
public void shutdown(){
weld.shutdown();
}
@Test
public void givenTheService_whenMethodAndInterceptorExecuted_thenOK() {
SuperService superService = container.select(SuperService.class).get();
String code = "123456";
superService.deliverService(code);
Assert.assertTrue(AuditedInterceptor.calledBefore);
Assert.assertTrue(AuditedInterceptor.calledAfter);
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.test;
import com.baeldung.spring.configuration.AppConfig;
import com.baeldung.spring.service.SpringSuperService;
import org.junit.Assert;
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.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import javax.inject.Inject;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {AppConfig.class})
public class TestSpringInterceptor {
@Autowired
SpringSuperService springSuperService;
@Autowired
private List<String> accumulator;
@Test
public void givenService_whenServiceAndAspectExecuted_thenOk(){
String code = "123456";
String result = springSuperService.getInfoFromService(code);
Assert.assertThat(accumulator.size(), is(2));
Assert.assertThat(accumulator.get(0),is("Call to getInfoFromService"));
Assert.assertThat(accumulator.get(1),is("Method called successfully: getInfoFromService"));
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.threadpool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.Collectors;
public class CountingTask extends RecursiveTask<Integer> {
private final TreeNode node;
public CountingTask(TreeNode node) {
this.node = node;
}
@Override
protected Integer compute() {
return node.value + node.children.stream()
.map(childNode -> new CountingTask(childNode).fork())
.collect(Collectors.summingInt(ForkJoinTask::join));
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.google.common.util.concurrent.MoreExecutors;
/**
* This class demonstrates the usage of Guava's exiting executor services that keep the VM from hanging.
* Without the exiting executor service, the task would hang indefinitely.
* This behaviour cannot be demonstrated in JUnit tests, as JUnit kills the VM after the tests.
*/
public class ExitingExecutorServiceExample {
public static void main(String... args) {
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
ExecutorService executorService = MoreExecutors.getExitingExecutorService(executor, 100, TimeUnit.MILLISECONDS);
executorService.submit(() -> {
while (true) {
}
});
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.threadpool;
import java.util.Set;
import com.google.common.collect.Sets;
public class TreeNode {
int value;
Set<TreeNode> children;
public TreeNode(int value, TreeNode... children) {
this.value = value;
this.children = Sets.newHashSet(children);
}
}

View File

@ -0,0 +1,190 @@
package com.baeldung.completablefuture;
import org.junit.Test;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CompletableFutureTest {
@Test
public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException {
Future<String> completableFuture = calculateAsync();
String result = completableFuture.get();
assertEquals("Hello", result);
}
public Future<String> calculateAsync() throws InterruptedException {
CompletableFuture<String> completableFuture = new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> {
Thread.sleep(500);
completableFuture.complete("Hello");
return null;
});
return completableFuture;
}
@Test
public void whenRunningCompletableFutureWithResult_thenGetMethodReturnsImmediately() throws InterruptedException, ExecutionException {
Future<String> completableFuture = CompletableFuture.completedFuture("Hello");
String result = completableFuture.get();
assertEquals("Hello", result);
}
@Test
public void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() throws ExecutionException, InterruptedException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello");
assertEquals("Hello", future.get());
}
@Test
public void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<Void> future = completableFuture.thenAccept(s -> System.out.println("Computation returned: " + s));
future.get();
}
@Test
public void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<Void> future = completableFuture.thenRun(() -> System.out.println("Computation finished."));
future.get();
}
@Test
public void whenAddingThenApplyToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future = completableFuture.thenApply(s -> s + " World");
assertEquals("Hello World", future.get());
}
@Test
public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
assertEquals("Hello World", completableFuture.get());
}
@Test
public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
.thenCombine(CompletableFuture.supplyAsync(() -> " World"),
(s1, s2) -> s1 + s2);
assertEquals("Hello World", completableFuture.get());
}
@Test
public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
CompletableFuture.supplyAsync(() -> "Hello")
.thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"),
(s1, s2) -> System.out.println(s1 + s2));
}
@Test
public void whenFutureCombinedWithAllOfCompletes_thenAllFuturesAreDone() throws ExecutionException, InterruptedException {
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Beautiful");
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "World");
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(future1, future2, future3);
// ...
combinedFuture.get();
assertTrue(future1.isDone());
assertTrue(future2.isDone());
assertTrue(future3.isDone());
String combined = Stream.of(future1, future2, future3)
.map(CompletableFuture::join)
.collect(Collectors.joining(" "));
assertEquals("Hello Beautiful World", combined);
}
@Test
public void whenFutureThrows_thenHandleMethodReceivesException() throws ExecutionException, InterruptedException {
String name = null;
// ...
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
if (name == null) {
throw new RuntimeException("Computation error!");
}
return "Hello, " + name;
}).handle((s, t) -> s != null ? s : "Hello, Stranger!");
assertEquals("Hello, Stranger!", completableFuture.get());
}
@Test(expected = ExecutionException.class)
public void whenCompletingFutureExceptionally_thenGetMethodThrows() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = new CompletableFuture<>();
// ...
completableFuture.completeExceptionally(new RuntimeException("Calculation failed!"));
// ...
completableFuture.get();
}
@Test
public void whenAddingThenApplyAsyncToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future = completableFuture.thenApplyAsync(s -> s + " World");
assertEquals("Hello World", future.get());
}
}

View File

@ -0,0 +1,146 @@
package com.baeldung.threadpool;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CoreThreadPoolTest {
@Test(timeout = 1000)
public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException {
CountDownLatch lock = new CountDownLatch(1);
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(() -> {
System.out.println("Hello World");
lock.countDown();
});
lock.await(1000, TimeUnit.MILLISECONDS);
}
@Test
public void whenUsingExecutorServiceAndFuture_thenCanWaitOnFutureResult() throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newFixedThreadPool(10);
Future<String> future = executorService.submit(() -> "Hello World");
String result = future.get();
assertEquals("Hello World", result);
}
@Test
public void whenUsingFixedThreadPool_thenCoreAndMaximumThreadSizeAreTheSame() {
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
executor.submit(() -> {
Thread.sleep(1000);
return null;
});
executor.submit(() -> {
Thread.sleep(1000);
return null;
});
executor.submit(() -> {
Thread.sleep(1000);
return null;
});
assertEquals(2, executor.getPoolSize());
assertEquals(1, executor.getQueue().size());
}
@Test
public void whenUsingCachedThreadPool_thenPoolSizeGrowsUnbounded() {
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
executor.submit(() -> {
Thread.sleep(1000);
return null;
});
executor.submit(() -> {
Thread.sleep(1000);
return null;
});
executor.submit(() -> {
Thread.sleep(1000);
return null;
});
assertEquals(3, executor.getPoolSize());
assertEquals(0, executor.getQueue().size());
}
@Test(timeout = 1000)
public void whenUsingSingleThreadPool_thenTasksExecuteSequentially() throws InterruptedException {
CountDownLatch lock = new CountDownLatch(2);
AtomicInteger counter = new AtomicInteger();
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
counter.set(1);
lock.countDown();
});
executor.submit(() -> {
counter.compareAndSet(1, 2);
lock.countDown();
});
lock.await(1000, TimeUnit.MILLISECONDS);
assertEquals(2, counter.get());
}
@Test(timeout = 1000)
public void whenSchedulingTask_thenTaskExecutesWithinGivenPeriod() throws InterruptedException {
CountDownLatch lock = new CountDownLatch(1);
ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
executor.schedule(() -> {
System.out.println("Hello World");
lock.countDown();
}, 500, TimeUnit.MILLISECONDS);
lock.await(1000, TimeUnit.MILLISECONDS);
}
@Test(timeout = 1000)
public void whenSchedulingTaskWithFixedPeriod_thenTaskExecutesMultipleTimes() throws InterruptedException {
CountDownLatch lock = new CountDownLatch(3);
ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> {
System.out.println("Hello World");
lock.countDown();
}, 500, 100, TimeUnit.MILLISECONDS);
lock.await();
future.cancel(true);
}
@Test
public void whenUsingForkJoinPool_thenSumOfTreeElementsIsCalculatedCorrectly() {
TreeNode tree = new TreeNode(5,
new TreeNode(3), new TreeNode(2,
new TreeNode(2), new TreeNode(8)));
ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
int sum = forkJoinPool.invoke(new CountingTask(tree));
assertEquals(20, sum);
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.threadpool;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class GuavaThreadPoolTest {
@Test
public void whenExecutingTaskWithDirectExecutor_thenTheTaskIsExecutedInTheCurrentThread() {
Executor executor = MoreExecutors.directExecutor();
AtomicBoolean executed = new AtomicBoolean();
executor.execute(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
executed.set(true);
});
assertTrue(executed.get());
}
@Test
public void whenJoiningFuturesWithAllAsList_thenCombinedFutureCompletesAfterAllFuturesComplete() throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executorService);
ListenableFuture<String> future1 = listeningExecutorService.submit(() -> "Hello");
ListenableFuture<String> future2 = listeningExecutorService.submit(() -> "World");
String greeting = Futures.allAsList(future1, future2).get()
.stream()
.collect(Collectors.joining(" "));
assertEquals("Hello World", greeting);
}
}

View File

@ -0,0 +1,44 @@
package org.baeldung.java.arrays;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Test;
public class ArraysJoinAndSplitJUnitTest {
private final String[] sauces = {"Marinara", "Olive Oil"};
private final String[] cheeses = {"Mozzarella", "Feta", "Parmesan"};
private final String[] vegetables = {"Olives", "Spinach", "Green Peppers"};
private final String[] customers = {"Jay", "Harry", "Ronnie", "Gary", "Ross"};
@Test
public void givenThreeStringArrays_whenJoiningIntoOneStringArray_shouldSucceed() {
String[] toppings = new String[sauces.length + cheeses.length + vegetables.length];
System.arraycopy(sauces, 0, toppings, 0, sauces.length);
int AddedSoFar = sauces.length;
System.arraycopy(cheeses, 0, toppings, AddedSoFar, cheeses.length);
AddedSoFar += cheeses.length;
System.arraycopy(vegetables, 0, toppings, AddedSoFar, vegetables.length);
Assert.assertArrayEquals(toppings,
new String[]{"Marinara", "Olive Oil", "Mozzarella", "Feta",
"Parmesan", "Olives", "Spinach", "Green Peppers"});
}
@Test
public void givenOneStringArray_whenSplittingInHalfTwoStringArrays_shouldSucceed() {
int ordersHalved = (customers.length / 2) + (customers.length % 2);
String[] driverOne = Arrays.copyOf(customers, ordersHalved);
String[] driverTwo = Arrays.copyOfRange(customers, ordersHalved, customers.length);
Assert.assertArrayEquals(driverOne, new String[]{"Jay", "Harry", "Ronnie"});
Assert.assertArrayEquals(driverTwo, new String[]{"Gary", "Ross"});
}
}

View File

@ -0,0 +1,62 @@
package org.baeldung.java.collections;
import java.util.ArrayList;
import java.util.Collections;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class CollectionsJoinAndSplitJUnitTest {
private ArrayList<String> sauces = new ArrayList<>();
private ArrayList<String> cheeses = new ArrayList<>();
private ArrayList<String> vegetables = new ArrayList<>();
private ArrayList<ArrayList<String>> ingredients = new ArrayList<>();
@Before
public void init() {
sauces.add("Olive Oil");
sauces.add("Marinara");
cheeses.add("Mozzarella");
cheeses.add("Feta");
cheeses.add("Parmesan");
vegetables.add("Olives");
vegetables.add("Spinach");
vegetables.add("Green Peppers");
ingredients.add(sauces);
ingredients.add(cheeses);
ingredients.add(vegetables);
}
@Test
public void givenThreeArrayLists_whenJoiningIntoOneArrayList_shouldSucceed() {
ArrayList<ArrayList<String>> toppings = new ArrayList<>();
toppings.add(sauces);
toppings.add(cheeses);
toppings.add(vegetables);
Assert.assertTrue(toppings.size() == 3);
Assert.assertTrue(toppings.contains(sauces));
Assert.assertTrue(toppings.contains(cheeses));
Assert.assertTrue(toppings.contains(vegetables));
}
@Test
public void givenOneArrayList_whenSplittingIntoTwoArrayLists_shouldSucceed() {
ArrayList<ArrayList<String>> removedToppings = new ArrayList<>();
removedToppings.add(ingredients.remove(ingredients.indexOf(vegetables)));
Assert.assertTrue(removedToppings.contains(vegetables));
Assert.assertTrue(removedToppings.size() == 1);
Assert.assertTrue(ingredients.size() == 2);
Assert.assertTrue(ingredients.contains(sauces));
Assert.assertTrue(ingredients.contains(cheeses));
}
}

View File

@ -1,5 +1,8 @@
package org.baeldung.java.io;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
@ -187,10 +190,24 @@ public class JavaReaderToXUnitTest {
targetStream.close();
}
@Test
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException {
String initialString = "With Commons IO";
final Reader initialReader = new StringReader(initialString);
final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader));
final String finalString = IOUtils.toString(targetStream);
assertThat(finalString, equalTo(initialString));
initialReader.close();
targetStream.close();
}
// tests - Reader to InputStream with encoding
@Test
public void givenUsingPlainJava_whenConvertingReaderIntoInputStreamWithCharset_thenCorrect() throws IOException {
public void givenUsingPlainJava_whenConvertingReaderIntoInputStreamWithCharset() throws IOException {
final Reader initialReader = new StringReader("With Java");
final char[] charBuffer = new char[8 * 1024];
@ -225,4 +242,17 @@ public class JavaReaderToXUnitTest {
targetStream.close();
}
@Test
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding_thenCorrect() throws IOException {
String initialString = "With Commons IO";
final Reader initialReader = new StringReader(initialString);
final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8);
String finalString = IOUtils.toString(targetStream, Charsets.UTF_8);
assertThat(finalString, equalTo(initialString));
initialReader.close();
targetStream.close();
}
}

Binary file not shown.

View File

@ -0,0 +1 @@
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<beansProjectDescription>
<version>1</version>
<pluginVersion><![CDATA[3.7.3.201602250914-RELEASE]]></pluginVersion>
<configSuffixes>
<configSuffix><![CDATA[xml]]></configSuffix>
</configSuffixes>
<enableImports><![CDATA[false]]></enableImports>
<configs>
</configs>
<autoconfigs>
</autoconfigs>
<configSets>
</configSets>
</beansProjectDescription>

233
couchbase-sdk-async/mvnw vendored Executable file
View File

@ -0,0 +1,233 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
#
# Look for the Apple JDKs first to preserve the existing behaviour, and then look
# for the new JDKs provided by Oracle.
#
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
#
# Oracle JDKs
#
export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
#
# Apple JDKs
#
export JAVA_HOME=`/usr/libexec/java_home`
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Migwn, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
fi
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
local basedir=$(pwd)
local wdir=$(pwd)
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
wdir=$(cd "$wdir/.."; pwd)
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} "$@"

145
couchbase-sdk-async/mvnw.cmd vendored Normal file
View File

@ -0,0 +1,145 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
set MAVEN_CMD_LINE_ARGS=%*
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar""
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS%
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

102
couchbase-sdk-async/pom.xml Normal file
View File

@ -0,0 +1,102 @@
<?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>couchbase-sdk-async</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>couchbase-sdk-async</name>
<description>Couchbase SDK Asynchronous Operations</description>
<dependencies>
<!-- Couchbase SDK -->
<dependency>
<groupId>com.couchbase.client</groupId>
<artifactId>java-client</artifactId>
<version>${couchbase.client.version}</version>
</dependency>
<!-- Spring Context for Dependency Injection -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- Test-Scoped Dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<java.version>1.7</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<couchbase.client.version>2.2.6</couchbase.client.version>
<spring-framework.version>4.2.4.RELEASE</spring-framework.version>
<logback.version>1.1.3</logback.version>
<org.slf4j.version>1.7.12</org.slf4j.version>
<junit.version>4.11</junit.version>
<commons-lang3.version>3.4</commons-lang3.version>
</properties>
</project>

View File

@ -0,0 +1,89 @@
package com.baeldung.couchbase.person;
import com.baeldung.couchbase.service.CouchbaseEntity;
public class Person implements CouchbaseEntity {
private String id;
private String type;
private String name;
private String homeTown;
Person() {}
public Person(Builder b) {
this.id = b.id;
this.type = b.type;
this.name = b.name;
this.homeTown = b.homeTown;
}
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHomeTown() {
return homeTown;
}
public void setHomeTown(String homeTown) {
this.homeTown = homeTown;
}
public static class Builder {
private String id;
private String type;
private String name;
private String homeTown;
public static Builder newInstance() {
return new Builder();
}
public Person build() {
return new Person(this);
}
public Builder id(String id) {
this.id = id;
return this;
}
public Builder type(String type) {
this.type = type;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder homeTown(String homeTown) {
this.homeTown = homeTown;
return this;
}
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.couchbase.person;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.baeldung.couchbase.service.AbstractCrudService;
import com.baeldung.couchbase.service.BucketService;
@Service
public class PersonCrudService extends AbstractCrudService<Person> {
@Autowired
public PersonCrudService(
@Qualifier("TutorialBucketService") BucketService bucketService,
PersonDocumentConverter converter) {
super(bucketService, converter);
}
@PostConstruct
private void init() {
loadBucket();
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.couchbase.person;
import org.springframework.stereotype.Service;
import com.baeldung.couchbase.service.JsonDocumentConverter;
import com.couchbase.client.java.document.JsonDocument;
import com.couchbase.client.java.document.json.JsonObject;
@Service
public class PersonDocumentConverter implements JsonDocumentConverter<Person> {
@Override
public JsonDocument toDocument(Person p) {
JsonObject content = JsonObject.empty()
.put("type", "Person")
.put("name", p.getName())
.put("homeTown", p.getHomeTown());
return JsonDocument.create(p.getId(), content);
}
@Override
public Person fromDocument(JsonDocument doc) {
JsonObject content = doc.content();
Person p = new Person();
p.setId(doc.id());
p.setType("Person");
p.setName(content.getString("name"));
p.setHomeTown(content.getString("homeTown"));
return p;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.couchbase.person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.couchbase.client.core.CouchbaseException;
@Service
public class RegistrationService {
@Autowired
private PersonCrudService crud;
public void registerNewPerson(String name, String homeTown) {
Person person = new Person();
person.setName(name);
person.setHomeTown(homeTown);
crud.create(person);
}
public Person findRegistrant(String id) {
try{
return crud.read(id);
}
catch(CouchbaseException e) {
return crud.readFromReplica(id);
}
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.couchbase.service;
import com.couchbase.client.java.Bucket;
public abstract class AbstractBucketService implements BucketService {
private ClusterService clusterService;
private Bucket bucket;
protected void openBucket() {
bucket = clusterService.openBucket(getBucketName(), getBucketPassword());
}
protected abstract String getBucketName();
protected abstract String getBucketPassword();
public AbstractBucketService(ClusterService clusterService) {
this.clusterService = clusterService;
}
@Override
public Bucket getBucket() {
return bucket;
}
}

View File

@ -0,0 +1,174 @@
package com.baeldung.couchbase.service;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.couchbase.client.core.BackpressureException;
import com.couchbase.client.core.time.Delay;
import com.couchbase.client.java.AsyncBucket;
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.ReplicaMode;
import com.couchbase.client.java.document.JsonDocument;
import com.couchbase.client.java.util.retry.RetryBuilder;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;
public abstract class AbstractCrudService<T extends CouchbaseEntity> implements CrudService<T> {
private static final Logger logger = LoggerFactory.getLogger(AbstractCrudService.class);
private BucketService bucketService;
private Bucket bucket;
private JsonDocumentConverter<T> converter;
public AbstractCrudService(BucketService bucketService, JsonDocumentConverter<T> converter) {
this.bucketService = bucketService;
this.converter = converter;
}
protected void loadBucket() {
bucket = bucketService.getBucket();
}
@Override
public void create(T t) {
if(t.getId() == null) {
t.setId(UUID.randomUUID().toString());
}
JsonDocument doc = converter.toDocument(t);
bucket.insert(doc);
}
@Override
public T read(String id) {
JsonDocument doc = bucket.get(id);
return (doc == null ? null : converter.fromDocument(doc));
}
@Override
public T readFromReplica(String id) {
List<JsonDocument> docs = bucket.getFromReplica(id, ReplicaMode.FIRST);
return (docs.isEmpty() ? null : converter.fromDocument(docs.get(0)));
}
@Override
public void update(T t) {
JsonDocument doc = converter.toDocument(t);
bucket.upsert(doc);
}
@Override
public void delete(String id) {
bucket.remove(id);
}
@Override
public List<T> readBulk(Iterable<String> ids) {
final AsyncBucket asyncBucket = bucket.async();
Observable<JsonDocument> asyncOperation = Observable
.from(ids)
.flatMap(new Func1<String, Observable<JsonDocument>>() {
public Observable<JsonDocument> call(String key) {
return asyncBucket.get(key);
}
});
final List<T> items = new ArrayList<T>();
try {
asyncOperation.toBlocking()
.forEach(new Action1<JsonDocument>() {
public void call(JsonDocument doc) {
T item = converter.fromDocument(doc);
items.add(item);
}
});
} catch (Exception e) {
logger.error("Error during bulk get", e);
}
return items;
}
@Override
public void createBulk(Iterable<T> items) {
final AsyncBucket asyncBucket = bucket.async();
Observable
.from(items)
.flatMap(new Func1<T, Observable<JsonDocument>>() {
@SuppressWarnings("unchecked")
@Override
public Observable<JsonDocument> call(final T t) {
if(t.getId() == null) {
t.setId(UUID.randomUUID().toString());
}
JsonDocument doc = converter.toDocument(t);
return asyncBucket.insert(doc)
.retryWhen(RetryBuilder
.anyOf(BackpressureException.class)
.delay(Delay.exponential(TimeUnit.MILLISECONDS, 100))
.max(10)
.build());
}
})
.last()
.toBlocking()
.single();
}
@Override
public void updateBulk(Iterable<T> items) {
final AsyncBucket asyncBucket = bucket.async();
Observable
.from(items)
.flatMap(new Func1<T, Observable<JsonDocument>>() {
@SuppressWarnings("unchecked")
@Override
public Observable<JsonDocument> call(final T t) {
JsonDocument doc = converter.toDocument(t);
return asyncBucket.upsert(doc)
.retryWhen(RetryBuilder
.anyOf(BackpressureException.class)
.delay(Delay.exponential(TimeUnit.MILLISECONDS, 100))
.max(10)
.build());
}
})
.last()
.toBlocking()
.single();
}
@Override
public void deleteBulk(Iterable<String> ids) {
final AsyncBucket asyncBucket = bucket.async();
Observable
.from(ids)
.flatMap(new Func1<String, Observable<JsonDocument>>() {
@SuppressWarnings("unchecked")
@Override
public Observable<JsonDocument> call(String key) {
return asyncBucket.remove(key)
.retryWhen(RetryBuilder
.anyOf(BackpressureException.class)
.delay(Delay.exponential(TimeUnit.MILLISECONDS, 100))
.max(10)
.build());
}
})
.last()
.toBlocking()
.single();
}
@Override
public boolean exists(String id) {
return bucket.exists(id);
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.couchbase.service;
import com.couchbase.client.java.Bucket;
public interface BucketService {
Bucket getBucket();
}

View File

@ -0,0 +1,8 @@
package com.baeldung.couchbase.service;
import com.couchbase.client.java.Bucket;
public interface ClusterService {
Bucket openBucket(String name, String password);
}

View File

@ -0,0 +1,36 @@
package com.baeldung.couchbase.service;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Service;
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.CouchbaseCluster;
import com.couchbase.client.java.env.CouchbaseEnvironment;
import com.couchbase.client.java.env.DefaultCouchbaseEnvironment;
@Service
public class ClusterServiceImpl implements ClusterService {
private Cluster cluster;
private Map<String, Bucket> buckets = new ConcurrentHashMap<>();
@PostConstruct
private void init() {
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.create();
cluster = CouchbaseCluster.create(env, "localhost");
}
@Override
synchronized public Bucket openBucket(String name, String password) {
if(!buckets.containsKey(name)) {
Bucket bucket = cluster.openBucket(name, password);
buckets.put(name, bucket);
}
return buckets.get(name);
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.couchbase.service;
public interface CouchbaseEntity {
String getId();
void setId(String id);
}

View File

@ -0,0 +1,26 @@
package com.baeldung.couchbase.service;
import java.util.List;
public interface CrudService<T> {
void create(T t);
T read(String id);
T readFromReplica(String id);
void update(T t);
void delete(String id);
List<T> readBulk(Iterable<String> ids);
void createBulk(Iterable<T> items);
void updateBulk(Iterable<T> items);
void deleteBulk(Iterable<String> ids);
boolean exists(String id);
}

View File

@ -0,0 +1,10 @@
package com.baeldung.couchbase.service;
import com.couchbase.client.java.document.JsonDocument;
public interface JsonDocumentConverter<T> {
JsonDocument toDocument(T t);
T fromDocument(JsonDocument doc);
}

View File

@ -0,0 +1,32 @@
package com.baeldung.couchbase.service;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
@Qualifier("TutorialBucketService")
public class TutorialBucketService extends AbstractBucketService {
@PostConstruct
void init() {
openBucket();
}
@Autowired
public TutorialBucketService(ClusterService clusterService) {
super(clusterService);
}
@Override
protected String getBucketName() {
return "baeldung-tutorial";
}
@Override
protected String getBucketPassword() {
return "";
}
}

View File

@ -0,0 +1,17 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="com.baeldung" level="DEBUG" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
package com.baeldung.couchbase;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { IntegrationTestConfig.class })
@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class })
public abstract class IntegrationTest {
}

View File

@ -0,0 +1,9 @@
package com.baeldung.couchbase;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages={"com.baeldung.couchbase"})
public class IntegrationTestConfig {
}

View File

@ -0,0 +1,220 @@
package com.baeldung.couchbase.person;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.annotation.PostConstruct;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.baeldung.couchbase.IntegrationTest;
import com.baeldung.couchbase.service.BucketService;
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.document.JsonDocument;
public class PersonCrudServiceTest extends IntegrationTest {
@Autowired
private PersonCrudService personService;
@Autowired
@Qualifier("TutorialBucketService")
private BucketService bucketService;
@Autowired
private PersonDocumentConverter converter;
private Bucket bucket;
@PostConstruct
private void init() {
bucket = bucketService.getBucket();
}
@Test
public final void givenRandomPerson_whenCreate_thenPersonPersisted() {
//create person
Person person = randomPerson();
personService.create(person);
//check results
assertNotNull(person.getId());
assertNotNull(bucket.get(person.getId()));
//cleanup
bucket.remove(person.getId());
}
@Test
public final void givenId_whenRead_thenReturnsPerson() {
//create and insert person document
String id = insertRandomPersonDocument().id();
//read person and check results
assertNotNull(personService.read(id));
//cleanup
bucket.remove(id);
}
@Test
public final void givenNewHometown_whenUpdate_thenNewHometownPersisted() {
//create and insert person document
JsonDocument doc = insertRandomPersonDocument();
//update person
Person expected = converter.fromDocument(doc);
String updatedHomeTown = RandomStringUtils.randomAlphabetic(12);
expected.setHomeTown(updatedHomeTown);
personService.update(expected);
//check results
JsonDocument actual = bucket.get(expected.getId());
assertNotNull(actual);
assertNotNull(actual.content());
assertEquals(expected.getHomeTown(), actual.content().getString("homeTown"));
//cleanup
bucket.remove(expected.getId());
}
@Test
public final void givenRandomPerson_whenDelete_thenPersonNotInBucket() {
//create and insert person document
String id = insertRandomPersonDocument().id();
//delete person and check results
personService.delete(id);
assertNull(bucket.get(id));
}
@Test
public final void givenIds_whenReadBulk_thenReturnsOnlyPersonsWithMatchingIds() {
List<String> ids = new ArrayList<>();
//add some person documents
for(int i=0; i<5; i++) {
ids.add(insertRandomPersonDocument().id());
}
//perform bulk read
List<Person> persons = personService.readBulk(ids);
//check results
for(Person person : persons) {
assertTrue(ids.contains(person.getId()));
}
//cleanup
for(String id : ids) {
bucket.remove(id);
}
}
@Test
public final void givenPersons_whenInsertBulk_thenPersonsAreInserted() {
//create some persons
List<Person> persons = new ArrayList<>();
for(int i=0; i<5; i++) {
persons.add(randomPerson());
}
//perform bulk insert
personService.createBulk(persons);
//check results
for(Person person : persons) {
assertNotNull(bucket.get(person.getId()));
}
//cleanup
for(Person person : persons) {
bucket.remove(person.getId());
}
}
@Test
public final void givenPersons_whenUpdateBulk_thenPersonsAreUpdated() {
List<String> ids = new ArrayList<>();
//add some person documents
for(int i=0; i<5; i++) {
ids.add(insertRandomPersonDocument().id());
}
//load persons from Couchbase
List<Person> persons = new ArrayList<>();
for(String id : ids) {
persons.add(converter.fromDocument(bucket.get(id)));
}
//modify persons
for(Person person : persons) {
person.setHomeTown(RandomStringUtils.randomAlphabetic(10));
}
//perform bulk update
personService.updateBulk(persons);
//check results
for(Person person : persons) {
JsonDocument doc = bucket.get(person.getId());
assertEquals(person.getName(), doc.content().getString("name"));
assertEquals(person.getHomeTown(), doc.content().getString("homeTown"));
}
//cleanup
for(String id : ids) {
bucket.remove(id);
}
}
@Test
public void givenIds_whenDeleteBulk_thenPersonsAreDeleted() {
List<String> ids = new ArrayList<>();
//add some person documents
for(int i=0; i<5; i++) {
ids.add(insertRandomPersonDocument().id());
}
//perform bulk delete
personService.deleteBulk(ids);
//check results
for(String id : ids) {
assertNull(bucket.get(id));
}
}
private JsonDocument insertRandomPersonDocument() {
Person expected = randomPersonWithId();
JsonDocument doc = converter.toDocument(expected);
return bucket.insert(doc);
}
private Person randomPerson() {
return Person.Builder.newInstance()
.name(RandomStringUtils.randomAlphabetic(10))
.homeTown(RandomStringUtils.randomAlphabetic(10))
.build();
}
private Person randomPersonWithId() {
return Person.Builder.newInstance()
.id(UUID.randomUUID().toString())
.name(RandomStringUtils.randomAlphabetic(10))
.homeTown(RandomStringUtils.randomAlphabetic(10))
.build();
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.couchbase.service;
import static org.junit.Assert.*;
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.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import com.baeldung.couchbase.IntegrationTest;
import com.baeldung.couchbase.IntegrationTestConfig;
import com.couchbase.client.java.Bucket;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { IntegrationTestConfig.class })
@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class })
public class ClusterServiceTest extends IntegrationTest {
@Autowired
private ClusterService couchbaseService;
private Bucket defaultBucket;
@Test
public void whenOpenBucket_thenBucketIsNotNull() throws Exception {
defaultBucket = couchbaseService.openBucket("default", "");
assertNotNull(defaultBucket);
assertFalse(defaultBucket.isClosed());
defaultBucket.close();
}
}

View File

@ -1,59 +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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>dozer-tutorial</artifactId>
<version>1.0</version>
<name>Dozer</name>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>7</source>
<target>7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.1</version>
</dependency>
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<version>5.5.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.3</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,38 +0,0 @@
package com.baeldung.dozer;
public class Dest2 {
private int id;
private int points;
public Dest2() {
}
public Dest2(int id, int points) {
super();
this.id = id;
this.points = points;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
@Override
public String toString() {
return "Dest2 [id=" + id + ", points=" + points + "]";
}
}

View File

@ -1,48 +0,0 @@
package com.baeldung.dozer;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.dozer.CustomConverter;
import org.dozer.MappingException;
public class MyCustomConvertor implements CustomConverter {
@Override
public Object convert(Object dest, Object source, Class<?> arg2,
Class<?> arg3) {
if (source == null) {
return null;
}
if (source instanceof Personne3) {
Personne3 person = (Personne3) source;
Date date = new Date(person.getDtob());
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
String isoDate = format.format(date);
return new Person3(person.getName(), isoDate);
} else if (source instanceof Person3) {
Person3 person = (Person3) source;
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = null;
try {
date = format.parse(person.getDtob());
} catch (ParseException e) {
throw new MappingException("Converter MyCustomConvertor "
+ "used incorrectly:" + e.getMessage());
}
long timestamp = date.getTime();
return new Personne3(person.getName(), timestamp);
} else {
throw new MappingException("Converter MyCustomConvertor "
+ "used incorrectly. Arguments passed in were:" + dest
+ " and " + source);
}
}
}

View File

@ -1,43 +0,0 @@
package com.baeldung.dozer;
public class Person2 {
private String name;
private String nickname;
private int age;
public Person2() {
}
public Person2(String name, String nickname, int age) {
super();
this.name = name;
this.nickname = nickname;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

View File

@ -1,47 +0,0 @@
package com.baeldung.dozer;
import org.dozer.Mapping;
public class Personne2 {
private String nom;
private String surnom;
private int age;
public Personne2() {
}
public Personne2(String nom, String surnom, int age) {
super();
this.nom = nom;
this.surnom = surnom;
this.age = age;
}
@Mapping("name")
public String getNom() {
return nom;
}
@Mapping("nickname")
public String getSurnom() {
return surnom;
}
public void setNom(String nom) {
this.nom = nom;
}
public void setSurnom(String surnom) {
this.surnom = surnom;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

View File

@ -1,38 +0,0 @@
package com.baeldung.dozer;
public class Source2 {
private String id;
private double points;
public Source2() {
}
public Source2(String id, double points) {
super();
this.id = id;
this.points = points;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public double getPoints() {
return points;
}
public void setPoints(double points) {
this.points = points;
}
@Override
public String toString() {
return "Source2 [id=" + id + ", points=" + points + "]";
}
}

View File

@ -1,200 +0,0 @@
package com.baeldung.dozer;
import static org.junit.Assert.assertEquals;
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.Test;
public class DozerTest {
private DozerBeanMapper mapper = new DozerBeanMapper();
@Before
public void before() throws Exception {
mapper = new DozerBeanMapper();
}
private BeanMappingBuilder builder = new BeanMappingBuilder() {
@Override
protected void configure() {
mapping(Person.class, Personne.class).fields("name", "nom").fields(
"nickname", "surnom");
}
};
private BeanMappingBuilder builderMinusAge = new BeanMappingBuilder() {
@Override
protected void configure() {
mapping(Person.class, Personne.class).fields("name", "nom")
.fields("nickname", "surnom").exclude("age");
}
};
@Test
public void givenApiMapper_whenMaps_thenCorrect() {
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());
assertEquals(englishAppPerson.getAge(), frenchAppPerson.getAge());
}
@Test
public void givenApiMapper_whenMapsOnlySpecifiedFields_thenCorrect() {
Person englishAppPerson = new Person("Sylvester Stallone", "Rambo", 70);
mapper.addMapping(builderMinusAge);
Personne frenchAppPerson = mapper.map(englishAppPerson, Personne.class);
assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName());
assertEquals(frenchAppPerson.getSurnom(),
englishAppPerson.getNickname());
assertEquals(frenchAppPerson.getAge(), 0);
}
@Test
public void givenApiMapper_whenMapsBidirectionally_thenCorrect() {
Person englishAppPerson = new Person("Sylvester Stallone", "Rambo", 70);
mapper.addMapping(builder);
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 givenSourceObjectAndDestClass_whenMapsSameNameFieldsCorrectly_thenCorrect() {
Source source = new Source("Baeldung", 10);
Dest dest = mapper.map(source, Dest.class);
assertEquals(dest.getName(), "Baeldung");
assertEquals(dest.getAge(), 10);
}
@Test
public void givenSourceObjectAndDestObject_whenMapsSameNameFieldsCorrectly_thenCorrect() {
Source source = new Source("Baeldung", 10);
Dest dest = new Dest();
mapper.map(source, dest);
assertEquals(dest.getName(), "Baeldung");
assertEquals(dest.getAge(), 10);
}
@Test
public void givenSourceAndDestWithDifferentFieldTypes_whenMapsAndAutoConverts_thenCorrect() {
Source2 source = new Source2("320", 15.2);
Dest2 dest = mapper.map(source, Dest2.class);
assertEquals(dest.getId(), 320);
assertEquals(dest.getPoints(), 15);
}
@Test
public void givenSrcAndDestWithDifferentFieldNamesWithCustomMapper_whenMaps_thenCorrect() {
List<String> mappingFiles = new ArrayList<>();
mappingFiles.add("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());
assertEquals(englishAppPerson.getAge(), frenchAppPerson.getAge());
}
@Test
public void givenSrcAndDestWithDifferentFieldNamesWithCustomMapper_whenMapsBidirectionally_thenCorrect() {
List<String> mappingFiles = new ArrayList<>();
mappingFiles.add("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());
// }
@Test
public void givenSrcAndDest_whenMapsOnlySpecifiedFields_thenCorrect() {
List<String> mappingFiles = new ArrayList<>();
mappingFiles.add("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());
assertEquals(frenchAppPerson.getAge(), 0);
}
@Test
public void givenAnnotatedSrcFields_whenMapsToRightDestField_thenCorrect() {
Person2 englishAppPerson = new Person2("Jean-Claude Van Damme", "JCVD",
55);
Personne2 frenchAppPerson = mapper.map(englishAppPerson,
Personne2.class);
assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName());
assertEquals(frenchAppPerson.getSurnom(),
englishAppPerson.getNickname());
assertEquals(frenchAppPerson.getAge(), englishAppPerson.getAge());
}
@Test
public void givenAnnotatedSrcFields_whenMapsToRightDestFieldBidirectionally_thenCorrect() {
Personne2 frenchAppPerson = new Personne2("Jason Statham",
"transporter", 49);
Person2 englishAppPerson = mapper.map(frenchAppPerson, Person2.class);
assertEquals(englishAppPerson.getName(), frenchAppPerson.getNom());
assertEquals(englishAppPerson.getNickname(),
frenchAppPerson.getSurnom());
assertEquals(englishAppPerson.getAge(), frenchAppPerson.getAge());
}
@Test
public void givenSrcAndDestWithDifferentFieldTypes_whenAbleToCustomConvert_thenCorrect() {
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());
}
@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" }));
Person3 person0 = mapper.map(person, Person3.class);
assertEquals(dateTime, person0.getDtob());
}
}

58
dozer/pom.xml Normal file
View File

@ -0,0 +1,58 @@
<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>dozer</artifactId>
<version>1.0</version>
<name>dozer</name>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>7</source>
<target>7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<version>5.5.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.3</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,33 @@
package com.baeldung.dozer;
public class Dest {
private String name;
private int age;
public Dest() {
}
public Dest(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.dozer;
public class Dest2 {
private int id;
private int points;
public Dest2() {
}
public Dest2(int id, int points) {
super();
this.id = id;
this.points = points;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
@Override
public String toString() {
return "Dest2 [id=" + id + ", points=" + points + "]";
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.dozer;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.dozer.CustomConverter;
import org.dozer.MappingException;
public class MyCustomConvertor implements CustomConverter {
@Override
public Object convert(Object dest, Object source, Class<?> arg2, Class<?> arg3) {
if (source == null) {
return null;
}
if (source instanceof Personne3) {
Personne3 person = (Personne3) source;
Date date = new Date(person.getDtob());
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
String isoDate = format.format(date);
return new Person3(person.getName(), isoDate);
} else if (source instanceof Person3) {
Person3 person = (Person3) source;
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = null;
try {
date = format.parse(person.getDtob());
} catch (ParseException e) {
throw new MappingException("Converter MyCustomConvertor " + "used incorrectly:" + e.getMessage());
}
long timestamp = date.getTime();
return new Personne3(person.getName(), timestamp);
} else {
throw new MappingException("Converter MyCustomConvertor " + "used incorrectly. Arguments passed in were:" + dest + " and " + source);
}
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.dozer;
public class Person {
private String name;
private String nickname;
private int age;
public Person() {
}
public Person(String name, String nickname, int age) {
super();
this.name = name;
this.nickname = nickname;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.dozer;
public class Person2 {
private String name;
private String nickname;
private int age;
public Person2() {
}
public Person2(String name, String nickname, int age) {
super();
this.name = name;
this.nickname = nickname;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.dozer;
public class Person3 {
private String name;
private String dtob;
public Person3() {
}
public Person3(String name, String dtob) {
super();
this.name = name;
this.dtob = dtob;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDtob() {
return dtob;
}
public void setDtob(String dtob) {
this.dtob = dtob;
}
@Override
public String toString() {
return "Person3 [name=" + name + ", dtob=" + dtob + "]";
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.dozer;
public class Personne {
private String nom;
private String surnom;
private int age;
public Personne() {
}
public Personne(String nom, String surnom, int age) {
super();
this.nom = nom;
this.surnom = surnom;
this.age = age;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getSurnom() {
return surnom;
}
public void setSurnom(String surnom) {
this.surnom = surnom;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.dozer;
import org.dozer.Mapping;
public class Personne2 {
private String nom;
private String surnom;
private int age;
public Personne2() {
}
public Personne2(String nom, String surnom, int age) {
super();
this.nom = nom;
this.surnom = surnom;
this.age = age;
}
@Mapping("name")
public String getNom() {
return nom;
}
@Mapping("nickname")
public String getSurnom() {
return surnom;
}
public void setNom(String nom) {
this.nom = nom;
}
public void setSurnom(String surnom) {
this.surnom = surnom;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.dozer;
public class Personne3 {
private String name;
private long dtob;
public Personne3() {
}
public Personne3(String name, long dtob) {
super();
this.name = name;
this.dtob = dtob;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getDtob() {
return dtob;
}
public void setDtob(long dtob) {
this.dtob = dtob;
}
@Override
public String toString() {
return "Personne3 [name=" + name + ", dtob=" + dtob + "]";
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.dozer;
public class Source {
private String name;
private int age;
public Source() {
}
public Source(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.dozer;
public class Source2 {
private String id;
private double points;
public Source2() {
}
public Source2(String id, double points) {
super();
this.id = id;
this.points = points;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public double getPoints() {
return points;
}
public void setPoints(double points) {
this.points = points;
}
@Override
public String toString() {
return "Source2 [id=" + id + ", points=" + points + "]";
}
}

View File

@ -0,0 +1,199 @@
package com.baeldung.dozer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
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;
DozerBeanMapper mapper;
@Before
public void before() throws Exception {
mapper = new DozerBeanMapper();
}
BeanMappingBuilder builder = new BeanMappingBuilder() {
@Override
protected void configure() {
mapping(Person.class, Personne.class).fields("name", "nom").fields("nickname", "surnom");
}
};
BeanMappingBuilder builderMinusAge = new BeanMappingBuilder() {
@Override
protected void configure() {
mapping(Person.class, Personne.class).fields("name", "nom").fields("nickname", "surnom").exclude("age");
}
};
@Test
public void givenApiMapper_whenMaps_thenCorrect() {
mapper.addMapping(builder);
Personne frenchAppPerson = new Personne("Sylvester Stallone", "Rambo", 70);
Person englishAppPerson = mapper.map(frenchAppPerson, Person.class);
assertEquals(englishAppPerson.getName(), frenchAppPerson.getNom());
assertEquals(englishAppPerson.getNickname(), frenchAppPerson.getSurnom());
assertEquals(englishAppPerson.getAge(), frenchAppPerson.getAge());
}
@Test
public void givenApiMapper_whenMapsOnlySpecifiedFields_thenCorrect() {
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());
assertEquals(frenchAppPerson.getAge(), 0);
}
@Test
public void givenApiMapper_whenMapsBidirectionally_thenCorrect() {
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());
assertEquals(frenchAppPerson.getAge(), englishAppPerson.getAge());
}
@Test
public void givenSourceObjectAndDestClass_whenMapsSameNameFieldsCorrectly_thenCorrect() {
Source source = new Source("Baeldung", 10);
Dest dest = mapper.map(source, Dest.class);
assertEquals(dest.getName(), "Baeldung");
assertEquals(dest.getAge(), 10);
}
@Test
public void givenSourceObjectAndDestObject_whenMapsSameNameFieldsCorrectly_thenCorrect() {
Source source = new Source("Baeldung", 10);
Dest dest = new Dest();
mapper.map(source, dest);
assertEquals(dest.getName(), "Baeldung");
assertEquals(dest.getAge(), 10);
}
@Test
public void givenSourceAndDestWithDifferentFieldTypes_whenMapsAndAutoConverts_thenCorrect() {
Source2 source = new Source2("320", 15.2);
Dest2 dest = mapper.map(source, Dest2.class);
assertEquals(dest.getId(), 320);
assertEquals(dest.getPoints(), 15);
}
@Test
public void givenSrcAndDestWithDifferentFieldNamesWithCustomMapper_whenMaps_thenCorrect() {
configureMapper("dozer_mapping.xml");
Personne frenchAppPerson = new Personne("Sylvester Stallone", "Rambo", 70);
Person englishAppPerson = mapper.map(frenchAppPerson, Person.class);
assertEquals(englishAppPerson.getName(), frenchAppPerson.getNom());
assertEquals(englishAppPerson.getNickname(), frenchAppPerson.getSurnom());
assertEquals(englishAppPerson.getAge(), frenchAppPerson.getAge());
}
@Test
public void givenSrcAndDestWithDifferentFieldNamesWithCustomMapper_whenMapsBidirectionally_thenCorrect() {
configureMapper("dozer_mapping.xml");
Person englishAppPerson = new Person("Dwayne Johnson", "The Rock", 44);
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() {
configureMapper("dozer_mapping2.xml");
Person englishAppPerson = new Person("Shawn Corey Carter", "Jay Z", 46);
Personne frenchAppPerson = mapper.map(englishAppPerson, Personne.class);
assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName());
assertEquals(frenchAppPerson.getSurnom(), englishAppPerson.getNickname());
assertEquals(frenchAppPerson.getAge(), 0);
}
@Test
public void givenAnnotatedSrcFields_whenMapsToRightDestField_thenCorrect() {
Person2 englishAppPerson = new Person2("Jean-Claude Van Damme", "JCVD", 55);
Personne2 frenchAppPerson = mapper.map(englishAppPerson, Personne2.class);
assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName());
assertEquals(frenchAppPerson.getSurnom(), englishAppPerson.getNickname());
assertEquals(frenchAppPerson.getAge(), englishAppPerson.getAge());
}
@Test
public void givenAnnotatedSrcFields_whenMapsToRightDestFieldBidirectionally_thenCorrect() {
Personne2 frenchAppPerson = new Personne2("Jason Statham", "transporter", 49);
Person2 englishAppPerson = mapper.map(frenchAppPerson, Person2.class);
assertEquals(englishAppPerson.getName(), frenchAppPerson.getNom());
assertEquals(englishAppPerson.getNickname(), frenchAppPerson.getSurnom());
assertEquals(englishAppPerson.getAge(), frenchAppPerson.getAge());
}
@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);
Personne3 person0 = mapper.map(person, Personne3.class);
long timestampToTest = person0.getDtob();
assertTrue(timestampToTest == timestamp || timestampToTest >= timestamp - GMT_DIFFERENCE || timestampToTest <= timestamp + GMT_DIFFERENCE);
}
@Test
public void givenSrcAndDestWithDifferentFieldTypes_whenAbleToCustomConvertBidirectionally_thenCorrect() {
long timestamp = new Long("1182882159000");
Personne3 person = new Personne3("Rich", timestamp);
configureMapper("dozer_custom_convertor.xml");
Person3 person0 = mapper.map(person, Person3.class);
String timestampTest = person0.getDtob();
assertTrue(timestampTest.charAt(10) == 'T' && timestampTest.charAt(19) == 'Z');
}
public void configureMapper(String... mappingFileUrls) {
mapper.setMappingFiles(Arrays.asList(mappingFileUrls));
}
}

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType">
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="false"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_DISABLED_BUILDER" value="org.eclipse.wst.jsdt.core.javascriptValidator"/>
<mapAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
</launchConfiguration>

View File

@ -0,0 +1,49 @@
package org.baeldung.gson.entities;
import java.util.Date;
import java.util.List;
public class ActorGson {
private String imdbId;
private Date dateOfBirth;
private List<String> filmography;
public ActorGson(String imdbId, Date dateOfBirth, List<String> filmography) {
super();
this.imdbId = imdbId;
this.dateOfBirth = dateOfBirth;
this.filmography = filmography;
}
@Override
public String toString() {
return "ActorGson [imdbId=" + imdbId + ", dateOfBirth=" + dateOfBirth + ", filmography=" + filmography + "]";
}
public String getImdbId() {
return imdbId;
}
public void setImdbId(String imdbId) {
this.imdbId = imdbId;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public List<String> getFilmography() {
return filmography;
}
public void setFilmography(List<String> filmography) {
this.filmography = filmography;
}
}

View File

@ -0,0 +1,48 @@
package org.baeldung.gson.entities;
import java.util.List;
public class Movie {
private String imdbId;
private String director;
private List<ActorGson> actors;
public Movie(String imdbID, String director, List<ActorGson> actors) {
super();
this.imdbId = imdbID;
this.director = director;
this.actors = actors;
}
@Override
public String toString() {
return "Movie [imdbId=" + imdbId + ", director=" + director + ", actors=" + actors + "]";
}
public String getImdbID() {
return imdbId;
}
public void setImdbID(String imdbID) {
this.imdbId = imdbID;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public List<ActorGson> getActors() {
return actors;
}
public void setActors(List<ActorGson> actors) {
this.actors = actors;
}
}

View File

@ -0,0 +1,46 @@
package org.baeldung.gson.entities;
import com.google.gson.annotations.Expose;
import java.util.List;
public class MovieWithNullValue {
@Expose
private String imdbId;
private String director;
@Expose
private List<ActorGson> actors;
public MovieWithNullValue(String imdbID, String director, List<ActorGson> actors) {
super();
this.imdbId = imdbID;
this.director = director;
this.actors = actors;
}
public String getImdbID() {
return imdbId;
}
public void setImdbID(String imdbID) {
this.imdbId = imdbID;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public List<ActorGson> getActors() {
return actors;
}
public void setActors(List<ActorGson> actors) {
this.actors = actors;
}
}

View File

@ -0,0 +1,40 @@
package org.baeldung.gson.serialization;
import com.google.gson.*;
import org.baeldung.gson.entities.ActorGson;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class ActorGsonDeserializer implements JsonDeserializer<ActorGson> {
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
@Override
public ActorGson deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
JsonElement jsonImdbId = jsonObject.get("imdbId");
JsonElement jsonDateOfBirth = jsonObject.get("dateOfBirth");
JsonArray jsonFilmography = jsonObject.getAsJsonArray("filmography");
ArrayList<String> filmList = new ArrayList<String>();
if (jsonFilmography != null) {
for (int i = 0; i < jsonFilmography.size(); i++) {
filmList.add(jsonFilmography.get(i).getAsString());
}
}
ActorGson actorGson = null;
try {
actorGson = new ActorGson(jsonImdbId.getAsString(), sdf.parse(jsonDateOfBirth.getAsString()), filmList);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return actorGson;
}
}

View File

@ -0,0 +1,33 @@
package org.baeldung.gson.serialization;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import org.baeldung.gson.entities.ActorGson;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.stream.Collectors;
public class ActorGsonSerializer implements JsonSerializer<ActorGson> {
private SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
@Override
public JsonElement serialize(ActorGson actor, Type type, JsonSerializationContext jsonSerializationContext) {
JsonObject actorJsonObj = new JsonObject();
actorJsonObj.addProperty("<strong>IMDB Code</strong>", actor.getImdbId());
actorJsonObj.addProperty("<strong>Date Of Birth</strong>", actor.getDateOfBirth() != null ? sdf.format(actor.getDateOfBirth()) : null);
actorJsonObj.addProperty("<strong>N° Film:</strong> ", actor.getFilmography() != null ? actor.getFilmography().size() : null);
actorJsonObj.addProperty("filmography", actor.getFilmography() != null ? convertFilmography(actor.getFilmography()) : null);
return actorJsonObj;
}
private String convertFilmography(List<String> filmography) {
return filmography.stream().collect(Collectors.joining("-"));
}
}

View File

@ -0,0 +1,38 @@
package org.baeldung.gson.deserialization;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.baeldung.gson.entities.ActorGson;
import org.baeldung.gson.entities.Movie;
import org.baeldung.gson.serialization.ActorGsonDeserializer;
import org.junit.Assert;
import org.junit.Test;
import java.text.ParseException;
public class GsonDeserializeTest {
@Test
public void whenSimpleDeserialize_thenCorrect() throws ParseException {
String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":" + "[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":" + "[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}";
Movie outputMovie = new Gson().fromJson(jsonInput, Movie.class);
String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorGson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 04:00:00 PDT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]";
Assert.assertEquals(outputMovie.toString(), expectedOutput);
}
@Test
public void whenCustomDeserialize_thenCorrect() throws ParseException {
String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":" + "[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":" + "[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}";
Gson gson = new GsonBuilder().registerTypeAdapter(ActorGson.class, new ActorGsonDeserializer()).create();
Movie outputMovie = gson.fromJson(jsonInput, Movie.class);
String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorGson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 12:00:00 PDT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]";
Assert.assertEquals(outputMovie.toString(), expectedOutput);
}
}

View File

@ -0,0 +1,48 @@
package org.baeldung.gson.serialization;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser;
import org.baeldung.gson.entities.ActorGson;
import org.baeldung.gson.entities.Movie;
import org.baeldung.gson.entities.MovieWithNullValue;
import org.junit.Assert;
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
public class GsonSerializeTest {
@Test
public void whenSimpleSerialize_thenCorrect() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
ActorGson rudyYoungblood = new ActorGson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers"));
Movie movie = new Movie("tt0472043", "Mel Gibson", Arrays.asList(rudyYoungblood));
String expectedOutput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"Sep 21, 1982 12:00:00 AM\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}";
Assert.assertEquals(new Gson().toJson(movie), expectedOutput);
}
@Test
public void whenCustomSerialize_thenCorrect() throws ParseException {
Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().serializeNulls().disableHtmlEscaping().registerTypeAdapter(ActorGson.class, new ActorGsonSerializer()).create();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
ActorGson rudyYoungblood = new ActorGson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers"));
MovieWithNullValue movieWithNullValue = new MovieWithNullValue(null, "Mel Gibson", Arrays.asList(rudyYoungblood));
String expectedOutput = new GsonBuilder()
.setPrettyPrinting()
.serializeNulls()
.disableHtmlEscaping()
.create()
.toJson(new JsonParser()
.parse("{\"imdbId\":null,\"actors\":[{\"<strong>IMDB Code</strong>\":\"nm2199632\",\"<strong>Date Of Birth</strong>\":\"21-09-1982\",\"<strong>N° Film:</strong> \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}]}"));
Assert.assertEquals(gson.toJson(movieWithNullValue), expectedOutput);
}
}

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType">
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="false"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_DISABLED_BUILDER" value="org.eclipse.wst.jsdt.core.javascriptValidator"/>
<mapAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
</launchConfiguration>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src/main/webapp"/>
<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,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="spring-rest">
<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-rest"/>
<property name="java-output-path" value="/spring-rest/target/classes"/>
</wb-module>
</project-modules>

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<installed facet="java" version="1.8"/>
</faceted-project>

View File

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

View File

@ -1,14 +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.303.v201202090300
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,7 +14,7 @@ public class GuavaMapFromSet<K, V> extends AbstractMap<K, V> {
private class SingleEntry implements Entry<K, V> {
private K key;
public SingleEntry( K key) {
public SingleEntry(K key) {
this.key = key;
}
@ -34,7 +34,7 @@ public class GuavaMapFromSet<K, V> extends AbstractMap<K, V> {
}
@Override
public V setValue( V value) {
public V setValue(V value) {
throw new UnsupportedOperationException();
}
}
@ -67,7 +67,7 @@ public class GuavaMapFromSet<K, V> extends AbstractMap<K, V> {
private Set<K> keys;
public MyEntrySet( Set<K> keys) {
public MyEntrySet(Set<K> keys) {
this.keys = keys;
}
@ -87,7 +87,7 @@ public class GuavaMapFromSet<K, V> extends AbstractMap<K, V> {
private Set<Entry<K, V>> entries;
private Function<? super K, ? extends V> function;
public GuavaMapFromSet( Set<K> keys, Function<? super K, ? extends V> function) {
public GuavaMapFromSet(Set<K> keys, Function<? super K, ? extends V> function) {
this.function = function;
this.cache = new WeakHashMap<K, V>();
this.entries = new MyEntrySet(keys);

View File

@ -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,11 +54,11 @@ 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);
set.add("one");
assertTrue(map.get("one") == 3 && map.size()==4);
assertTrue(map.get("one") == 3 && map.size() == 4);
}
}

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType">
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="false"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_DISABLED_BUILDER" value="org.eclipse.wst.jsdt.core.javascriptValidator"/>
<mapAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
</launchConfiguration>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src/main/webapp"/>
<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,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,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="spring-rest">
<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-rest"/>
<property name="java-output-path" value="/spring-rest/target/classes"/>
</wb-module>
</project-modules>

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<installed facet="java" version="1.8"/>
</faceted-project>

View File

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

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