Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
e05929081a
@ -1,9 +1,10 @@
|
|||||||
package com.baeldung.s3;
|
package com.baeldung.s3;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.FileOutputStream;
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import org.apache.commons.io.FileUtils;
|
||||||
|
|
||||||
import com.amazonaws.auth.AWSCredentials;
|
import com.amazonaws.auth.AWSCredentials;
|
||||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
||||||
import com.amazonaws.auth.BasicAWSCredentials;
|
import com.amazonaws.auth.BasicAWSCredentials;
|
||||||
@ -74,15 +75,7 @@ public class S3Application {
|
|||||||
//downloading an object
|
//downloading an object
|
||||||
S3Object s3object = awsService.getObject(bucketName, "Document/hello.txt");
|
S3Object s3object = awsService.getObject(bucketName, "Document/hello.txt");
|
||||||
S3ObjectInputStream inputStream = s3object.getObjectContent();
|
S3ObjectInputStream inputStream = s3object.getObjectContent();
|
||||||
FileOutputStream fos = new FileOutputStream(new File("/Users/user/Desktop/hello.txt"));
|
FileUtils.copyInputStreamToFile(inputStream, new File("/Users/user/Desktop/hello.txt"));
|
||||||
|
|
||||||
int read = 0;
|
|
||||||
byte[] bytes = new byte[1024];
|
|
||||||
while ((read = inputStream.read(bytes)) != -1) {
|
|
||||||
fos.write(bytes, 0, read);
|
|
||||||
}
|
|
||||||
inputStream.close();
|
|
||||||
fos.close();
|
|
||||||
|
|
||||||
//copying an object
|
//copying an object
|
||||||
awsService.copyObject(
|
awsService.copyObject(
|
||||||
|
@ -13,14 +13,13 @@ import org.springframework.beans.factory.annotation.Value;
|
|||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
import org.springframework.boot.web.servlet.ServletRegistrationBean;
|
import org.springframework.boot.web.servlet.ServletRegistrationBean;
|
||||||
import org.springframework.boot.web.support.SpringBootServletInitializer;
|
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.ComponentScan;
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
@ComponentScan(basePackages="com.baeldung.camel")
|
@ComponentScan(basePackages="com.baeldung.camel")
|
||||||
public class Application extends SpringBootServletInitializer {
|
public class Application{
|
||||||
|
|
||||||
@Value("${server.port}")
|
@Value("${server.port}")
|
||||||
String serverPort;
|
String serverPort;
|
||||||
@ -62,10 +61,12 @@ public class Application extends SpringBootServletInitializer {
|
|||||||
.bindingMode(RestBindingMode.json)
|
.bindingMode(RestBindingMode.json)
|
||||||
.dataFormatProperty("prettyPrint", "true");
|
.dataFormatProperty("prettyPrint", "true");
|
||||||
/**
|
/**
|
||||||
The Rest DSL supports automatic binding json/xml contents to/from POJOs using Camels Data Format.
|
The Rest DSL supports automatic binding json/xml contents to/from
|
||||||
By default the binding mode is off, meaning there is no automatic binding happening for incoming and outgoing messages.
|
POJOs using Camels Data Format.
|
||||||
You may want to use binding if you develop POJOs that maps to your REST services request and response types.
|
By default the binding mode is off, meaning there is no automatic
|
||||||
This allows you, as a developer, to work with the POJOs in Java code.
|
binding happening for incoming and outgoing messages.
|
||||||
|
You may want to use binding if you develop POJOs that maps to
|
||||||
|
your REST services request and response types.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
rest("/api/").description("Teste REST Service")
|
rest("/api/").description("Teste REST Service")
|
||||||
|
39
core-java/hashcode/pom.xml
Normal file
39
core-java/hashcode/pom.xml
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
<?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.hashcode</groupId>
|
||||||
|
<artifactId>hashcode</artifactId>
|
||||||
|
<version>1.0</version>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>4.12</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.slf4j</groupId>
|
||||||
|
<artifactId>slf4j-api</artifactId>
|
||||||
|
<version>1.7.25</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.slf4j</groupId>
|
||||||
|
<artifactId>slf4j-simple</artifactId>
|
||||||
|
<version>1.7.25</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</project>
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.application;
|
||||||
|
|
||||||
|
import com.baeldung.entities.User;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class Application {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Map<User, User> users = new HashMap<>();
|
||||||
|
User user1 = new User(1L, "John", "john@domain.com");
|
||||||
|
User user2 = new User(2L, "Jennifer", "jennifer@domain.com");
|
||||||
|
User user3 = new User(3L, "Mary", "mary@domain.com");
|
||||||
|
|
||||||
|
users.put(user1, user1);
|
||||||
|
users.put(user2, user2);
|
||||||
|
users.put(user3, user3);
|
||||||
|
|
||||||
|
if (users.containsKey(user1)) {
|
||||||
|
System.out.print("User found in the collection");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.baeldung.entities;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class User {
|
||||||
|
|
||||||
|
private final Logger logger = LoggerFactory.getLogger(User.class);
|
||||||
|
private long id;
|
||||||
|
private String name;
|
||||||
|
private String email;
|
||||||
|
|
||||||
|
public User(long id, String name, String email) {
|
||||||
|
this.id = id;
|
||||||
|
this.name = name;
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) return true;
|
||||||
|
if (o == null) return false;
|
||||||
|
if (this.getClass() != o.getClass()) return false;
|
||||||
|
User user = (User) o;
|
||||||
|
return id != user.id && (!name.equals(user.name) && !email.equals(user.email));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
int hash = 7;
|
||||||
|
hash = 31 * hash + (int) id;
|
||||||
|
hash = 31 * hash + (name == null ? 0 : name.hashCode());
|
||||||
|
hash = 31 * hash + (email == null ? 0 : email.hashCode());
|
||||||
|
logger.info("hashCode() method called - Computed hash: " + hash);
|
||||||
|
return hash;
|
||||||
|
}
|
||||||
|
// getters and setters here
|
||||||
|
}
|
@ -0,0 +1,30 @@
|
|||||||
|
package com.baeldung.application;
|
||||||
|
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.PrintStream;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class ApplicationTest {
|
||||||
|
|
||||||
|
private ByteArrayOutputStream outContent;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUpPrintStreamInstance() throws Exception {
|
||||||
|
this.outContent = new ByteArrayOutputStream();
|
||||||
|
System.setOut(new PrintStream(outContent));
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDownByteArrayOutputStream() throws Exception {
|
||||||
|
outContent = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void main_NoInputState_TextPrintedToConsole() throws Exception {
|
||||||
|
Application.main(new String[]{});
|
||||||
|
assertEquals("User found in the collection", outContent.toString());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,34 @@
|
|||||||
|
package com.baeldung.entities;
|
||||||
|
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class UserTest {
|
||||||
|
|
||||||
|
private User user;
|
||||||
|
private User comparisonUser;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUpUserInstances() {
|
||||||
|
this.user = new User(1L, "test", "test@domain.com");
|
||||||
|
this.comparisonUser = this.user;
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDownUserInstances() {
|
||||||
|
user = null;
|
||||||
|
comparisonUser = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void equals_EqualUserInstance_TrueAssertion(){
|
||||||
|
Assert.assertTrue(user.equals(comparisonUser));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void hashCode_UserHash_TrueAssertion() {
|
||||||
|
Assert.assertEquals(1792276941, user.hashCode());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,34 @@
|
|||||||
|
package com.baeldung.concurrent.Scheduledexecutorservice;
|
||||||
|
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
|
import java.util.concurrent.ScheduledFuture;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
public class ScheduledExecutorServiceDemo {
|
||||||
|
|
||||||
|
public void execute() {
|
||||||
|
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
|
||||||
|
|
||||||
|
ScheduledFuture<?> scheduledFuture = executorService.schedule(() -> {
|
||||||
|
// Task
|
||||||
|
}, 1, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
executorService.scheduleAtFixedRate(() -> {
|
||||||
|
// Task
|
||||||
|
}, 1, 10, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
executorService.scheduleWithFixedDelay(() -> {
|
||||||
|
// Task
|
||||||
|
}, 1, 10, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
Future<String> future = executorService.schedule(() -> {
|
||||||
|
// Task
|
||||||
|
return "Hellow world";
|
||||||
|
}, 1, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
executorService.shutdown();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.concurrent.atomic;
|
||||||
|
|
||||||
|
public class SafeCounterWithLock {
|
||||||
|
private volatile int counter;
|
||||||
|
|
||||||
|
public int getValue() {
|
||||||
|
return counter;
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized void increment() {
|
||||||
|
counter++;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
package com.baeldung.concurrent.atomic;
|
||||||
|
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
|
public class SafeCounterWithoutLock {
|
||||||
|
private final AtomicInteger counter = new AtomicInteger(0);
|
||||||
|
|
||||||
|
public int getValue() {
|
||||||
|
return counter.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void increment() {
|
||||||
|
while(true) {
|
||||||
|
int existingValue = getValue();
|
||||||
|
int newValue = existingValue + 1;
|
||||||
|
if(counter.compareAndSet(existingValue, newValue)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.concurrent.atomic;
|
||||||
|
|
||||||
|
public class UnsafeCounter {
|
||||||
|
int counter;
|
||||||
|
|
||||||
|
public int getValue() {
|
||||||
|
return counter;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void increment() {
|
||||||
|
counter++;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.concurrent.cyclicbarrier;
|
||||||
|
|
||||||
|
import java.util.concurrent.CyclicBarrier;
|
||||||
|
|
||||||
|
public class CyclicBarrierExample {
|
||||||
|
|
||||||
|
public void start() {
|
||||||
|
CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> {
|
||||||
|
// Task
|
||||||
|
System.out.println("All previous tasks are completed");
|
||||||
|
});
|
||||||
|
|
||||||
|
Thread t1 = new Thread(new Task(cyclicBarrier), "T1");
|
||||||
|
Thread t2 = new Thread(new Task(cyclicBarrier), "T2");
|
||||||
|
Thread t3 = new Thread(new Task(cyclicBarrier), "T3");
|
||||||
|
|
||||||
|
if (!cyclicBarrier.isBroken()) {
|
||||||
|
t1.start();
|
||||||
|
t2.start();
|
||||||
|
t3.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.concurrent.cyclicbarrier;
|
||||||
|
|
||||||
|
import java.util.concurrent.BrokenBarrierException;
|
||||||
|
import java.util.concurrent.CyclicBarrier;
|
||||||
|
|
||||||
|
public class Task implements Runnable {
|
||||||
|
|
||||||
|
private CyclicBarrier barrier;
|
||||||
|
|
||||||
|
public Task(CyclicBarrier barrier) {
|
||||||
|
this.barrier = barrier;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
try {
|
||||||
|
System.out.println("Thread : "+ Thread.currentThread().getName() + " is waiting");
|
||||||
|
barrier.await();
|
||||||
|
System.out.println("Thread : "+ Thread.currentThread().getName() + " is released");
|
||||||
|
} catch (InterruptedException | BrokenBarrierException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.concurrent.executor;
|
||||||
|
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
|
||||||
|
public class ExecutorDemo {
|
||||||
|
|
||||||
|
public void execute() {
|
||||||
|
Executor executor = new Invoker();
|
||||||
|
executor.execute(()->{
|
||||||
|
// task to be performed
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.concurrent.executor;
|
||||||
|
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
|
||||||
|
public class Invoker implements Executor {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void execute(Runnable r) {
|
||||||
|
r.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,27 @@
|
|||||||
|
package com.baeldung.concurrent.executorservice;
|
||||||
|
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
public class ExecutorServiceDemo {
|
||||||
|
|
||||||
|
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||||
|
|
||||||
|
public void execute() {
|
||||||
|
|
||||||
|
executor.submit(() -> {
|
||||||
|
new Task();
|
||||||
|
});
|
||||||
|
|
||||||
|
executor.shutdown();
|
||||||
|
executor.shutdownNow();
|
||||||
|
try {
|
||||||
|
executor.awaitTermination(20l, TimeUnit.NANOSECONDS);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.concurrent.executorservice;
|
||||||
|
|
||||||
|
public class Task implements Runnable {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
// task details
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,44 @@
|
|||||||
|
package com.baeldung.concurrent.future;
|
||||||
|
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.TimeoutException;
|
||||||
|
|
||||||
|
public class FutureDemo {
|
||||||
|
|
||||||
|
public String invoke() {
|
||||||
|
|
||||||
|
String str = null;
|
||||||
|
|
||||||
|
ExecutorService executorService = Executors.newFixedThreadPool(10);
|
||||||
|
|
||||||
|
Future<String> future = executorService.submit(() -> {
|
||||||
|
// Task
|
||||||
|
Thread.sleep(10000l);
|
||||||
|
return "Hellow world";
|
||||||
|
});
|
||||||
|
|
||||||
|
future.cancel(false);
|
||||||
|
|
||||||
|
try {
|
||||||
|
future.get(20, TimeUnit.SECONDS);
|
||||||
|
} catch (InterruptedException | ExecutionException | TimeoutException e1) {
|
||||||
|
e1.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (future.isDone() && !future.isCancelled()) {
|
||||||
|
try {
|
||||||
|
str = future.get();
|
||||||
|
} catch (InterruptedException | ExecutionException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return str;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
package com.baeldung.concurrent.semaphore;
|
||||||
|
|
||||||
|
import java.util.concurrent.Semaphore;
|
||||||
|
|
||||||
|
public class SemaPhoreDemo {
|
||||||
|
|
||||||
|
static Semaphore semaphore = new Semaphore(10);
|
||||||
|
|
||||||
|
public void execute() throws InterruptedException {
|
||||||
|
|
||||||
|
System.out.println("Available permit : " + semaphore.availablePermits());
|
||||||
|
System.out.println("Number of threads waiting to acquire: " + semaphore.getQueueLength());
|
||||||
|
|
||||||
|
if (semaphore.tryAcquire()) {
|
||||||
|
semaphore.acquire();
|
||||||
|
// perform some critical operations
|
||||||
|
semaphore.release();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.concurrent.threadfactory;
|
||||||
|
|
||||||
|
import java.util.concurrent.ThreadFactory;
|
||||||
|
|
||||||
|
public class BaeldungThreadFactory implements ThreadFactory {
|
||||||
|
|
||||||
|
private int threadId;
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
public BaeldungThreadFactory(String name) {
|
||||||
|
threadId = 1;
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Thread newThread(Runnable r) {
|
||||||
|
Thread t = new Thread(r, name + "-Thread_" + threadId);
|
||||||
|
System.out.println("created new thread with id : " + threadId + " and name : " + t.getName());
|
||||||
|
threadId++;
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.concurrent.threadfactory;
|
||||||
|
|
||||||
|
public class Demo {
|
||||||
|
|
||||||
|
public void execute() {
|
||||||
|
BaeldungThreadFactory factory = new BaeldungThreadFactory("BaeldungThreadFactory");
|
||||||
|
for (int i = 0; i < 10; i++) {
|
||||||
|
Thread t = factory.newThread(new Task());
|
||||||
|
t.start();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.concurrent.threadfactory;
|
||||||
|
|
||||||
|
public class Task implements Runnable {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
// task details
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -9,7 +9,7 @@ public class AppleProduct implements Serializable {
|
|||||||
|
|
||||||
public String headphonePort;
|
public String headphonePort;
|
||||||
public String thunderboltPort;
|
public String thunderboltPort;
|
||||||
public String lighteningPort;
|
public String lightningPort;
|
||||||
|
|
||||||
public String getHeadphonePort() {
|
public String getHeadphonePort() {
|
||||||
return headphonePort;
|
return headphonePort;
|
||||||
@ -23,4 +23,8 @@ public class AppleProduct implements Serializable {
|
|||||||
return serialVersionUID;
|
return serialVersionUID;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getLightningPort() {
|
||||||
|
return lightningPort;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -9,11 +9,12 @@ public class DeserializationUtility {
|
|||||||
|
|
||||||
public static void main(String[] args) throws ClassNotFoundException, IOException {
|
public static void main(String[] args) throws ClassNotFoundException, IOException {
|
||||||
|
|
||||||
String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
|
String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADWxpZ2h0bmluZ1BvcnRxAH4AAUwAD3RodW5kZXJib2x0UG9ydHEAfgABeHB0ABFoZWFkcGhvbmVQb3J0MjAyMHQAEWxpZ2h0bmluZ1BvcnQyMDIwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
|
||||||
System.out.println("Deserializing AppleProduct...");
|
System.out.println("Deserializing AppleProduct...");
|
||||||
AppleProduct deserializedObj = (AppleProduct) deSerializeObjectFromString(serializedObj);
|
AppleProduct deserializedObj = (AppleProduct) deSerializeObjectFromString(serializedObj);
|
||||||
System.out.println("Headphone port of AppleProduct:" + deserializedObj.getHeadphonePort());
|
System.out.println("Headphone port of AppleProduct:" + deserializedObj.getHeadphonePort());
|
||||||
System.out.println("Thunderbolt port of AppleProduct:" + deserializedObj.getThunderboltPort());
|
System.out.println("Thunderbolt port of AppleProduct:" + deserializedObj.getThunderboltPort());
|
||||||
|
System.out.println("LightningPort port of AppleProduct:" + deserializedObj.getLightningPort());
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Object deSerializeObjectFromString(String s) throws IOException, ClassNotFoundException {
|
public static Object deSerializeObjectFromString(String s) throws IOException, ClassNotFoundException {
|
||||||
|
@ -13,6 +13,7 @@ public class SerializationUtility {
|
|||||||
AppleProduct macBook = new AppleProduct();
|
AppleProduct macBook = new AppleProduct();
|
||||||
macBook.headphonePort = "headphonePort2020";
|
macBook.headphonePort = "headphonePort2020";
|
||||||
macBook.thunderboltPort = "thunderboltPort2020";
|
macBook.thunderboltPort = "thunderboltPort2020";
|
||||||
|
macBook.lightningPort = "lightningPort2020";
|
||||||
|
|
||||||
String serializedObj = serializeObjectToString(macBook);
|
String serializedObj = serializeObjectToString(macBook);
|
||||||
System.out.println("Serialized AppleProduct object to string:");
|
System.out.println("Serialized AppleProduct object to string:");
|
||||||
|
@ -10,14 +10,13 @@ public class CustomTemporalAdjuster implements TemporalAdjuster {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Temporal adjustInto(Temporal temporal) {
|
public Temporal adjustInto(Temporal temporal) {
|
||||||
DayOfWeek dayOfWeek = DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK));
|
switch (DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK))) {
|
||||||
int daysToAdd;
|
case FRIDAY:
|
||||||
if (dayOfWeek == DayOfWeek.FRIDAY)
|
return temporal.plus(3, ChronoUnit.DAYS);
|
||||||
daysToAdd = 3;
|
case SATURDAY:
|
||||||
else if (dayOfWeek == DayOfWeek.SATURDAY)
|
return temporal.plus(2, ChronoUnit.DAYS);
|
||||||
daysToAdd = 2;
|
default:
|
||||||
else
|
return temporal.plus(1, ChronoUnit.DAYS);
|
||||||
daysToAdd = 1;
|
}
|
||||||
return temporal.plus(daysToAdd, ChronoUnit.DAYS);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.baeldung.concurrent.atomic;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class ThreadSafeCounterTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMultiThread_whenSafeCounterWithLockIncrement() throws InterruptedException {
|
||||||
|
ExecutorService service = Executors.newFixedThreadPool(3);
|
||||||
|
SafeCounterWithLock safeCounter = new SafeCounterWithLock();
|
||||||
|
|
||||||
|
IntStream.range(0, 1000)
|
||||||
|
.forEach(count -> service.submit(safeCounter::increment));
|
||||||
|
service.awaitTermination(100, TimeUnit.MILLISECONDS);
|
||||||
|
|
||||||
|
assertEquals(1000, safeCounter.getValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMultiThread_whenSafeCounterWithoutLockIncrement() throws InterruptedException {
|
||||||
|
ExecutorService service = Executors.newFixedThreadPool(3);
|
||||||
|
SafeCounterWithoutLock safeCounter = new SafeCounterWithoutLock();
|
||||||
|
|
||||||
|
IntStream.range(0, 1000)
|
||||||
|
.forEach(count -> service.submit(safeCounter::increment));
|
||||||
|
service.awaitTermination(100, TimeUnit.MILLISECONDS);
|
||||||
|
|
||||||
|
assertEquals(1000, safeCounter.getValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.concurrent.atomic;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This test shows the behaviour of a thread-unsafe class in a multithreaded scenario. We are calling
|
||||||
|
* the increment methods 1000 times from a pool of 3 threads. In most of the cases, the counter will
|
||||||
|
* less than 1000, because of lost updates, however, occasionally it may reach 1000, when no threads
|
||||||
|
* called the method simultaneously. This may cause the build to fail occasionally. Hence excluding this
|
||||||
|
* test from build by adding this in manual test
|
||||||
|
*/
|
||||||
|
public class ThreadUnsafeCounterManualTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMultiThread_whenUnsafeCounterIncrement() throws InterruptedException {
|
||||||
|
ExecutorService service = Executors.newFixedThreadPool(3);
|
||||||
|
UnsafeCounter unsafeCounter = new UnsafeCounter();
|
||||||
|
|
||||||
|
IntStream.range(0, 1000)
|
||||||
|
.forEach(count -> service.submit(unsafeCounter::increment));
|
||||||
|
service.awaitTermination(100, TimeUnit.MILLISECONDS);
|
||||||
|
|
||||||
|
assertEquals(1000, unsafeCounter.getValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -12,7 +12,7 @@ import org.junit.Test;
|
|||||||
|
|
||||||
public class DeserializationUnitTest {
|
public class DeserializationUnitTest {
|
||||||
|
|
||||||
private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
|
private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAdMuxAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADWxpZ2h0bmluZ1BvcnRxAH4AAUwAD3RodW5kZXJib2x0UG9ydHEAfgABeHB0ABFoZWFkcGhvbmVQb3J0MjAyMHQAEWxpZ2h0bmluZ1BvcnQyMDIwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA";
|
||||||
|
|
||||||
private static long userDefinedSerialVersionUID = 1234567L;
|
private static long userDefinedSerialVersionUID = 1234567L;
|
||||||
|
|
||||||
@ -29,6 +29,7 @@ public class DeserializationUnitTest {
|
|||||||
AppleProduct macBook = new AppleProduct();
|
AppleProduct macBook = new AppleProduct();
|
||||||
macBook.headphonePort = "headphonePort2020";
|
macBook.headphonePort = "headphonePort2020";
|
||||||
macBook.thunderboltPort = "thunderboltPort2020";
|
macBook.thunderboltPort = "thunderboltPort2020";
|
||||||
|
macBook.lightningPort = "lightningPort2020";
|
||||||
|
|
||||||
// serializes the "AppleProduct" object
|
// serializes the "AppleProduct" object
|
||||||
String serializedProduct = SerializationUtility.serializeObjectToString(macBook);
|
String serializedProduct = SerializationUtility.serializeObjectToString(macBook);
|
||||||
@ -38,6 +39,7 @@ public class DeserializationUnitTest {
|
|||||||
|
|
||||||
assertTrue(deserializedProduct.headphonePort.equalsIgnoreCase(macBook.headphonePort));
|
assertTrue(deserializedProduct.headphonePort.equalsIgnoreCase(macBook.headphonePort));
|
||||||
assertTrue(deserializedProduct.thunderboltPort.equalsIgnoreCase(macBook.thunderboltPort));
|
assertTrue(deserializedProduct.thunderboltPort.equalsIgnoreCase(macBook.thunderboltPort));
|
||||||
|
assertTrue(deserializedProduct.lightningPort.equalsIgnoreCase(macBook.lightningPort));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -59,7 +61,6 @@ public class DeserializationUnitTest {
|
|||||||
public void testDeserializeObj_incompatible() throws ClassNotFoundException, IOException {
|
public void testDeserializeObj_incompatible() throws ClassNotFoundException, IOException {
|
||||||
|
|
||||||
assertNotEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
|
assertNotEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
|
||||||
|
|
||||||
// attempts to deserialize the "AppleProduct" object
|
// attempts to deserialize the "AppleProduct" object
|
||||||
DeserializationUtility.deSerializeObjectFromString(serializedObj);
|
DeserializationUtility.deSerializeObjectFromString(serializedObj);
|
||||||
}
|
}
|
||||||
|
@ -1,34 +1,34 @@
|
|||||||
package com.baeldung.temporaladjusters;
|
package com.baeldung.temporaladjusters;
|
||||||
|
|
||||||
import java.time.DayOfWeek;
|
import com.baeldung.temporaladjuster.CustomTemporalAdjuster;
|
||||||
import java.time.LocalDate;
|
|
||||||
import java.time.Period;
|
|
||||||
import java.time.temporal.TemporalAdjuster;
|
|
||||||
import java.time.temporal.TemporalAdjusters;
|
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import com.baeldung.temporaladjuster.CustomTemporalAdjuster;
|
import java.time.LocalDate;
|
||||||
|
import java.time.Period;
|
||||||
|
import java.time.temporal.TemporalAdjuster;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
public class CustomTemporalAdjusterTest {
|
public class CustomTemporalAdjusterTest {
|
||||||
|
|
||||||
|
private static final TemporalAdjuster NEXT_WORKING_DAY = new CustomTemporalAdjuster();
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenAdjustAndImplementInterface_thenNextWorkingDay() {
|
public void whenAdjustAndImplementInterface_thenNextWorkingDay() {
|
||||||
LocalDate localDate = LocalDate.of(2017, 07, 8);
|
LocalDate localDate = LocalDate.of(2017, 07, 8);
|
||||||
CustomTemporalAdjuster temporalAdjuster = new CustomTemporalAdjuster();
|
CustomTemporalAdjuster temporalAdjuster = new CustomTemporalAdjuster();
|
||||||
LocalDate nextWorkingDay = localDate.with(temporalAdjuster);
|
LocalDate nextWorkingDay = localDate.with(temporalAdjuster);
|
||||||
|
|
||||||
Assert.assertEquals("2017-07-10", nextWorkingDay.toString());
|
assertEquals("2017-07-10", nextWorkingDay.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenAdjust_thenNextWorkingDay() {
|
public void whenAdjust_thenNextWorkingDay() {
|
||||||
LocalDate localDate = LocalDate.of(2017, 07, 8);
|
LocalDate localDate = LocalDate.of(2017, 07, 8);
|
||||||
TemporalAdjuster temporalAdjuster = NEXT_WORKING_DAY;
|
LocalDate date = localDate.with(NEXT_WORKING_DAY);
|
||||||
LocalDate date = localDate.with(temporalAdjuster);
|
|
||||||
|
|
||||||
Assert.assertEquals("2017-07-10", date.toString());
|
assertEquals("2017-07-10", date.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -39,18 +39,6 @@ public class CustomTemporalAdjusterTest {
|
|||||||
|
|
||||||
String fourteenDaysAfterDate = "2017-07-22";
|
String fourteenDaysAfterDate = "2017-07-22";
|
||||||
|
|
||||||
Assert.assertEquals(fourteenDaysAfterDate, result.toString());
|
assertEquals(fourteenDaysAfterDate, result.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
static TemporalAdjuster NEXT_WORKING_DAY = TemporalAdjusters.ofDateAdjuster(date -> {
|
|
||||||
DayOfWeek dayOfWeek = date.getDayOfWeek();
|
|
||||||
int daysToAdd;
|
|
||||||
if (dayOfWeek == DayOfWeek.FRIDAY)
|
|
||||||
daysToAdd = 3;
|
|
||||||
else if (dayOfWeek == DayOfWeek.SATURDAY)
|
|
||||||
daysToAdd = 2;
|
|
||||||
else
|
|
||||||
daysToAdd = 1;
|
|
||||||
return date.plusDays(daysToAdd);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -147,7 +147,7 @@
|
|||||||
<wiremock.version>2.5.1</wiremock.version>
|
<wiremock.version>2.5.1</wiremock.version>
|
||||||
|
|
||||||
<httpcore.version>4.4.5</httpcore.version>
|
<httpcore.version>4.4.5</httpcore.version>
|
||||||
<httpclient.version>4.5.2</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 -->
|
<httpclient.version>4.5.3</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 -->
|
||||||
|
|
||||||
<!-- maven plugins -->
|
<!-- maven plugins -->
|
||||||
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
||||||
|
@ -101,12 +101,7 @@ public class HttpAsyncClientLiveTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception {
|
public void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception {
|
||||||
final TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
|
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
|
||||||
@Override
|
|
||||||
public final boolean isTrusted(final X509Certificate[] certificate, final String authType) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
|
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
|
||||||
|
|
||||||
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLContext(sslContext).build();
|
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLContext(sslContext).build();
|
||||||
@ -160,7 +155,7 @@ public class HttpAsyncClientLiveTest {
|
|||||||
private final HttpContext context;
|
private final HttpContext context;
|
||||||
private final HttpGet request;
|
private final HttpGet request;
|
||||||
|
|
||||||
public GetThread(final CloseableHttpAsyncClient client, final HttpGet request) {
|
GetThread(final CloseableHttpAsyncClient client, final HttpGet request) {
|
||||||
this.client = client;
|
this.client = client;
|
||||||
context = HttpClientContext.create();
|
context = HttpClientContext.create();
|
||||||
this.request = request;
|
this.request = request;
|
||||||
|
@ -1,11 +1,7 @@
|
|||||||
package org.baeldung.httpclient;
|
package org.baeldung.httpclient;
|
||||||
|
|
||||||
import java.io.IOException;
|
import com.google.common.collect.Lists;
|
||||||
import java.io.InputStream;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import org.apache.http.Header;
|
import org.apache.http.Header;
|
||||||
import org.apache.http.HttpEntity;
|
|
||||||
import org.apache.http.HttpHeaders;
|
import org.apache.http.HttpHeaders;
|
||||||
import org.apache.http.client.ClientProtocolException;
|
import org.apache.http.client.ClientProtocolException;
|
||||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||||
@ -20,7 +16,8 @@ import org.junit.After;
|
|||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import com.google.common.collect.Lists;
|
import java.io.IOException;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
public class HttpClientHeadersLiveTest {
|
public class HttpClientHeadersLiveTest {
|
||||||
|
|
||||||
@ -37,19 +34,7 @@ public class HttpClientHeadersLiveTest {
|
|||||||
|
|
||||||
@After
|
@After
|
||||||
public final void after() throws IllegalStateException, IOException {
|
public final void after() throws IllegalStateException, IOException {
|
||||||
if (response == null) {
|
ResponseUtil.closeResponse(response);
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
final HttpEntity entity = response.getEntity();
|
|
||||||
if (entity != null) {
|
|
||||||
final InputStream instream = entity.getContent();
|
|
||||||
instream.close();
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
response.close();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// tests - headers - deprecated
|
// tests - headers - deprecated
|
||||||
|
@ -1,22 +1,7 @@
|
|||||||
package org.baeldung.httpclient;
|
package org.baeldung.httpclient;
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
|
||||||
import static org.junit.Assert.assertThat;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
import java.io.BufferedReader;
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.FileInputStream;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.io.InputStreamReader;
|
|
||||||
import java.net.URL;
|
|
||||||
import java.util.logging.Level;
|
|
||||||
import java.util.logging.Logger;
|
|
||||||
|
|
||||||
import org.apache.http.HttpEntity;
|
import org.apache.http.HttpEntity;
|
||||||
import org.apache.http.HttpStatus;
|
import org.apache.http.HttpStatus;
|
||||||
import org.apache.http.client.ClientProtocolException;
|
|
||||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||||
import org.apache.http.client.methods.HttpPost;
|
import org.apache.http.client.methods.HttpPost;
|
||||||
import org.apache.http.entity.ContentType;
|
import org.apache.http.entity.ContentType;
|
||||||
@ -30,6 +15,20 @@ import org.junit.After;
|
|||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.util.logging.Level;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class HttpClientMultipartLiveTest {
|
public class HttpClientMultipartLiveTest {
|
||||||
|
|
||||||
// No longer available
|
// No longer available
|
||||||
@ -67,15 +66,7 @@ public class HttpClientMultipartLiveTest {
|
|||||||
LOGGER.log(Level.SEVERE, e.getMessage(), e);
|
LOGGER.log(Level.SEVERE, e.getMessage(), e);
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
try {
|
ResponseUtil.closeResponse(response);
|
||||||
final HttpEntity entity = response.getEntity();
|
|
||||||
if (entity != null) {
|
|
||||||
final InputStream instream = entity.getContent();
|
|
||||||
instream.close();
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
response.close();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// tests
|
// tests
|
||||||
@ -113,7 +104,7 @@ public class HttpClientMultipartLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws ClientProtocolException, IOException {
|
public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException {
|
||||||
final URL url = Thread.currentThread()
|
final URL url = Thread.currentThread()
|
||||||
.getContextClassLoader()
|
.getContextClassLoader()
|
||||||
.getResource("uploads/" + TEXTFILENAME);
|
.getResource("uploads/" + TEXTFILENAME);
|
||||||
@ -138,7 +129,7 @@ public class HttpClientMultipartLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException {
|
public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
|
||||||
final URL url = Thread.currentThread()
|
final URL url = Thread.currentThread()
|
||||||
.getContextClassLoader()
|
.getContextClassLoader()
|
||||||
.getResource("uploads/" + ZIPFILENAME);
|
.getResource("uploads/" + ZIPFILENAME);
|
||||||
@ -169,7 +160,7 @@ public class HttpClientMultipartLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException {
|
public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
|
||||||
final String message = "This is a multipart post";
|
final String message = "This is a multipart post";
|
||||||
final byte[] bytes = "binary code".getBytes();
|
final byte[] bytes = "binary code".getBytes();
|
||||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||||
@ -192,18 +183,18 @@ public class HttpClientMultipartLiveTest {
|
|||||||
|
|
||||||
// UTIL
|
// UTIL
|
||||||
|
|
||||||
final String getContent() throws IOException {
|
private String getContent() throws IOException {
|
||||||
rd = new BufferedReader(new InputStreamReader(response.getEntity()
|
rd = new BufferedReader(new InputStreamReader(response.getEntity()
|
||||||
.getContent()));
|
.getContent()));
|
||||||
String body = "";
|
String body = "";
|
||||||
String content = "";
|
StringBuilder content = new StringBuilder();
|
||||||
while ((body = rd.readLine()) != null) {
|
while ((body = rd.readLine()) != null) {
|
||||||
content += body + "\n";
|
content.append(body).append("\n");
|
||||||
}
|
}
|
||||||
return content.trim();
|
return content.toString().trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
final String getContentTypeHeader() throws IOException {
|
private String getContentTypeHeader() throws IOException {
|
||||||
return post.getEntity()
|
return post.getEntity()
|
||||||
.getContentType()
|
.getContentType()
|
||||||
.toString();
|
.toString();
|
||||||
|
@ -1,20 +1,10 @@
|
|||||||
package org.baeldung.httpclient;
|
package org.baeldung.httpclient;
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
|
||||||
import static org.junit.Assert.assertFalse;
|
|
||||||
import static org.junit.Assert.assertThat;
|
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import org.apache.http.HttpEntity;
|
import org.apache.http.HttpEntity;
|
||||||
import org.apache.http.HttpResponse;
|
import org.apache.http.HttpResponse;
|
||||||
import org.apache.http.NameValuePair;
|
import org.apache.http.NameValuePair;
|
||||||
import org.apache.http.auth.AuthenticationException;
|
import org.apache.http.auth.AuthenticationException;
|
||||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||||
import org.apache.http.client.ClientProtocolException;
|
|
||||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||||
import org.apache.http.client.fluent.Form;
|
import org.apache.http.client.fluent.Form;
|
||||||
import org.apache.http.client.fluent.Request;
|
import org.apache.http.client.fluent.Request;
|
||||||
@ -29,17 +19,26 @@ import org.apache.http.impl.client.HttpClients;
|
|||||||
import org.apache.http.message.BasicNameValuePair;
|
import org.apache.http.message.BasicNameValuePair;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* NOTE : Need module spring-rest to be running
|
* NOTE : Need module spring-rest to be running
|
||||||
*/
|
*/
|
||||||
public class HttpClientPostingLiveTest {
|
public class HttpClientPostingLiveTest {
|
||||||
private static final String SAMPLE_URL = "http://localhost:8080/spring-rest/users";
|
private static final String SAMPLE_URL = "http://localhost:8082/spring-rest/users";
|
||||||
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";
|
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";
|
||||||
private static final String DEFAULT_USER = "test";
|
private static final String DEFAULT_USER = "test";
|
||||||
private static final String DEFAULT_PASS = "test";
|
private static final String DEFAULT_PASS = "test";
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSendPostRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
|
public void whenSendPostRequestUsingHttpClient_thenCorrect() throws IOException {
|
||||||
final CloseableHttpClient client = HttpClients.createDefault();
|
final CloseableHttpClient client = HttpClients.createDefault();
|
||||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
|
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
|
||||||
|
|
||||||
@ -54,7 +53,7 @@ public class HttpClientPostingLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException, AuthenticationException {
|
public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException, AuthenticationException {
|
||||||
final CloseableHttpClient client = HttpClients.createDefault();
|
final CloseableHttpClient client = HttpClients.createDefault();
|
||||||
final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);
|
final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);
|
||||||
|
|
||||||
@ -68,7 +67,7 @@ public class HttpClientPostingLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPostJsonUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
|
public void whenPostJsonUsingHttpClient_thenCorrect() throws IOException {
|
||||||
final CloseableHttpClient client = HttpClients.createDefault();
|
final CloseableHttpClient client = HttpClients.createDefault();
|
||||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/detail");
|
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/detail");
|
||||||
|
|
||||||
@ -84,14 +83,14 @@ public class HttpClientPostingLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws ClientProtocolException, IOException {
|
public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws IOException {
|
||||||
final HttpResponse response = Request.Post(SAMPLE_URL).bodyForm(Form.form().add("username", DEFAULT_USER).add("password", DEFAULT_PASS).build()).execute().returnResponse();
|
final HttpResponse response = Request.Post(SAMPLE_URL).bodyForm(Form.form().add("username", DEFAULT_USER).add("password", DEFAULT_PASS).build()).execute().returnResponse();
|
||||||
|
|
||||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
|
public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws IOException {
|
||||||
final CloseableHttpClient client = HttpClients.createDefault();
|
final CloseableHttpClient client = HttpClients.createDefault();
|
||||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/multipart");
|
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/multipart");
|
||||||
|
|
||||||
@ -109,7 +108,7 @@ public class HttpClientPostingLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUploadFileUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
|
public void whenUploadFileUsingHttpClient_thenCorrect() throws IOException {
|
||||||
final CloseableHttpClient client = HttpClients.createDefault();
|
final CloseableHttpClient client = HttpClients.createDefault();
|
||||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload");
|
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload");
|
||||||
|
|
||||||
@ -125,7 +124,7 @@ public class HttpClientPostingLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
|
public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws IOException {
|
||||||
final CloseableHttpClient client = HttpClients.createDefault();
|
final CloseableHttpClient client = HttpClients.createDefault();
|
||||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload");
|
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload");
|
||||||
|
|
||||||
@ -133,12 +132,7 @@ public class HttpClientPostingLiveTest {
|
|||||||
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
|
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
|
||||||
final HttpEntity multipart = builder.build();
|
final HttpEntity multipart = builder.build();
|
||||||
|
|
||||||
final ProgressEntityWrapper.ProgressListener pListener = new ProgressEntityWrapper.ProgressListener() {
|
final ProgressEntityWrapper.ProgressListener pListener = percentage -> assertFalse(Float.compare(percentage, 100) > 0);
|
||||||
@Override
|
|
||||||
public void progress(final float percentage) {
|
|
||||||
assertFalse(Float.compare(percentage, 100) > 0);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener));
|
httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener));
|
||||||
|
|
||||||
|
@ -1,13 +1,5 @@
|
|||||||
package org.baeldung.httpclient;
|
package org.baeldung.httpclient;
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
|
||||||
import static org.junit.Assert.assertThat;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
|
|
||||||
import org.apache.http.HttpEntity;
|
|
||||||
import org.apache.http.client.ClientProtocolException;
|
|
||||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||||
import org.apache.http.client.methods.HttpGet;
|
import org.apache.http.client.methods.HttpGet;
|
||||||
import org.apache.http.client.methods.HttpHead;
|
import org.apache.http.client.methods.HttpHead;
|
||||||
@ -21,6 +13,12 @@ import org.junit.After;
|
|||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
public class HttpClientRedirectLiveTest {
|
public class HttpClientRedirectLiveTest {
|
||||||
|
|
||||||
private CloseableHttpClient instance;
|
private CloseableHttpClient instance;
|
||||||
@ -34,25 +32,13 @@ public class HttpClientRedirectLiveTest {
|
|||||||
|
|
||||||
@After
|
@After
|
||||||
public final void after() throws IllegalStateException, IOException {
|
public final void after() throws IllegalStateException, IOException {
|
||||||
if (response == null) {
|
ResponseUtil.closeResponse(response);
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
final HttpEntity entity = response.getEntity();
|
|
||||||
if (entity != null) {
|
|
||||||
final InputStream instream = entity.getContent();
|
|
||||||
instream.close();
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
response.close();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// tests
|
// tests
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenRedirectsAreDisabledViaNewApi_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException {
|
public final void givenRedirectsAreDisabledViaNewApi_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
|
||||||
instance = HttpClients.custom().disableRedirectHandling().build();
|
instance = HttpClients.custom().disableRedirectHandling().build();
|
||||||
|
|
||||||
final HttpGet httpGet = new HttpGet("http://t.co/I5YYd9tddw");
|
final HttpGet httpGet = new HttpGet("http://t.co/I5YYd9tddw");
|
||||||
@ -62,7 +48,7 @@ public class HttpClientRedirectLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException {
|
public final void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
|
||||||
instance = HttpClientBuilder.create().disableRedirectHandling().build();
|
instance = HttpClientBuilder.create().disableRedirectHandling().build();
|
||||||
response = instance.execute(new HttpGet("http://t.co/I5YYd9tddw"));
|
response = instance.execute(new HttpGet("http://t.co/I5YYd9tddw"));
|
||||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
|
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
|
||||||
@ -71,26 +57,22 @@ public class HttpClientRedirectLiveTest {
|
|||||||
// redirect with POST
|
// redirect with POST
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException {
|
public final void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
|
||||||
instance = HttpClientBuilder.create().build();
|
instance = HttpClientBuilder.create().build();
|
||||||
response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
|
response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
|
||||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
|
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenRedirectingPOSTViaPost4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException {
|
public final void givenRedirectingPOSTViaPost4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
|
||||||
final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() {
|
final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() {
|
||||||
/** Redirectable methods. */
|
/** Redirectable methods. */
|
||||||
private final String[] REDIRECT_METHODS = new String[]{HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME};
|
private final String[] REDIRECT_METHODS = new String[]{HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME};
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean isRedirectable(final String method) {
|
protected boolean isRedirectable(final String method) {
|
||||||
for (final String m : REDIRECT_METHODS) {
|
return Arrays.stream(REDIRECT_METHODS)
|
||||||
if (m.equalsIgnoreCase(method)) {
|
.anyMatch(m -> m.equalsIgnoreCase(method));
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
}).build();
|
}).build();
|
||||||
|
|
||||||
@ -99,7 +81,7 @@ public class HttpClientRedirectLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenRedirectingPOSTVia4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException {
|
public final void givenRedirectingPOSTVia4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
|
||||||
final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()).build();
|
final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()).build();
|
||||||
|
|
||||||
response = client.execute(new HttpPost("http://t.co/I5YYd9tddw"));
|
response = client.execute(new HttpPost("http://t.co/I5YYd9tddw"));
|
||||||
@ -107,7 +89,7 @@ public class HttpClientRedirectLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException {
|
public final void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
|
||||||
instance = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
|
instance = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
|
||||||
response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
|
response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
|
||||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||||
|
@ -1,13 +1,5 @@
|
|||||||
package org.baeldung.httpclient;
|
package org.baeldung.httpclient;
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
|
||||||
import static org.junit.Assert.assertThat;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
|
|
||||||
import org.apache.http.HttpEntity;
|
|
||||||
import org.apache.http.client.ClientProtocolException;
|
|
||||||
import org.apache.http.client.config.RequestConfig;
|
import org.apache.http.client.config.RequestConfig;
|
||||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||||
import org.apache.http.client.methods.HttpGet;
|
import org.apache.http.client.methods.HttpGet;
|
||||||
@ -18,31 +10,24 @@ import org.apache.http.impl.client.HttpClientBuilder;
|
|||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
public class HttpClientTimeoutLiveTest {
|
public class HttpClientTimeoutLiveTest {
|
||||||
|
|
||||||
private CloseableHttpResponse response;
|
private CloseableHttpResponse response;
|
||||||
|
|
||||||
@After
|
@After
|
||||||
public final void after() throws IllegalStateException, IOException {
|
public final void after() throws IllegalStateException, IOException {
|
||||||
if (response == null) {
|
ResponseUtil.closeResponse(response);
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
final HttpEntity entity = response.getEntity();
|
|
||||||
if (entity != null) {
|
|
||||||
final InputStream instream = entity.getContent();
|
|
||||||
instream.close();
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
response.close();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// tests
|
// tests
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrect() throws ClientProtocolException, IOException {
|
public final void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrect() throws IOException {
|
||||||
final int timeout = 2;
|
final int timeout = 2;
|
||||||
final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
|
final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
|
||||||
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
|
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
|
||||||
@ -56,7 +41,7 @@ public class HttpClientTimeoutLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingNewApi_whenSettingTimeoutViaSocketConfig_thenCorrect() throws ClientProtocolException, IOException {
|
public final void givenUsingNewApi_whenSettingTimeoutViaSocketConfig_thenCorrect() throws IOException {
|
||||||
final int timeout = 2;
|
final int timeout = 2;
|
||||||
|
|
||||||
final SocketConfig config = SocketConfig.custom().setSoTimeout(timeout * 1000).build();
|
final SocketConfig config = SocketConfig.custom().setSoTimeout(timeout * 1000).build();
|
||||||
@ -70,7 +55,7 @@ public class HttpClientTimeoutLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingNewApi_whenSettingTimeoutViaHighLevelApi_thenCorrect() throws ClientProtocolException, IOException {
|
public final void givenUsingNewApi_whenSettingTimeoutViaHighLevelApi_thenCorrect() throws IOException {
|
||||||
final int timeout = 5;
|
final int timeout = 5;
|
||||||
|
|
||||||
final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
|
final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
|
||||||
@ -87,7 +72,7 @@ public class HttpClientTimeoutLiveTest {
|
|||||||
* This simulates a timeout against a domain with multiple routes/IPs to it (not a single raw IP)
|
* This simulates a timeout against a domain with multiple routes/IPs to it (not a single raw IP)
|
||||||
*/
|
*/
|
||||||
@Test(expected = HttpHostConnectException.class)
|
@Test(expected = HttpHostConnectException.class)
|
||||||
public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws ClientProtocolException, IOException {
|
public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws IOException {
|
||||||
final int timeout = 3;
|
final int timeout = 3;
|
||||||
|
|
||||||
final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
|
final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
|
||||||
|
@ -1,14 +1,5 @@
|
|||||||
package org.baeldung.httpclient;
|
package org.baeldung.httpclient;
|
||||||
|
|
||||||
import static org.hamcrest.CoreMatchers.equalTo;
|
|
||||||
import static org.junit.Assert.assertThat;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.security.GeneralSecurityException;
|
|
||||||
|
|
||||||
import javax.net.ssl.SSLContext;
|
|
||||||
import javax.net.ssl.SSLHandshakeException;
|
|
||||||
|
|
||||||
import org.apache.http.HttpResponse;
|
import org.apache.http.HttpResponse;
|
||||||
import org.apache.http.client.methods.HttpGet;
|
import org.apache.http.client.methods.HttpGet;
|
||||||
import org.apache.http.conn.ClientConnectionManager;
|
import org.apache.http.conn.ClientConnectionManager;
|
||||||
@ -28,6 +19,14 @@ import org.apache.http.ssl.SSLContextBuilder;
|
|||||||
import org.apache.http.ssl.SSLContexts;
|
import org.apache.http.ssl.SSLContexts;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import javax.net.ssl.SSLContext;
|
||||||
|
import javax.net.ssl.SSLHandshakeException;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.security.GeneralSecurityException;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.equalTo;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This test requires a localhost server over HTTPS <br>
|
* This test requires a localhost server over HTTPS <br>
|
||||||
* It should only be manually run, not part of the automated build
|
* It should only be manually run, not part of the automated build
|
||||||
|
@ -10,7 +10,7 @@ import org.apache.http.entity.HttpEntityWrapper;
|
|||||||
public class ProgressEntityWrapper extends HttpEntityWrapper {
|
public class ProgressEntityWrapper extends HttpEntityWrapper {
|
||||||
private final ProgressListener listener;
|
private final ProgressListener listener;
|
||||||
|
|
||||||
public ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) {
|
ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) {
|
||||||
super(entity);
|
super(entity);
|
||||||
this.listener = listener;
|
this.listener = listener;
|
||||||
}
|
}
|
||||||
@ -20,7 +20,7 @@ public class ProgressEntityWrapper extends HttpEntityWrapper {
|
|||||||
super.writeTo(new CountingOutputStream(outstream, listener, getContentLength()));
|
super.writeTo(new CountingOutputStream(outstream, listener, getContentLength()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static interface ProgressListener {
|
public interface ProgressListener {
|
||||||
void progress(float percentage);
|
void progress(float percentage);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -30,7 +30,7 @@ public class ProgressEntityWrapper extends HttpEntityWrapper {
|
|||||||
private long transferred;
|
private long transferred;
|
||||||
private long totalBytes;
|
private long totalBytes;
|
||||||
|
|
||||||
public CountingOutputStream(final OutputStream out, final ProgressListener listener, final long totalBytes) {
|
CountingOutputStream(final OutputStream out, final ProgressListener listener, final long totalBytes) {
|
||||||
super(out);
|
super(out);
|
||||||
this.listener = listener;
|
this.listener = listener;
|
||||||
transferred = 0;
|
transferred = 0;
|
||||||
|
@ -0,0 +1,26 @@
|
|||||||
|
package org.baeldung.httpclient;
|
||||||
|
|
||||||
|
import org.apache.http.HttpEntity;
|
||||||
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public final class ResponseUtil {
|
||||||
|
private ResponseUtil() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void closeResponse(CloseableHttpResponse response) throws IOException {
|
||||||
|
if (response == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
final HttpEntity entity = response.getEntity();
|
||||||
|
if (entity != null) {
|
||||||
|
entity.getContent().close();
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
response.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -24,7 +24,14 @@ import org.junit.Test;
|
|||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
import static com.github.tomakehurst.wiremock.client.WireMock.*;
|
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
|
||||||
|
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
|
||||||
|
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
|
||||||
|
import static com.github.tomakehurst.wiremock.client.WireMock.get;
|
||||||
|
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
|
||||||
|
import static com.github.tomakehurst.wiremock.client.WireMock.post;
|
||||||
|
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
|
||||||
|
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
public class HttpClientAdvancedConfigurationIntegrationTest {
|
public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||||
|
@ -1,13 +1,5 @@
|
|||||||
package org.baeldung.httpclient.base;
|
package org.baeldung.httpclient.base;
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
|
||||||
import static org.hamcrest.Matchers.notNullValue;
|
|
||||||
import static org.junit.Assert.assertThat;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
|
|
||||||
import org.apache.http.HttpEntity;
|
|
||||||
import org.apache.http.HttpStatus;
|
import org.apache.http.HttpStatus;
|
||||||
import org.apache.http.client.ClientProtocolException;
|
import org.apache.http.client.ClientProtocolException;
|
||||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||||
@ -16,10 +8,17 @@ import org.apache.http.entity.ContentType;
|
|||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.apache.http.impl.client.HttpClientBuilder;
|
import org.apache.http.impl.client.HttpClientBuilder;
|
||||||
import org.apache.http.util.EntityUtils;
|
import org.apache.http.util.EntityUtils;
|
||||||
|
import org.baeldung.httpclient.ResponseUtil;
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
|
import static org.hamcrest.Matchers.notNullValue;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
public class HttpClientBasicLiveTest {
|
public class HttpClientBasicLiveTest {
|
||||||
|
|
||||||
private static final String SAMPLE_URL = "http://www.github.com";
|
private static final String SAMPLE_URL = "http://www.github.com";
|
||||||
@ -35,19 +34,7 @@ public class HttpClientBasicLiveTest {
|
|||||||
|
|
||||||
@After
|
@After
|
||||||
public final void after() throws IllegalStateException, IOException {
|
public final void after() throws IllegalStateException, IOException {
|
||||||
if (response == null) {
|
ResponseUtil.closeResponse(response);
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
final HttpEntity entity = response.getEntity();
|
|
||||||
if (entity != null) {
|
|
||||||
final InputStream instream = entity.getContent();
|
|
||||||
instream.close();
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
response.close();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// tests
|
// tests
|
||||||
|
@ -1,22 +1,20 @@
|
|||||||
package org.baeldung.httpclient.base;
|
package org.baeldung.httpclient.base;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
|
|
||||||
import org.apache.http.HttpEntity;
|
|
||||||
import org.apache.http.auth.AuthenticationException;
|
import org.apache.http.auth.AuthenticationException;
|
||||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||||
import org.apache.http.client.ClientProtocolException;
|
|
||||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||||
import org.apache.http.client.methods.HttpPost;
|
import org.apache.http.client.methods.HttpPost;
|
||||||
import org.apache.http.entity.StringEntity;
|
import org.apache.http.entity.StringEntity;
|
||||||
import org.apache.http.impl.auth.BasicScheme;
|
import org.apache.http.impl.auth.BasicScheme;
|
||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.apache.http.impl.client.HttpClientBuilder;
|
import org.apache.http.impl.client.HttpClientBuilder;
|
||||||
|
import org.baeldung.httpclient.ResponseUtil;
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
public class HttpClientBasicPostLiveTest {
|
public class HttpClientBasicPostLiveTest {
|
||||||
|
|
||||||
private static final String SAMPLE_URL = "http://www.github.com";
|
private static final String SAMPLE_URL = "http://www.github.com";
|
||||||
@ -32,37 +30,25 @@ public class HttpClientBasicPostLiveTest {
|
|||||||
|
|
||||||
@After
|
@After
|
||||||
public final void after() throws IllegalStateException, IOException {
|
public final void after() throws IllegalStateException, IOException {
|
||||||
if (response == null) {
|
ResponseUtil.closeResponse(response);
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
final HttpEntity entity = response.getEntity();
|
|
||||||
if (entity != null) {
|
|
||||||
final InputStream instream = entity.getContent();
|
|
||||||
instream.close();
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
response.close();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// tests - non-GET
|
// tests - non-GET
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void whenExecutingPostRequest_thenNoExceptions() throws ClientProtocolException, IOException {
|
public final void whenExecutingPostRequest_thenNoExceptions() throws IOException {
|
||||||
instance.execute(new HttpPost(SAMPLE_URL));
|
instance.execute(new HttpPost(SAMPLE_URL));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws ClientProtocolException, IOException {
|
public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException {
|
||||||
final HttpPost request = new HttpPost(SAMPLE_URL);
|
final HttpPost request = new HttpPost(SAMPLE_URL);
|
||||||
request.setEntity(new StringEntity("in the body of the POST"));
|
request.setEntity(new StringEntity("in the body of the POST"));
|
||||||
instance.execute(request);
|
instance.execute(request);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws ClientProtocolException, IOException, AuthenticationException {
|
public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException, AuthenticationException {
|
||||||
final HttpPost request = new HttpPost(SAMPLE_URL);
|
final HttpPost request = new HttpPost(SAMPLE_URL);
|
||||||
request.setEntity(new StringEntity("in the body of the POST"));
|
request.setEntity(new StringEntity("in the body of the POST"));
|
||||||
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password");
|
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password");
|
||||||
|
@ -11,12 +11,12 @@ import org.apache.http.impl.client.CloseableHttpClient;
|
|||||||
import org.apache.http.impl.client.HttpClientBuilder;
|
import org.apache.http.impl.client.HttpClientBuilder;
|
||||||
import org.apache.http.impl.client.HttpClients;
|
import org.apache.http.impl.client.HttpClients;
|
||||||
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
|
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
|
||||||
|
import org.baeldung.httpclient.ResponseUtil;
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.emptyArray;
|
import static org.hamcrest.Matchers.emptyArray;
|
||||||
import static org.hamcrest.Matchers.not;
|
import static org.hamcrest.Matchers.not;
|
||||||
@ -37,19 +37,7 @@ public class HttpClientLiveTest {
|
|||||||
|
|
||||||
@After
|
@After
|
||||||
public final void after() throws IllegalStateException, IOException {
|
public final void after() throws IllegalStateException, IOException {
|
||||||
if (response == null) {
|
ResponseUtil.closeResponse(response);
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
final HttpEntity entity = response.getEntity();
|
|
||||||
if (entity != null) {
|
|
||||||
final InputStream instream = entity.getContent();
|
|
||||||
instream.close();
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
response.close();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// tests
|
// tests
|
||||||
|
@ -1,9 +1,5 @@
|
|||||||
package org.baeldung.httpclient.base;
|
package org.baeldung.httpclient.base;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
|
|
||||||
import org.apache.http.HttpEntity;
|
|
||||||
import org.apache.http.auth.AuthScope;
|
import org.apache.http.auth.AuthScope;
|
||||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||||
import org.apache.http.client.CredentialsProvider;
|
import org.apache.http.client.CredentialsProvider;
|
||||||
@ -12,8 +8,11 @@ import org.apache.http.client.methods.HttpGet;
|
|||||||
import org.apache.http.impl.client.BasicCredentialsProvider;
|
import org.apache.http.impl.client.BasicCredentialsProvider;
|
||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.apache.http.impl.client.HttpClientBuilder;
|
import org.apache.http.impl.client.HttpClientBuilder;
|
||||||
|
import org.baeldung.httpclient.ResponseUtil;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* NOTE : Need module spring-security-rest-basic-auth to be running
|
* NOTE : Need module spring-security-rest-basic-auth to be running
|
||||||
*/
|
*/
|
||||||
@ -32,15 +31,6 @@ public class HttpClientSandboxLiveTest {
|
|||||||
|
|
||||||
System.out.println(response.getStatusLine());
|
System.out.println(response.getStatusLine());
|
||||||
|
|
||||||
try {
|
ResponseUtil.closeResponse(response);
|
||||||
final HttpEntity entity = response.getEntity();
|
|
||||||
if (entity != null) {
|
|
||||||
// EntityUtils.consume(entity);
|
|
||||||
final InputStream instream = entity.getContent();
|
|
||||||
instream.close();
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
response.close();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,11 +1,5 @@
|
|||||||
package org.baeldung.httpclient.conn;
|
package org.baeldung.httpclient.conn;
|
||||||
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.concurrent.ExecutionException;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
import org.apache.http.HeaderElement;
|
import org.apache.http.HeaderElement;
|
||||||
import org.apache.http.HeaderElementIterator;
|
import org.apache.http.HeaderElementIterator;
|
||||||
import org.apache.http.HttpClientConnection;
|
import org.apache.http.HttpClientConnection;
|
||||||
@ -36,6 +30,12 @@ import org.junit.Before;
|
|||||||
import org.junit.Ignore;
|
import org.junit.Ignore;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class HttpClientConnectionManagementLiveTest {
|
public class HttpClientConnectionManagementLiveTest {
|
||||||
private static final String SERVER1 = "http://www.petrikainulainen.net/";
|
private static final String SERVER1 = "http://www.petrikainulainen.net/";
|
||||||
private static final String SERVER7 = "http://www.baeldung.com/";
|
private static final String SERVER7 = "http://www.baeldung.com/";
|
||||||
|
@ -9,7 +9,7 @@ public class IdleConnectionMonitorThread extends Thread {
|
|||||||
private final HttpClientConnectionManager connMgr;
|
private final HttpClientConnectionManager connMgr;
|
||||||
private volatile boolean shutdown;
|
private volatile boolean shutdown;
|
||||||
|
|
||||||
public IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) {
|
IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) {
|
||||||
super();
|
super();
|
||||||
this.connMgr = connMgr;
|
this.connMgr = connMgr;
|
||||||
}
|
}
|
||||||
@ -31,7 +31,7 @@ public class IdleConnectionMonitorThread extends Thread {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public final void shutdown() {
|
private void shutdown() {
|
||||||
shutdown = true;
|
shutdown = true;
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
notifyAll();
|
notifyAll();
|
||||||
|
@ -18,23 +18,23 @@ public class MultiHttpClientConnThread extends Thread {
|
|||||||
private final HttpGet get;
|
private final HttpGet get;
|
||||||
|
|
||||||
private PoolingHttpClientConnectionManager connManager;
|
private PoolingHttpClientConnectionManager connManager;
|
||||||
public int leasedConn;
|
private int leasedConn;
|
||||||
|
|
||||||
public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) {
|
MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) {
|
||||||
this.client = client;
|
this.client = client;
|
||||||
this.get = get;
|
this.get = get;
|
||||||
this.connManager = connManager;
|
this.connManager = connManager;
|
||||||
leasedConn = 0;
|
leasedConn = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) {
|
MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) {
|
||||||
this.client = client;
|
this.client = client;
|
||||||
this.get = get;
|
this.get = get;
|
||||||
}
|
}
|
||||||
|
|
||||||
// API
|
// API
|
||||||
|
|
||||||
public final int getLeasedConn() {
|
final int getLeasedConn() {
|
||||||
return leasedConn;
|
return leasedConn;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -61,8 +61,6 @@ public class MultiHttpClientConnThread extends Thread {
|
|||||||
}
|
}
|
||||||
|
|
||||||
EntityUtils.consume(response.getEntity());
|
EntityUtils.consume(response.getEntity());
|
||||||
} catch (final ClientProtocolException ex) {
|
|
||||||
logger.error("", ex);
|
|
||||||
} catch (final IOException ex) {
|
} catch (final IOException ex) {
|
||||||
logger.error("", ex);
|
logger.error("", ex);
|
||||||
}
|
}
|
||||||
|
@ -18,7 +18,7 @@ public class TesterVersion_MultiHttpClientConnThread extends Thread {
|
|||||||
private final HttpGet get;
|
private final HttpGet get;
|
||||||
private PoolingHttpClientConnectionManager connManager;
|
private PoolingHttpClientConnectionManager connManager;
|
||||||
|
|
||||||
public TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) {
|
TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) {
|
||||||
this.client = client;
|
this.client = client;
|
||||||
this.get = get;
|
this.get = get;
|
||||||
this.connManager = Preconditions.checkNotNull(connManager);
|
this.connManager = Preconditions.checkNotNull(connManager);
|
||||||
@ -38,8 +38,6 @@ public class TesterVersion_MultiHttpClientConnThread extends Thread {
|
|||||||
|
|
||||||
logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased());
|
logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased());
|
||||||
logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable());
|
logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable());
|
||||||
} catch (final ClientProtocolException ex) {
|
|
||||||
logger.error("", ex);
|
|
||||||
} catch (final IOException ex) {
|
} catch (final IOException ex) {
|
||||||
logger.error("", ex);
|
logger.error("", ex);
|
||||||
}
|
}
|
||||||
|
@ -1,12 +1,7 @@
|
|||||||
package org.baeldung.httpclient.rare;
|
package org.baeldung.httpclient.rare;
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import com.google.common.base.Preconditions;
|
||||||
import static org.junit.Assert.assertThat;
|
import com.google.common.collect.Lists;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.tuple.ImmutablePair;
|
import org.apache.commons.lang3.tuple.ImmutablePair;
|
||||||
import org.apache.commons.lang3.tuple.Pair;
|
import org.apache.commons.lang3.tuple.Pair;
|
||||||
import org.apache.http.Header;
|
import org.apache.http.Header;
|
||||||
@ -20,8 +15,12 @@ import org.apache.http.util.EntityUtils;
|
|||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import com.google.common.base.Preconditions;
|
import java.io.IOException;
|
||||||
import com.google.common.collect.Lists;
|
import java.io.InputStream;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
public class HttpClientUnshortenLiveTest {
|
public class HttpClientUnshortenLiveTest {
|
||||||
|
|
||||||
@ -52,7 +51,7 @@ public class HttpClientUnshortenLiveTest {
|
|||||||
|
|
||||||
// API
|
// API
|
||||||
|
|
||||||
final String expand(final String urlArg) throws IOException {
|
private String expand(final String urlArg) throws IOException {
|
||||||
String originalUrl = urlArg;
|
String originalUrl = urlArg;
|
||||||
String newUrl = expandSingleLevel(originalUrl);
|
String newUrl = expandSingleLevel(originalUrl);
|
||||||
while (!originalUrl.equals(newUrl)) {
|
while (!originalUrl.equals(newUrl)) {
|
||||||
@ -81,7 +80,7 @@ public class HttpClientUnshortenLiveTest {
|
|||||||
return newUrl;
|
return newUrl;
|
||||||
}
|
}
|
||||||
|
|
||||||
final Pair<Integer, String> expandSingleLevelSafe(final String url) throws IOException {
|
private Pair<Integer, String> expandSingleLevelSafe(final String url) throws IOException {
|
||||||
HttpHead request = null;
|
HttpHead request = null;
|
||||||
HttpEntity httpEntity = null;
|
HttpEntity httpEntity = null;
|
||||||
InputStream entityContentStream = null;
|
InputStream entityContentStream = null;
|
||||||
@ -95,15 +94,15 @@ public class HttpClientUnshortenLiveTest {
|
|||||||
|
|
||||||
final int statusCode = httpResponse.getStatusLine().getStatusCode();
|
final int statusCode = httpResponse.getStatusLine().getStatusCode();
|
||||||
if (statusCode != 301 && statusCode != 302) {
|
if (statusCode != 301 && statusCode != 302) {
|
||||||
return new ImmutablePair<Integer, String>(statusCode, url);
|
return new ImmutablePair<>(statusCode, url);
|
||||||
}
|
}
|
||||||
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
|
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
|
||||||
Preconditions.checkState(headers.length == 1);
|
Preconditions.checkState(headers.length == 1);
|
||||||
final String newUrl = headers[0].getValue();
|
final String newUrl = headers[0].getValue();
|
||||||
|
|
||||||
return new ImmutablePair<Integer, String>(statusCode, newUrl);
|
return new ImmutablePair<>(statusCode, newUrl);
|
||||||
} catch (final IllegalArgumentException uriEx) {
|
} catch (final IllegalArgumentException uriEx) {
|
||||||
return new ImmutablePair<Integer, String>(500, url);
|
return new ImmutablePair<>(500, url);
|
||||||
} finally {
|
} finally {
|
||||||
if (request != null) {
|
if (request != null) {
|
||||||
request.releaseConnection();
|
request.releaseConnection();
|
||||||
@ -117,7 +116,7 @@ public class HttpClientUnshortenLiveTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
final String expandSingleLevel(final String url) throws IOException {
|
private String expandSingleLevel(final String url) throws IOException {
|
||||||
HttpHead request = null;
|
HttpHead request = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@ -130,9 +129,8 @@ public class HttpClientUnshortenLiveTest {
|
|||||||
}
|
}
|
||||||
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
|
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
|
||||||
Preconditions.checkState(headers.length == 1);
|
Preconditions.checkState(headers.length == 1);
|
||||||
final String newUrl = headers[0].getValue();
|
|
||||||
|
|
||||||
return newUrl;
|
return headers[0].getValue();
|
||||||
} catch (final IllegalArgumentException uriEx) {
|
} catch (final IllegalArgumentException uriEx) {
|
||||||
return url;
|
return url;
|
||||||
} finally {
|
} finally {
|
||||||
|
@ -1,21 +1,12 @@
|
|||||||
package org.baeldung.httpclient.sec;
|
package org.baeldung.httpclient.sec;
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
|
||||||
import static org.junit.Assert.assertThat;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.nio.charset.Charset;
|
|
||||||
|
|
||||||
import org.apache.commons.codec.binary.Base64;
|
import org.apache.commons.codec.binary.Base64;
|
||||||
import org.apache.http.HttpEntity;
|
|
||||||
import org.apache.http.HttpHeaders;
|
import org.apache.http.HttpHeaders;
|
||||||
import org.apache.http.HttpHost;
|
import org.apache.http.HttpHost;
|
||||||
import org.apache.http.HttpStatus;
|
import org.apache.http.HttpStatus;
|
||||||
import org.apache.http.auth.AuthScope;
|
import org.apache.http.auth.AuthScope;
|
||||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||||
import org.apache.http.client.AuthCache;
|
import org.apache.http.client.AuthCache;
|
||||||
import org.apache.http.client.ClientProtocolException;
|
|
||||||
import org.apache.http.client.CredentialsProvider;
|
import org.apache.http.client.CredentialsProvider;
|
||||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||||
import org.apache.http.client.methods.HttpGet;
|
import org.apache.http.client.methods.HttpGet;
|
||||||
@ -26,10 +17,17 @@ import org.apache.http.impl.client.BasicCredentialsProvider;
|
|||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.apache.http.impl.client.HttpClientBuilder;
|
import org.apache.http.impl.client.HttpClientBuilder;
|
||||||
import org.apache.http.protocol.HttpContext;
|
import org.apache.http.protocol.HttpContext;
|
||||||
|
import org.baeldung.httpclient.ResponseUtil;
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.Charset;
|
||||||
|
|
||||||
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* NOTE : Need module spring-security-rest-basic-auth to be running
|
* NOTE : Need module spring-security-rest-basic-auth to be running
|
||||||
*/
|
*/
|
||||||
@ -51,25 +49,13 @@ public class HttpClientAuthLiveTest {
|
|||||||
|
|
||||||
@After
|
@After
|
||||||
public final void after() throws IllegalStateException, IOException {
|
public final void after() throws IllegalStateException, IOException {
|
||||||
if (response == null) {
|
ResponseUtil.closeResponse(response);
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
final HttpEntity entity = response.getEntity();
|
|
||||||
if (entity != null) {
|
|
||||||
final InputStream instream = entity.getContent();
|
|
||||||
instream.close();
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
response.close();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// tests
|
// tests
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws ClientProtocolException, IOException {
|
public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException {
|
||||||
client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider()).build();
|
client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider()).build();
|
||||||
|
|
||||||
response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION));
|
response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION));
|
||||||
@ -79,7 +65,7 @@ public class HttpClientAuthLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws ClientProtocolException, IOException {
|
public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException {
|
||||||
client = HttpClientBuilder.create().build();
|
client = HttpClientBuilder.create().build();
|
||||||
response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context());
|
response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context());
|
||||||
|
|
||||||
@ -88,7 +74,7 @@ public class HttpClientAuthLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws ClientProtocolException, IOException {
|
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws IOException {
|
||||||
client = HttpClientBuilder.create().build();
|
client = HttpClientBuilder.create().build();
|
||||||
|
|
||||||
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
|
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
|
||||||
@ -100,7 +86,7 @@ public class HttpClientAuthLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws ClientProtocolException, IOException {
|
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws IOException {
|
||||||
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
|
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
|
||||||
final String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
|
final String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
|
||||||
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
|
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
|
||||||
@ -116,14 +102,14 @@ public class HttpClientAuthLiveTest {
|
|||||||
|
|
||||||
// UTILS
|
// UTILS
|
||||||
|
|
||||||
private final CredentialsProvider provider() {
|
private CredentialsProvider provider() {
|
||||||
final CredentialsProvider provider = new BasicCredentialsProvider();
|
final CredentialsProvider provider = new BasicCredentialsProvider();
|
||||||
final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
|
final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
|
||||||
provider.setCredentials(AuthScope.ANY, credentials);
|
provider.setCredentials(AuthScope.ANY, credentials);
|
||||||
return provider;
|
return provider;
|
||||||
}
|
}
|
||||||
|
|
||||||
private final HttpContext context() {
|
private HttpContext context() {
|
||||||
final HttpHost targetHost = new HttpHost("localhost", 8080, "http");
|
final HttpHost targetHost = new HttpHost("localhost", 8080, "http");
|
||||||
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
|
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
|
||||||
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS));
|
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS));
|
||||||
@ -141,12 +127,11 @@ public class HttpClientAuthLiveTest {
|
|||||||
return context;
|
return context;
|
||||||
}
|
}
|
||||||
|
|
||||||
private final String authorizationHeader(final String username, final String password) {
|
private String authorizationHeader(final String username, final String password) {
|
||||||
final String auth = username + ":" + password;
|
final String auth = username + ":" + password;
|
||||||
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
|
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
|
||||||
final String authHeader = "Basic " + new String(encodedAuth);
|
|
||||||
|
|
||||||
return authHeader;
|
return "Basic " + new String(encodedAuth);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,13 +1,5 @@
|
|||||||
package org.baeldung.httpclient.sec;
|
package org.baeldung.httpclient.sec;
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
|
||||||
import static org.junit.Assert.assertThat;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
|
|
||||||
import org.apache.http.HttpEntity;
|
|
||||||
import org.apache.http.client.ClientProtocolException;
|
|
||||||
import org.apache.http.client.HttpClient;
|
import org.apache.http.client.HttpClient;
|
||||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||||
import org.apache.http.client.methods.HttpGet;
|
import org.apache.http.client.methods.HttpGet;
|
||||||
@ -18,10 +10,16 @@ import org.apache.http.impl.client.HttpClientBuilder;
|
|||||||
import org.apache.http.impl.cookie.BasicClientCookie;
|
import org.apache.http.impl.cookie.BasicClientCookie;
|
||||||
import org.apache.http.protocol.BasicHttpContext;
|
import org.apache.http.protocol.BasicHttpContext;
|
||||||
import org.apache.http.protocol.HttpContext;
|
import org.apache.http.protocol.HttpContext;
|
||||||
|
import org.baeldung.httpclient.ResponseUtil;
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
public class HttpClientCookieLiveTest {
|
public class HttpClientCookieLiveTest {
|
||||||
|
|
||||||
private CloseableHttpClient instance;
|
private CloseableHttpClient instance;
|
||||||
@ -35,25 +33,13 @@ public class HttpClientCookieLiveTest {
|
|||||||
|
|
||||||
@After
|
@After
|
||||||
public final void after() throws IllegalStateException, IOException {
|
public final void after() throws IllegalStateException, IOException {
|
||||||
if (response == null) {
|
ResponseUtil.closeResponse(response);
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
final HttpEntity entity = response.getEntity();
|
|
||||||
if (entity != null) {
|
|
||||||
final InputStream instream = entity.getContent();
|
|
||||||
instream.close();
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
response.close();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// tests
|
// tests
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void whenSettingCookiesOnARequest_thenCorrect() throws ClientProtocolException, IOException {
|
public final void whenSettingCookiesOnARequest_thenCorrect() throws IOException {
|
||||||
instance = HttpClientBuilder.create().build();
|
instance = HttpClientBuilder.create().build();
|
||||||
final HttpGet request = new HttpGet("http://www.github.com");
|
final HttpGet request = new HttpGet("http://www.github.com");
|
||||||
request.setHeader("Cookie", "JSESSIONID=1234");
|
request.setHeader("Cookie", "JSESSIONID=1234");
|
||||||
@ -64,7 +50,7 @@ public class HttpClientCookieLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws ClientProtocolException, IOException {
|
public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws IOException {
|
||||||
final BasicCookieStore cookieStore = new BasicCookieStore();
|
final BasicCookieStore cookieStore = new BasicCookieStore();
|
||||||
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
|
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
|
||||||
cookie.setDomain(".github.com");
|
cookie.setDomain(".github.com");
|
||||||
@ -80,7 +66,7 @@ public class HttpClientCookieLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws ClientProtocolException, IOException {
|
public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws IOException {
|
||||||
final BasicCookieStore cookieStore = new BasicCookieStore();
|
final BasicCookieStore cookieStore = new BasicCookieStore();
|
||||||
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
|
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
|
||||||
cookie.setDomain(".github.com");
|
cookie.setDomain(".github.com");
|
||||||
@ -96,7 +82,7 @@ public class HttpClientCookieLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws ClientProtocolException, IOException {
|
public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws IOException {
|
||||||
final BasicCookieStore cookieStore = new BasicCookieStore();
|
final BasicCookieStore cookieStore = new BasicCookieStore();
|
||||||
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
|
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
|
||||||
cookie.setDomain(".github.com");
|
cookie.setDomain(".github.com");
|
||||||
|
10
jmh/pom.xml
10
jmh/pom.xml
@ -12,6 +12,8 @@
|
|||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||||
<java.version>1.8</java.version>
|
<java.version>1.8</java.version>
|
||||||
|
<maven.compiler.source>1.6</maven.compiler.source>
|
||||||
|
<maven.compiler.target>1.6</maven.compiler.target>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@ -31,6 +33,12 @@
|
|||||||
<version>3.8.1</version>
|
<version>3.8.1</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.guava</groupId>
|
||||||
|
<artifactId>guava</artifactId>
|
||||||
|
<version>21.0</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -41,7 +49,7 @@
|
|||||||
<configuration>
|
<configuration>
|
||||||
<archive>
|
<archive>
|
||||||
<manifest>
|
<manifest>
|
||||||
<mainClass>com.baeldung.Application</mainClass>
|
<mainClass>com.baeldung.BenchmarkRunner</mainClass>
|
||||||
</manifest>
|
</manifest>
|
||||||
</archive>
|
</archive>
|
||||||
</configuration>
|
</configuration>
|
||||||
|
@ -1,14 +0,0 @@
|
|||||||
package com.baeldung;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
import org.openjdk.jmh.Main;
|
|
||||||
import org.openjdk.jmh.runner.RunnerException;
|
|
||||||
|
|
||||||
public class Application {
|
|
||||||
|
|
||||||
public static void main(String[] args) throws RunnerException, IOException {
|
|
||||||
Main.main(args);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,12 +1,48 @@
|
|||||||
package com.baeldung;
|
package com.baeldung;
|
||||||
|
|
||||||
import org.openjdk.jmh.annotations.Benchmark;
|
import com.google.common.hash.HashFunction;
|
||||||
|
import com.google.common.hash.Hasher;
|
||||||
|
import com.google.common.hash.Hashing;
|
||||||
|
import org.openjdk.jmh.annotations.*;
|
||||||
|
|
||||||
|
import java.nio.charset.Charset;
|
||||||
|
|
||||||
public class BenchMark {
|
public class BenchMark {
|
||||||
|
|
||||||
|
@State(Scope.Benchmark)
|
||||||
|
public static class ExecutionPlan {
|
||||||
|
|
||||||
|
@Param({ "100", "200", "300", "500", "1000" })
|
||||||
|
public int iterations;
|
||||||
|
|
||||||
|
public Hasher murmur3;
|
||||||
|
|
||||||
|
public String password = "4v3rys3kur3p455w0rd";
|
||||||
|
|
||||||
|
@Setup(Level.Invocation)
|
||||||
|
public void setUp() {
|
||||||
|
murmur3 = Hashing.murmur3_128().newHasher();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Fork(value = 1, warmups = 1)
|
||||||
@Benchmark
|
@Benchmark
|
||||||
|
@BenchmarkMode(Mode.Throughput)
|
||||||
|
@Warmup(iterations = 5)
|
||||||
|
public void benchMurmur3_128(ExecutionPlan plan) {
|
||||||
|
|
||||||
|
for (int i = plan.iterations; i > 0; i--) {
|
||||||
|
plan.murmur3.putString(plan.password, Charset.defaultCharset());
|
||||||
|
}
|
||||||
|
|
||||||
|
plan.murmur3.hash();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
@Fork(value = 1, warmups = 1)
|
||||||
|
@BenchmarkMode(Mode.Throughput)
|
||||||
public void init() {
|
public void init() {
|
||||||
|
// Do nothing
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
9
jmh/src/main/java/com/baeldung/BenchmarkRunner.java
Normal file
9
jmh/src/main/java/com/baeldung/BenchmarkRunner.java
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
package com.baeldung;
|
||||||
|
|
||||||
|
public class BenchmarkRunner {
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
org.openjdk.jmh.Main.main(args);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,38 +0,0 @@
|
|||||||
package com.baeldung;
|
|
||||||
|
|
||||||
import junit.framework.Test;
|
|
||||||
import junit.framework.TestCase;
|
|
||||||
import junit.framework.TestSuite;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Unit test for simple App.
|
|
||||||
*/
|
|
||||||
public class AppTest
|
|
||||||
extends TestCase
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Create the test case
|
|
||||||
*
|
|
||||||
* @param testName name of the test case
|
|
||||||
*/
|
|
||||||
public AppTest( String testName )
|
|
||||||
{
|
|
||||||
super( testName );
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return the suite of tests being tested
|
|
||||||
*/
|
|
||||||
public static Test suite()
|
|
||||||
{
|
|
||||||
return new TestSuite( AppTest.class );
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Rigourous Test :-)
|
|
||||||
*/
|
|
||||||
public void testApp()
|
|
||||||
{
|
|
||||||
assertTrue( true );
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,3 @@
|
|||||||
|
package com.baeldung.destructuringdeclarations
|
||||||
|
|
||||||
|
data class Person(var id: Int, var name: String, var age: Int)
|
@ -0,0 +1,3 @@
|
|||||||
|
package com.baeldung.destructuringdeclarations
|
||||||
|
|
||||||
|
data class Result(val result: Int, val status: String)
|
@ -0,0 +1,55 @@
|
|||||||
|
package com.baeldung.destructuringdeclarations
|
||||||
|
|
||||||
|
import com.baeldung.destructuringdeclarations.Person
|
||||||
|
import com.baeldung.destructuringdeclarations.Result
|
||||||
|
|
||||||
|
fun main(args: Array<String>) {
|
||||||
|
|
||||||
|
//2.1. Objects
|
||||||
|
val person = Person(1, "Jon Snow", 20)
|
||||||
|
val(id, name, age) = person
|
||||||
|
|
||||||
|
println(id) //1
|
||||||
|
println(name) //Jon Snow
|
||||||
|
println(age) //20
|
||||||
|
|
||||||
|
//The equivalent of line 10
|
||||||
|
/* val id = person.component1();
|
||||||
|
val name = person.component2();
|
||||||
|
val age = person.component3();*/
|
||||||
|
|
||||||
|
//2.2. Functions
|
||||||
|
fun getPersonInfo() = Person(2, "Ned Stark", 45)
|
||||||
|
val(idf, namef, agef) = getPersonInfo()
|
||||||
|
|
||||||
|
fun twoValuesReturn(): Result {
|
||||||
|
|
||||||
|
// needed code
|
||||||
|
|
||||||
|
return Result(1, "success")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now, to use this function:
|
||||||
|
val (result, status) = twoValuesReturn()
|
||||||
|
|
||||||
|
//2.3. Collections and For-loops
|
||||||
|
var map: HashMap<Int, Person> = HashMap()
|
||||||
|
map.put(1, person)
|
||||||
|
|
||||||
|
for((key, value) in map){
|
||||||
|
println("Key: $key, Value: $value")
|
||||||
|
}
|
||||||
|
|
||||||
|
//2.4. Underscore and Destructuring in Lambdas
|
||||||
|
val (_, status2) = twoValuesReturn()
|
||||||
|
|
||||||
|
map.mapValues { entry -> "${entry.value}!" }
|
||||||
|
map.mapValues { (key, value) -> "$value!" }
|
||||||
|
|
||||||
|
//A pair of parameters vs. a destructuring pair
|
||||||
|
/* { a -> ... } // one parameter
|
||||||
|
{ a, b -> ... } // two parameters
|
||||||
|
{ (a, b) -> ... } // a destructured pair
|
||||||
|
{ (a, b), c -> ... } // a destructured pair and another parameter*/
|
||||||
|
|
||||||
|
}
|
@ -24,7 +24,9 @@
|
|||||||
- [Locality-Sensitive Hashing in Java Using Java-LSH](http://www.baeldung.com/locality-sensitive-hashing)
|
- [Locality-Sensitive Hashing in Java Using Java-LSH](http://www.baeldung.com/locality-sensitive-hashing)
|
||||||
- [Apache Commons Collections OrderedMap](http://www.baeldung.com/apache-commons-ordered-map)
|
- [Apache Commons Collections OrderedMap](http://www.baeldung.com/apache-commons-ordered-map)
|
||||||
- [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils)
|
- [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils)
|
||||||
|
- [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing)
|
||||||
|
- [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog)
|
||||||
|
- [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph)
|
||||||
|
|
||||||
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.
|
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.
|
||||||
|
|
||||||
|
@ -7,7 +7,6 @@
|
|||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
<artifactId>libraries</artifactId>
|
<artifactId>libraries</artifactId>
|
||||||
<name>libraries</name>
|
<name>libraries</name>
|
||||||
<build>
|
<build>
|
||||||
@ -71,79 +70,51 @@
|
|||||||
</execution>
|
</execution>
|
||||||
</executions>
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
<!-- Vaadin -->
|
<!-- Neuroph -->
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-war-plugin</artifactId>
|
<artifactId>maven-jar-plugin</artifactId>
|
||||||
<version>3.0.0</version>
|
<version>3.0.2</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
<excludes>
|
||||||
<packagingExcludes>WEB-INF/classes/VAADIN/widgetsets/WEB-INF/**</packagingExcludes>
|
<exclude>**/log4j.properties</exclude>
|
||||||
|
</excludes>
|
||||||
|
<archive>
|
||||||
|
<manifest>
|
||||||
|
<mainClass>com.baeldung.neuroph.NeurophXOR</mainClass>
|
||||||
|
</manifest>
|
||||||
|
</archive>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>com.vaadin</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>vaadin-maven-plugin</artifactId>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
<version>${vaadin.plugin.version}</version>
|
<version>2.18.1</version>
|
||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
|
<id>test</id>
|
||||||
|
<phase>test</phase>
|
||||||
<goals>
|
<goals>
|
||||||
<goal>update-theme</goal>
|
<goal>test</goal>
|
||||||
<goal>update-widgetset</goal>
|
|
||||||
<goal>compile</goal>
|
|
||||||
<goal>compile-theme</goal>
|
|
||||||
</goals>
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<includes>
|
||||||
|
<include>test/java/com/baeldung/neuroph/XORTest.java</include>
|
||||||
|
</includes>
|
||||||
|
</configuration>
|
||||||
</execution>
|
</execution>
|
||||||
</executions>
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<!-- /Neuroph -->
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-clean-plugin</artifactId>
|
|
||||||
<version>3.0.0</version>
|
|
||||||
<configuration>
|
|
||||||
<filesets>
|
|
||||||
<fileset>
|
|
||||||
<directory>src/main/webapp/VAADIN/themes</directory>
|
|
||||||
<includes>
|
|
||||||
<include>**/styles.css</include>
|
|
||||||
<include>**/styles.scss.cache</include>
|
|
||||||
</includes>
|
|
||||||
</fileset>
|
|
||||||
</filesets>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.eclipse.jetty</groupId>
|
|
||||||
<artifactId>jetty-maven-plugin</artifactId>
|
|
||||||
<version>${jetty.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<scanIntervalSeconds>2</scanIntervalSeconds>
|
|
||||||
<skipTests>true</skipTests>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
<!-- /Vaadin -->
|
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
<!-- Vaadin -->
|
|
||||||
<repositories>
|
|
||||||
<repository>
|
|
||||||
<id>vaadin-addons</id>
|
|
||||||
<url>http://maven.vaadin.com/vaadin-addons</url>
|
|
||||||
</repository>
|
|
||||||
</repositories>
|
|
||||||
<dependencyManagement>
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
<!-- https://mvnrepository.com/artifact/org.beykery/neuroph/2.92 -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.vaadin</groupId>
|
<groupId>org.beykery</groupId>
|
||||||
<artifactId>vaadin-bom</artifactId>
|
<artifactId>neuroph</artifactId>
|
||||||
<version>${vaadin.version}</version>
|
<version>${neuroph.version}</version>
|
||||||
<type>pom</type>
|
|
||||||
<scope>import</scope>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
|
||||||
</dependencyManagement>
|
|
||||||
<!-- /Vaadin -->
|
|
||||||
<dependencies>
|
|
||||||
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
|
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>cglib</groupId>
|
<groupId>cglib</groupId>
|
||||||
@ -227,6 +198,11 @@
|
|||||||
<artifactId>commons-io</artifactId>
|
<artifactId>commons-io</artifactId>
|
||||||
<version>${commons.io.version}</version>
|
<version>${commons.io.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-chain</groupId>
|
||||||
|
<artifactId>commons-chain</artifactId>
|
||||||
|
<version>${commons-chain.version}</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-dbutils</groupId>
|
<groupId>commons-dbutils</groupId>
|
||||||
<artifactId>commons-dbutils</artifactId>
|
<artifactId>commons-dbutils</artifactId>
|
||||||
@ -392,7 +368,6 @@
|
|||||||
<artifactId>quartz</artifactId>
|
<artifactId>quartz</artifactId>
|
||||||
<version>2.3.0</version>
|
<version>2.3.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>one.util</groupId>
|
<groupId>one.util</groupId>
|
||||||
<artifactId>streamex</artifactId>
|
<artifactId>streamex</artifactId>
|
||||||
@ -458,68 +433,6 @@
|
|||||||
<version>${org.hamcrest.java-hamcrest.version}</version>
|
<version>${org.hamcrest.java-hamcrest.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- Vaadin -->
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.vaadin</groupId>
|
|
||||||
<artifactId>vaadin-server</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.vaadin</groupId>
|
|
||||||
<artifactId>vaadin-client-compiled</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.vaadin</groupId>
|
|
||||||
<artifactId>vaadin-themes</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.seleniumhq.selenium</groupId>
|
|
||||||
<artifactId>selenium-java</artifactId>
|
|
||||||
<scope>test</scope>
|
|
||||||
<version>3.4.0</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.seleniumhq.selenium</groupId>
|
|
||||||
<artifactId>htmlunit-driver</artifactId>
|
|
||||||
<version>2.27</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.eclipse.jetty.websocket</groupId>
|
|
||||||
<artifactId>websocket-server</artifactId>
|
|
||||||
<version>${jetty.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.eclipse.jetty.websocket</groupId>
|
|
||||||
<artifactId>websocket-client</artifactId>
|
|
||||||
<version>${jetty.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.eclipse.jetty.websocket</groupId>
|
|
||||||
<artifactId>websocket-api</artifactId>
|
|
||||||
<version>${jetty.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.eclipse.jetty.websocket</groupId>
|
|
||||||
<artifactId>websocket-common</artifactId>
|
|
||||||
<version>${jetty.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.eclipse.jetty</groupId>
|
|
||||||
<artifactId>jetty-continuation</artifactId>
|
|
||||||
<version>${jetty.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.eclipse.jetty</groupId>
|
|
||||||
<artifactId>jetty-util</artifactId>
|
|
||||||
<version>${jetty.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.seleniumhq.selenium</groupId>
|
|
||||||
<artifactId>selenium-api</artifactId>
|
|
||||||
<version>3.4.0</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
<type>jar</type>
|
|
||||||
</dependency>
|
|
||||||
<!-- /Vaadin -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>net.agkn</groupId>
|
<groupId>net.agkn</groupId>
|
||||||
<artifactId>hll</artifactId>
|
<artifactId>hll</artifactId>
|
||||||
@ -535,6 +448,16 @@
|
|||||||
<artifactId>byte-buddy-agent</artifactId>
|
<artifactId>byte-buddy-agent</artifactId>
|
||||||
<version>${bytebuddy.version}</version>
|
<version>${bytebuddy.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>net.bytebuddy</groupId>
|
||||||
|
<artifactId>byte-buddy</artifactId>
|
||||||
|
<version>${bytebuddy.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>net.bytebuddy</groupId>
|
||||||
|
<artifactId>byte-buddy-agent</artifactId>
|
||||||
|
<version>${bytebuddy.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
<properties>
|
<properties>
|
||||||
<multiverse.version>0.7.0</multiverse.version>
|
<multiverse.version>0.7.0</multiverse.version>
|
||||||
@ -542,6 +465,7 @@
|
|||||||
<commons-lang.version>3.5</commons-lang.version>
|
<commons-lang.version>3.5</commons-lang.version>
|
||||||
<commons-text.version>1.1</commons-text.version>
|
<commons-text.version>1.1</commons-text.version>
|
||||||
<commons-beanutils.version>1.9.3</commons-beanutils.version>
|
<commons-beanutils.version>1.9.3</commons-beanutils.version>
|
||||||
|
<commons-chain.version>1.2</commons-chain.version>
|
||||||
<jasypt.version>1.9.2</jasypt.version>
|
<jasypt.version>1.9.2</jasypt.version>
|
||||||
<javatuples.version>1.2</javatuples.version>
|
<javatuples.version>1.2</javatuples.version>
|
||||||
<javaassist.version>3.21.0-GA</javaassist.version>
|
<javaassist.version>3.21.0-GA</javaassist.version>
|
||||||
@ -558,6 +482,7 @@
|
|||||||
<commons.io.version>2.5</commons.io.version>
|
<commons.io.version>2.5</commons.io.version>
|
||||||
<flink.version>1.2.0</flink.version>
|
<flink.version>1.2.0</flink.version>
|
||||||
<jackson.version>2.8.5</jackson.version>
|
<jackson.version>2.8.5</jackson.version>
|
||||||
|
<neuroph.version>2.92</neuroph.version>
|
||||||
<serenity.version>1.4.0</serenity.version>
|
<serenity.version>1.4.0</serenity.version>
|
||||||
<serenity.jbehave.version>1.24.0</serenity.jbehave.version>
|
<serenity.jbehave.version>1.24.0</serenity.jbehave.version>
|
||||||
<serenity.jira.version>1.1.3-rc.5</serenity.jira.version>
|
<serenity.jira.version>1.1.3-rc.5</serenity.jira.version>
|
||||||
@ -570,54 +495,7 @@
|
|||||||
<pact.version>3.5.0</pact.version>
|
<pact.version>3.5.0</pact.version>
|
||||||
<awaitility.version>3.0.0</awaitility.version>
|
<awaitility.version>3.0.0</awaitility.version>
|
||||||
<org.hamcrest.java-hamcrest.version>2.0.0.0</org.hamcrest.java-hamcrest.version>
|
<org.hamcrest.java-hamcrest.version>2.0.0.0</org.hamcrest.java-hamcrest.version>
|
||||||
<!-- Vaadin -->
|
|
||||||
<vaadin.version>7.7.10</vaadin.version>
|
|
||||||
<vaadin.plugin.version>8.0.6</vaadin.plugin.version>
|
|
||||||
<vaadin.theme>mytheme</vaadin.theme>
|
|
||||||
<!-- /Vaadin -->
|
|
||||||
<hll.version>1.6.0</hll.version>
|
<hll.version>1.6.0</hll.version>
|
||||||
<bytebuddy.version>1.7.1</bytebuddy.version>
|
<bytebuddy.version>1.7.1</bytebuddy.version>
|
||||||
</properties>
|
</properties>
|
||||||
<profiles>
|
|
||||||
<!-- Vaadin -->
|
|
||||||
<profile>
|
|
||||||
<id>vaadin-prerelease</id>
|
|
||||||
<activation>
|
|
||||||
<activeByDefault>false</activeByDefault>
|
|
||||||
</activation>
|
|
||||||
<repositories>
|
|
||||||
<repository>
|
|
||||||
<id>vaadin-prereleases</id>
|
|
||||||
<url>http://maven.vaadin.com/vaadin-prereleases</url>
|
|
||||||
</repository>
|
|
||||||
<repository>
|
|
||||||
<id>vaadin-snapshots</id>
|
|
||||||
<url>https://oss.sonatype.org/content/repositories/vaadin-snapshots/</url>
|
|
||||||
<releases>
|
|
||||||
<enabled>false</enabled>
|
|
||||||
</releases>
|
|
||||||
<snapshots>
|
|
||||||
<enabled>true</enabled>
|
|
||||||
</snapshots>
|
|
||||||
</repository>
|
|
||||||
</repositories>
|
|
||||||
<pluginRepositories>
|
|
||||||
<pluginRepository>
|
|
||||||
<id>vaadin-prereleases</id>
|
|
||||||
<url>http://maven.vaadin.com/vaadin-prereleases</url>
|
|
||||||
</pluginRepository>
|
|
||||||
<pluginRepository>
|
|
||||||
<id>vaadin-snapshots</id>
|
|
||||||
<url>https://oss.sonatype.org/content/repositories/vaadin-snapshots/</url>
|
|
||||||
<releases>
|
|
||||||
<enabled>false</enabled>
|
|
||||||
</releases>
|
|
||||||
<snapshots>
|
|
||||||
<enabled>true</enabled>
|
|
||||||
</snapshots>
|
|
||||||
</pluginRepository>
|
|
||||||
</pluginRepositories>
|
|
||||||
</profile>
|
|
||||||
<!-- Vaadin -->
|
|
||||||
</profiles>
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.commons.chain;
|
||||||
|
|
||||||
|
import org.apache.commons.chain.Command;
|
||||||
|
import org.apache.commons.chain.Context;
|
||||||
|
|
||||||
|
import static com.baeldung.commons.chain.AtmConstants.AMOUNT_LEFT_TO_BE_WITHDRAWN;
|
||||||
|
|
||||||
|
public abstract class AbstractDenominationDispenser implements Command {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean execute(Context context) throws Exception {
|
||||||
|
int amountLeftToBeWithdrawn = (int) context.get(AMOUNT_LEFT_TO_BE_WITHDRAWN);
|
||||||
|
if (amountLeftToBeWithdrawn >= getDenominationValue()) {
|
||||||
|
context.put(getDenominationString(), amountLeftToBeWithdrawn / getDenominationValue());
|
||||||
|
context.put(AMOUNT_LEFT_TO_BE_WITHDRAWN, amountLeftToBeWithdrawn % getDenominationValue());
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected abstract String getDenominationString();
|
||||||
|
|
||||||
|
protected abstract int getDenominationValue();
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.commons.chain;
|
||||||
|
|
||||||
|
import org.apache.commons.chain.impl.CatalogBase;
|
||||||
|
|
||||||
|
import static com.baeldung.commons.chain.AtmConstants.ATM_WITHDRAWAL_CHAIN;
|
||||||
|
|
||||||
|
public class AtmCatalog extends CatalogBase {
|
||||||
|
|
||||||
|
public AtmCatalog() {
|
||||||
|
super();
|
||||||
|
addCommand(ATM_WITHDRAWAL_CHAIN, new AtmWithdrawalChain());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.commons.chain;
|
||||||
|
|
||||||
|
public class AtmConstants {
|
||||||
|
public static final String TOTAL_AMOUNT_TO_BE_WITHDRAWN = "totalAmountToBeWithdrawn";
|
||||||
|
public static final String AMOUNT_LEFT_TO_BE_WITHDRAWN = "amountLeftToBeWithdrawn";
|
||||||
|
public static final String NO_OF_HUNDREDS_DISPENSED = "noOfHundredsDispensed";
|
||||||
|
public static final String NO_OF_FIFTIES_DISPENSED = "noOfFiftiesDispensed";
|
||||||
|
public static final String NO_OF_TENS_DISPENSED = "noOfTensDispensed";
|
||||||
|
public static final String ATM_WITHDRAWAL_CHAIN = "atmWithdrawalChain";
|
||||||
|
}
|
@ -0,0 +1,52 @@
|
|||||||
|
package com.baeldung.commons.chain;
|
||||||
|
|
||||||
|
import org.apache.commons.chain.impl.ContextBase;
|
||||||
|
|
||||||
|
public class AtmRequestContext extends ContextBase {
|
||||||
|
|
||||||
|
int totalAmountToBeWithdrawn;
|
||||||
|
int noOfHundredsDispensed;
|
||||||
|
int noOfFiftiesDispensed;
|
||||||
|
int noOfTensDispensed;
|
||||||
|
int amountLeftToBeWithdrawn;
|
||||||
|
|
||||||
|
public int getTotalAmountToBeWithdrawn() {
|
||||||
|
return totalAmountToBeWithdrawn;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTotalAmountToBeWithdrawn(int totalAmountToBeWithdrawn) {
|
||||||
|
this.totalAmountToBeWithdrawn = totalAmountToBeWithdrawn;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getNoOfHundredsDispensed() {
|
||||||
|
return noOfHundredsDispensed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setNoOfHundredsDispensed(int noOfHundredsDispensed) {
|
||||||
|
this.noOfHundredsDispensed = noOfHundredsDispensed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getNoOfFiftiesDispensed() {
|
||||||
|
return noOfFiftiesDispensed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setNoOfFiftiesDispensed(int noOfFiftiesDispensed) {
|
||||||
|
this.noOfFiftiesDispensed = noOfFiftiesDispensed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getNoOfTensDispensed() {
|
||||||
|
return noOfTensDispensed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setNoOfTensDispensed(int noOfTensDispensed) {
|
||||||
|
this.noOfTensDispensed = noOfTensDispensed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getAmountLeftToBeWithdrawn() {
|
||||||
|
return amountLeftToBeWithdrawn;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAmountLeftToBeWithdrawn(int amountLeftToBeWithdrawn) {
|
||||||
|
this.amountLeftToBeWithdrawn = amountLeftToBeWithdrawn;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.commons.chain;
|
||||||
|
|
||||||
|
import org.apache.commons.chain.impl.ChainBase;
|
||||||
|
|
||||||
|
public class AtmWithdrawalChain extends ChainBase {
|
||||||
|
|
||||||
|
public AtmWithdrawalChain() {
|
||||||
|
super();
|
||||||
|
addCommand(new HundredDenominationDispenser());
|
||||||
|
addCommand(new FiftyDenominationDispenser());
|
||||||
|
addCommand(new TenDenominationDispenser());
|
||||||
|
addCommand(new AuditFilter());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.commons.chain;
|
||||||
|
|
||||||
|
import org.apache.commons.chain.Context;
|
||||||
|
import org.apache.commons.chain.Filter;
|
||||||
|
|
||||||
|
public class AuditFilter implements Filter {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean postprocess(Context context, Exception exception) {
|
||||||
|
// Send notification to customer & bank.
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean execute(Context context) throws Exception {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.commons.chain;
|
||||||
|
|
||||||
|
import static com.baeldung.commons.chain.AtmConstants.NO_OF_FIFTIES_DISPENSED;
|
||||||
|
|
||||||
|
public class FiftyDenominationDispenser extends AbstractDenominationDispenser {
|
||||||
|
@Override
|
||||||
|
protected String getDenominationString() {
|
||||||
|
return NO_OF_FIFTIES_DISPENSED;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected int getDenominationValue() {
|
||||||
|
return 50;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.commons.chain;
|
||||||
|
|
||||||
|
import static com.baeldung.commons.chain.AtmConstants.NO_OF_HUNDREDS_DISPENSED;
|
||||||
|
|
||||||
|
public class HundredDenominationDispenser extends AbstractDenominationDispenser {
|
||||||
|
@Override
|
||||||
|
protected String getDenominationString() {
|
||||||
|
return NO_OF_HUNDREDS_DISPENSED;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected int getDenominationValue() {
|
||||||
|
return 100;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.commons.chain;
|
||||||
|
|
||||||
|
import static com.baeldung.commons.chain.AtmConstants.NO_OF_TENS_DISPENSED;
|
||||||
|
|
||||||
|
public class TenDenominationDispenser extends AbstractDenominationDispenser {
|
||||||
|
@Override
|
||||||
|
protected String getDenominationString() {
|
||||||
|
return NO_OF_TENS_DISPENSED;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected int getDenominationValue() {
|
||||||
|
return 10;
|
||||||
|
}
|
||||||
|
}
|
73
libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java
Normal file
73
libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
package com.baeldung.neuroph;
|
||||||
|
|
||||||
|
import org.neuroph.core.Layer;
|
||||||
|
import org.neuroph.core.NeuralNetwork;
|
||||||
|
import org.neuroph.core.Neuron;
|
||||||
|
import org.neuroph.core.data.DataSet;
|
||||||
|
import org.neuroph.core.data.DataSetRow;
|
||||||
|
import org.neuroph.nnet.learning.BackPropagation;
|
||||||
|
import org.neuroph.util.ConnectionFactory;
|
||||||
|
import org.neuroph.util.NeuralNetworkType;
|
||||||
|
|
||||||
|
public class NeurophXOR {
|
||||||
|
|
||||||
|
public static NeuralNetwork assembleNeuralNetwork() {
|
||||||
|
|
||||||
|
Layer inputLayer = new Layer();
|
||||||
|
inputLayer.addNeuron(new Neuron());
|
||||||
|
inputLayer.addNeuron(new Neuron());
|
||||||
|
|
||||||
|
Layer hiddenLayerOne = new Layer();
|
||||||
|
hiddenLayerOne.addNeuron(new Neuron());
|
||||||
|
hiddenLayerOne.addNeuron(new Neuron());
|
||||||
|
hiddenLayerOne.addNeuron(new Neuron());
|
||||||
|
hiddenLayerOne.addNeuron(new Neuron());
|
||||||
|
|
||||||
|
Layer hiddenLayerTwo = new Layer();
|
||||||
|
hiddenLayerTwo.addNeuron(new Neuron());
|
||||||
|
hiddenLayerTwo.addNeuron(new Neuron());
|
||||||
|
hiddenLayerTwo.addNeuron(new Neuron());
|
||||||
|
hiddenLayerTwo.addNeuron(new Neuron());
|
||||||
|
|
||||||
|
Layer outputLayer = new Layer();
|
||||||
|
outputLayer.addNeuron(new Neuron());
|
||||||
|
|
||||||
|
NeuralNetwork ann = new NeuralNetwork();
|
||||||
|
|
||||||
|
ann.addLayer(0, inputLayer);
|
||||||
|
ann.addLayer(1, hiddenLayerOne);
|
||||||
|
ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(1));
|
||||||
|
ann.addLayer(2, hiddenLayerTwo);
|
||||||
|
ConnectionFactory.fullConnect(ann.getLayerAt(1), ann.getLayerAt(2));
|
||||||
|
ann.addLayer(3, outputLayer);
|
||||||
|
ConnectionFactory.fullConnect(ann.getLayerAt(2), ann.getLayerAt(3));
|
||||||
|
ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(ann.getLayersCount()-1), false);
|
||||||
|
|
||||||
|
ann.setInputNeurons(inputLayer.getNeurons());
|
||||||
|
ann.setOutputNeurons(outputLayer.getNeurons());
|
||||||
|
|
||||||
|
ann.setNetworkType(NeuralNetworkType.MULTI_LAYER_PERCEPTRON);
|
||||||
|
return ann;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static NeuralNetwork trainNeuralNetwork(NeuralNetwork ann) {
|
||||||
|
int inputSize = 2;
|
||||||
|
int outputSize = 1;
|
||||||
|
DataSet ds = new DataSet(inputSize, outputSize);
|
||||||
|
|
||||||
|
DataSetRow rOne = new DataSetRow(new double[] {0, 1}, new double[] {1});
|
||||||
|
ds.addRow(rOne);
|
||||||
|
DataSetRow rTwo = new DataSetRow(new double[] {1, 1}, new double[] {0});
|
||||||
|
ds.addRow(rTwo);
|
||||||
|
DataSetRow rThree = new DataSetRow(new double[] {0, 0}, new double[] {0});
|
||||||
|
ds.addRow(rThree);
|
||||||
|
DataSetRow rFour = new DataSetRow(new double[] {1, 0}, new double[] {1});
|
||||||
|
ds.addRow(rFour);
|
||||||
|
|
||||||
|
BackPropagation backPropagation = new BackPropagation();
|
||||||
|
backPropagation.setMaxIterations(1000);
|
||||||
|
|
||||||
|
ann.learn(ds, backPropagation);
|
||||||
|
return ann;
|
||||||
|
}
|
||||||
|
}
|
@ -1,7 +0,0 @@
|
|||||||
/* This file is automatically managed and will be overwritten from time to time. */
|
|
||||||
/* Do not manually edit this file. */
|
|
||||||
|
|
||||||
/* Import and include this mixin into your project theme to include the addon themes */
|
|
||||||
@mixin addons {
|
|
||||||
}
|
|
||||||
|
|
@ -0,0 +1,37 @@
|
|||||||
|
package com.baeldung.commons.chain;
|
||||||
|
|
||||||
|
import org.apache.commons.chain.Catalog;
|
||||||
|
import org.apache.commons.chain.Command;
|
||||||
|
import org.apache.commons.chain.Context;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static com.baeldung.commons.chain.AtmConstants.*;
|
||||||
|
|
||||||
|
public class AtmChainTest {
|
||||||
|
|
||||||
|
public static final int EXPECTED_TOTAL_AMOUNT_TO_BE_WITHDRAWN = 460;
|
||||||
|
public static final int EXPECTED_AMOUNT_LEFT_TO_BE_WITHDRAWN = 0;
|
||||||
|
public static final int EXPECTED_NO_OF_HUNDREDS_DISPENSED = 4;
|
||||||
|
public static final int EXPECTED_NO_OF_FIFTIES_DISPENSED = 1;
|
||||||
|
public static final int EXPECTED_NO_OF_TENS_DISPENSED = 1;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInputsToContext_whenAppliedChain_thenExpectedContext() {
|
||||||
|
Context context = new AtmRequestContext();
|
||||||
|
context.put(TOTAL_AMOUNT_TO_BE_WITHDRAWN, 460);
|
||||||
|
context.put(AMOUNT_LEFT_TO_BE_WITHDRAWN, 460);
|
||||||
|
Catalog catalog = new AtmCatalog();
|
||||||
|
Command atmWithdrawalChain = catalog.getCommand(ATM_WITHDRAWAL_CHAIN);
|
||||||
|
try {
|
||||||
|
atmWithdrawalChain.execute(context);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
Assert.assertEquals(EXPECTED_TOTAL_AMOUNT_TO_BE_WITHDRAWN, (int) context.get(TOTAL_AMOUNT_TO_BE_WITHDRAWN));
|
||||||
|
Assert.assertEquals(EXPECTED_AMOUNT_LEFT_TO_BE_WITHDRAWN, (int) context.get(AMOUNT_LEFT_TO_BE_WITHDRAWN));
|
||||||
|
Assert.assertEquals(EXPECTED_NO_OF_HUNDREDS_DISPENSED, (int) context.get(NO_OF_HUNDREDS_DISPENSED));
|
||||||
|
Assert.assertEquals(EXPECTED_NO_OF_FIFTIES_DISPENSED, (int) context.get(NO_OF_FIFTIES_DISPENSED));
|
||||||
|
Assert.assertEquals(EXPECTED_NO_OF_TENS_DISPENSED, (int) context.get(NO_OF_TENS_DISPENSED));
|
||||||
|
}
|
||||||
|
}
|
@ -4,14 +4,19 @@ import org.apache.commons.collections4.MapIterator;
|
|||||||
import org.apache.commons.collections4.MapUtils;
|
import org.apache.commons.collections4.MapUtils;
|
||||||
import org.apache.commons.collections4.PredicateUtils;
|
import org.apache.commons.collections4.PredicateUtils;
|
||||||
import org.apache.commons.collections4.TransformerUtils;
|
import org.apache.commons.collections4.TransformerUtils;
|
||||||
|
import org.assertj.core.api.Assertions;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.io.ByteArrayOutputStream;
|
import java.io.ByteArrayOutputStream;
|
||||||
import java.io.PrintStream;
|
import java.io.PrintStream;
|
||||||
|
import java.util.Collection;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.not;
|
||||||
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
import static org.hamcrest.Matchers.is;
|
import static org.hamcrest.Matchers.is;
|
||||||
import static org.hamcrest.collection.IsMapContaining.hasEntry;
|
import static org.hamcrest.collection.IsMapContaining.hasEntry;
|
||||||
import static org.hamcrest.collection.IsMapWithSize.aMapWithSize;
|
import static org.hamcrest.collection.IsMapWithSize.aMapWithSize;
|
||||||
@ -63,19 +68,7 @@ public class MapUtilsTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenVerbosePrintMap_thenMustPrintFormattedMap() {
|
public void whenVerbosePrintMap_thenMustPrintFormattedMap() {
|
||||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
MapUtils.verbosePrint(System.out, "Optional Label", this.colorMap);
|
||||||
PrintStream outPrint = new PrintStream(out);
|
|
||||||
|
|
||||||
outPrint.println("Optional Label = ");
|
|
||||||
outPrint.println("{");
|
|
||||||
outPrint.println(" RED = #FF0000");
|
|
||||||
outPrint.println(" BLUE = #0000FF");
|
|
||||||
outPrint.println(" GREEN = #00FF00");
|
|
||||||
outPrint.println("}");
|
|
||||||
|
|
||||||
out.reset();
|
|
||||||
|
|
||||||
MapUtils.verbosePrint(outPrint, "Optional Label", this.colorMap);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -97,19 +90,12 @@ public class MapUtilsTest {
|
|||||||
@Test
|
@Test
|
||||||
public void whenInvertMap_thenMustReturnInvertedMap() {
|
public void whenInvertMap_thenMustReturnInvertedMap() {
|
||||||
Map<String, String> invColorMap = MapUtils.invertMap(this.colorMap);
|
Map<String, String> invColorMap = MapUtils.invertMap(this.colorMap);
|
||||||
assertEquals(this.colorMap.size(), invColorMap.size());
|
|
||||||
|
|
||||||
MapIterator<String, String> itColorMap
|
int size = invColorMap.size();
|
||||||
= MapUtils.iterableMap(this.colorMap).mapIterator();
|
Assertions.assertThat(invColorMap)
|
||||||
|
.hasSameSizeAs(colorMap)
|
||||||
while (itColorMap.hasNext()) {
|
.containsKeys(this.colorMap.values().toArray(new String[size]))
|
||||||
String colorMapKey = itColorMap.next();
|
.containsValues(this.colorMap.keySet().toArray(new String[size]));
|
||||||
String colorMapValue = itColorMap.getValue();
|
|
||||||
|
|
||||||
String invColorMapValue = MapUtils.getString(invColorMap, colorMapValue);
|
|
||||||
|
|
||||||
assertTrue(invColorMapValue.equals(colorMapKey));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test(expected = IllegalArgumentException.class)
|
@Test(expected = IllegalArgumentException.class)
|
||||||
|
@ -4,6 +4,7 @@ package com.baeldung.hll;
|
|||||||
import com.google.common.hash.HashFunction;
|
import com.google.common.hash.HashFunction;
|
||||||
import com.google.common.hash.Hashing;
|
import com.google.common.hash.Hashing;
|
||||||
import net.agkn.hll.HLL;
|
import net.agkn.hll.HLL;
|
||||||
|
import org.assertj.core.data.Offset;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.stream.LongStream;
|
import java.util.stream.LongStream;
|
||||||
@ -15,8 +16,8 @@ public class HLLUnitTest {
|
|||||||
@Test
|
@Test
|
||||||
public void givenHLL_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinality() {
|
public void givenHLL_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinality() {
|
||||||
//given
|
//given
|
||||||
int numberOfElements = 100_000_000;
|
long numberOfElements = 100_000_000;
|
||||||
int toleratedDifference = 1_000_000;
|
long toleratedDifference = 1_000_000;
|
||||||
HashFunction hashFunction = Hashing.murmur3_128();
|
HashFunction hashFunction = Hashing.murmur3_128();
|
||||||
HLL hll = new HLL(14, 5);
|
HLL hll = new HLL(14, 5);
|
||||||
|
|
||||||
@ -29,14 +30,14 @@ public class HLLUnitTest {
|
|||||||
|
|
||||||
//then
|
//then
|
||||||
long cardinality = hll.cardinality();
|
long cardinality = hll.cardinality();
|
||||||
assertThat(isSimilarTo(cardinality, numberOfElements, toleratedDifference)).isTrue();
|
assertThat(cardinality).isCloseTo(numberOfElements, Offset.offset(toleratedDifference));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTwoHLLs_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinalityForUnionOfHLLs() {
|
public void givenTwoHLLs_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinalityForUnionOfHLLs() {
|
||||||
//given
|
//given
|
||||||
int numberOfElements = 100_000_000;
|
long numberOfElements = 100_000_000;
|
||||||
int toleratedDifference = 1_000_000;
|
long toleratedDifference = 1_000_000;
|
||||||
HashFunction hashFunction = Hashing.murmur3_128();
|
HashFunction hashFunction = Hashing.murmur3_128();
|
||||||
HLL firstHll = new HLL(15, 5);
|
HLL firstHll = new HLL(15, 5);
|
||||||
HLL secondHLL = new HLL(15, 5);
|
HLL secondHLL = new HLL(15, 5);
|
||||||
@ -57,12 +58,6 @@ public class HLLUnitTest {
|
|||||||
//then
|
//then
|
||||||
firstHll.union(secondHLL);
|
firstHll.union(secondHLL);
|
||||||
long cardinality = firstHll.cardinality();
|
long cardinality = firstHll.cardinality();
|
||||||
assertThat(isSimilarTo(cardinality, numberOfElements * 2,
|
assertThat(cardinality).isCloseTo(numberOfElements * 2, Offset.offset(toleratedDifference * 2));
|
||||||
toleratedDifference * 2)).isTrue();
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isSimilarTo(long cardinality, int numberOfElements, int maxToleratedDifference) {
|
|
||||||
System.out.println(cardinality);
|
|
||||||
return Math.abs(cardinality - numberOfElements) <= maxToleratedDifference;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
50
libraries/src/test/java/com/baeldung/neuroph/XORTest.java
Normal file
50
libraries/src/test/java/com/baeldung/neuroph/XORTest.java
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
package com.baeldung.neuroph;
|
||||||
|
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.neuroph.core.NeuralNetwork;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class XORTest {
|
||||||
|
private NeuralNetwork ann = null;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void annInit() {
|
||||||
|
ann = NeurophXOR.trainNeuralNetwork(NeurophXOR.assembleNeuralNetwork());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void leftDisjunctTest() {
|
||||||
|
ann.setInput(0, 1);
|
||||||
|
ann.calculate();
|
||||||
|
assertEquals(ann.getOutput()[0], 1.0,0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void rightDisjunctTest() {
|
||||||
|
ann.setInput(1, 0);
|
||||||
|
ann.calculate();
|
||||||
|
assertEquals(ann.getOutput()[0], 1.0,0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void bothFalseConjunctTest() {
|
||||||
|
ann.setInput(0, 0);
|
||||||
|
ann.calculate();
|
||||||
|
assertEquals(ann.getOutput()[0], 0.0,0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void bothTrueConjunctTest() {
|
||||||
|
ann.setInput(1, 1);
|
||||||
|
ann.calculate();
|
||||||
|
assertEquals(ann.getOutput()[0], 0.0,0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void annClose() {
|
||||||
|
ann = null;
|
||||||
|
}
|
||||||
|
}
|
54
mockserver/pom.xml
Normal file
54
mockserver/pom.xml
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>mockserver</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
<properties>
|
||||||
|
<mock-sever-netty-version>3.10.8</mock-sever-netty-version>
|
||||||
|
<apche-http-version>4.4.1</apche-http-version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.mock-server</groupId>
|
||||||
|
<artifactId>mockserver-netty</artifactId>
|
||||||
|
<version>${mock-sever-netty-version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.mock-server</groupId>
|
||||||
|
<artifactId>mockserver-client-java</artifactId>
|
||||||
|
<version>${mock-sever-netty-version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.httpcomponents</groupId>
|
||||||
|
<artifactId>httpclient</artifactId>
|
||||||
|
<version>${apche-http-version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.httpcomponents</groupId>
|
||||||
|
<artifactId>httpcore</artifactId>
|
||||||
|
<version>${apche-http-version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>2.20</version>
|
||||||
|
<configuration>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/**LiveTest.java</exclude>
|
||||||
|
</excludes>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
|
||||||
|
</build>
|
||||||
|
</project>
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.mock.server;
|
||||||
|
|
||||||
|
import org.mockserver.mock.action.ExpectationCallback;
|
||||||
|
import org.mockserver.model.HttpRequest;
|
||||||
|
import org.mockserver.model.HttpResponse;
|
||||||
|
|
||||||
|
import static org.mockserver.model.HttpResponse.notFoundResponse;
|
||||||
|
import static org.mockserver.model.HttpResponse.response;
|
||||||
|
|
||||||
|
|
||||||
|
public class ExpectationCallbackHandler implements ExpectationCallback {
|
||||||
|
|
||||||
|
public HttpResponse handle(HttpRequest httpRequest) {
|
||||||
|
if (httpRequest.getPath().getValue().endsWith("/callback")) {
|
||||||
|
return httpResponse;
|
||||||
|
} else {
|
||||||
|
return notFoundResponse();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static HttpResponse httpResponse = response()
|
||||||
|
.withStatusCode(200);
|
||||||
|
}
|
@ -0,0 +1,176 @@
|
|||||||
|
package com.baeldung.mock.server;
|
||||||
|
|
||||||
|
import org.apache.http.client.HttpClient;
|
||||||
|
import org.apache.http.client.methods.HttpGet;
|
||||||
|
import org.apache.http.client.methods.HttpPost;
|
||||||
|
import org.apache.http.entity.StringEntity;
|
||||||
|
import org.apache.http.impl.client.HttpClientBuilder;
|
||||||
|
import org.junit.*;
|
||||||
|
import org.mockserver.client.server.MockServerClient;
|
||||||
|
import org.mockserver.integration.ClientAndProxy;
|
||||||
|
import org.mockserver.integration.ClientAndServer;
|
||||||
|
import org.mockserver.model.Header;
|
||||||
|
import org.mockserver.model.HttpForward;
|
||||||
|
import org.mockserver.verify.VerificationTimes;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import static junit.framework.Assert.assertEquals;
|
||||||
|
import static org.mockserver.integration.ClientAndProxy.startClientAndProxy;
|
||||||
|
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
|
||||||
|
import static org.mockserver.matchers.Times.exactly;
|
||||||
|
import static org.mockserver.model.HttpClassCallback.callback;
|
||||||
|
import static org.mockserver.model.HttpForward.forward;
|
||||||
|
import static org.mockserver.model.HttpRequest.request;
|
||||||
|
import static org.mockserver.model.HttpResponse.response;
|
||||||
|
import static org.mockserver.model.StringBody.exact;
|
||||||
|
|
||||||
|
public class MockServerLiveTest {
|
||||||
|
|
||||||
|
private static ClientAndProxy proxy;
|
||||||
|
private static ClientAndServer mockServer;
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void startProxy() {
|
||||||
|
mockServer = startClientAndServer(1080);
|
||||||
|
proxy = startClientAndProxy(1090);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPostRequestMockServer_thenServerReceived(){
|
||||||
|
createExpectationForInvalidAuth();
|
||||||
|
hitTheServerWithPostRequest();
|
||||||
|
verifyPostRequest();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPostRequestForInvalidAuth_then401Received(){
|
||||||
|
createExpectationForInvalidAuth();
|
||||||
|
org.apache.http.HttpResponse response = hitTheServerWithPostRequest();
|
||||||
|
assertEquals(401, response.getStatusLine().getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGetRequest_ThenForward(){
|
||||||
|
createExpectationForForward();
|
||||||
|
hitTheServerWithGetRequest("index.html");
|
||||||
|
verifyGetRequest();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCallbackRequest_ThenCallbackMethodCalled(){
|
||||||
|
createExpectationForCallBack();
|
||||||
|
org.apache.http.HttpResponse response= hitTheServerWithGetRequest("/callback");
|
||||||
|
assertEquals(200,response.getStatusLine().getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void verifyPostRequest() {
|
||||||
|
new MockServerClient("localhost", 1080).verify(
|
||||||
|
request()
|
||||||
|
.withMethod("POST")
|
||||||
|
.withPath("/validate")
|
||||||
|
.withBody(exact("{username: 'foo', password: 'bar'}")),
|
||||||
|
VerificationTimes.exactly(1)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
private void verifyGetRequest() {
|
||||||
|
new MockServerClient("localhost", 1080).verify(
|
||||||
|
request()
|
||||||
|
.withMethod("GET")
|
||||||
|
.withPath("/index.html"),
|
||||||
|
VerificationTimes.exactly(1)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private org.apache.http.HttpResponse hitTheServerWithPostRequest() {
|
||||||
|
String url = "http://127.0.0.1:1080/validate";
|
||||||
|
HttpClient client = HttpClientBuilder.create().build();
|
||||||
|
HttpPost post = new HttpPost(url);
|
||||||
|
post.setHeader("Content-type", "application/json");
|
||||||
|
org.apache.http.HttpResponse response=null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
StringEntity stringEntity = new StringEntity("{username: 'foo', password: 'bar'}");
|
||||||
|
post.getRequestLine();
|
||||||
|
post.setEntity(stringEntity);
|
||||||
|
response=client.execute(post);
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
private org.apache.http.HttpResponse hitTheServerWithGetRequest(String page) {
|
||||||
|
String url = "http://127.0.0.1:1080/"+page;
|
||||||
|
HttpClient client = HttpClientBuilder.create().build();
|
||||||
|
org.apache.http.HttpResponse response=null;
|
||||||
|
HttpGet get = new HttpGet(url);
|
||||||
|
try {
|
||||||
|
response=client.execute(get);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createExpectationForInvalidAuth() {
|
||||||
|
new MockServerClient("127.0.0.1", 1080)
|
||||||
|
.when(
|
||||||
|
request()
|
||||||
|
.withMethod("POST")
|
||||||
|
.withPath("/validate")
|
||||||
|
.withHeader("\"Content-type\", \"application/json\"")
|
||||||
|
.withBody(exact("{username: 'foo', password: 'bar'}")),
|
||||||
|
exactly(1)
|
||||||
|
)
|
||||||
|
.respond(
|
||||||
|
response()
|
||||||
|
.withStatusCode(401)
|
||||||
|
.withHeaders(
|
||||||
|
new Header("Content-Type", "application/json; charset=utf-8"),
|
||||||
|
new Header("Cache-Control", "public, max-age=86400")
|
||||||
|
)
|
||||||
|
.withBody("{ message: 'incorrect username and password combination' }")
|
||||||
|
.withDelay(TimeUnit.SECONDS,1)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createExpectationForForward(){
|
||||||
|
new MockServerClient("127.0.0.1", 1080)
|
||||||
|
.when(
|
||||||
|
request()
|
||||||
|
.withMethod("GET")
|
||||||
|
.withPath("/index.html"),
|
||||||
|
exactly(1)
|
||||||
|
)
|
||||||
|
.forward(
|
||||||
|
forward()
|
||||||
|
.withHost("www.mock-server.com")
|
||||||
|
.withPort(80)
|
||||||
|
.withScheme(HttpForward.Scheme.HTTP)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createExpectationForCallBack(){
|
||||||
|
mockServer
|
||||||
|
.when(
|
||||||
|
request()
|
||||||
|
.withPath("/callback")
|
||||||
|
)
|
||||||
|
.callback(
|
||||||
|
callback()
|
||||||
|
.withCallbackClass("com.baeldung.mock.server.ExpectationCallbackHandler")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterClass
|
||||||
|
public static void stopProxy() {
|
||||||
|
proxy.stop();
|
||||||
|
mockServer.stop();
|
||||||
|
}
|
||||||
|
}
|
2
pom.xml
2
pom.xml
@ -211,6 +211,7 @@
|
|||||||
<module>spring-reactor</module>
|
<module>spring-reactor</module>
|
||||||
<module>spring-vertx</module>
|
<module>spring-vertx</module>
|
||||||
|
|
||||||
|
|
||||||
<module>testing</module>
|
<module>testing</module>
|
||||||
<module>testng</module>
|
<module>testng</module>
|
||||||
|
|
||||||
@ -230,6 +231,7 @@
|
|||||||
<module>drools</module>
|
<module>drools</module>
|
||||||
<module>liquibase</module>
|
<module>liquibase</module>
|
||||||
<module>spring-boot-property-exp</module>
|
<module>spring-boot-property-exp</module>
|
||||||
|
<module>mockserver</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
@ -14,7 +14,9 @@ import org.springframework.test.context.junit4.SpringRunner;
|
|||||||
import javax.servlet.FilterRegistration;
|
import javax.servlet.FilterRegistration;
|
||||||
import javax.servlet.ServletContext;
|
import javax.servlet.ServletContext;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class)
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class)
|
||||||
@ -22,7 +24,8 @@ import static org.junit.Assert.*;
|
|||||||
@TestPropertySource(properties = {"security.basic.enabled=false"})
|
@TestPropertySource(properties = {"security.basic.enabled=false"})
|
||||||
public class SpringBootWithServletComponentIntegrationTest {
|
public class SpringBootWithServletComponentIntegrationTest {
|
||||||
|
|
||||||
@Autowired private ServletContext servletContext;
|
@Autowired
|
||||||
|
private ServletContext servletContext;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenServletContext_whenAccessAttrs_thenFoundAttrsPutInServletListner() {
|
public void givenServletContext_whenAccessAttrs_thenFoundAttrsPutInServletListner() {
|
||||||
@ -42,7 +45,8 @@ public class SpringBootWithServletComponentIntegrationTest {
|
|||||||
.contains("echo servlet"));
|
.contains("echo servlet"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Autowired private TestRestTemplate restTemplate;
|
@Autowired
|
||||||
|
private TestRestTemplate restTemplate;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenServletFilter_whenGetHello_thenRequestFiltered() {
|
public void givenServletFilter_whenGetHello_thenRequestFiltered() {
|
||||||
@ -59,7 +63,6 @@ public class SpringBootWithServletComponentIntegrationTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -14,7 +14,9 @@ import org.springframework.test.context.junit4.SpringRunner;
|
|||||||
import javax.servlet.FilterRegistration;
|
import javax.servlet.FilterRegistration;
|
||||||
import javax.servlet.ServletContext;
|
import javax.servlet.ServletContext;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class)
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class)
|
||||||
@ -22,9 +24,11 @@ import static org.junit.Assert.*;
|
|||||||
@TestPropertySource(properties = {"security.basic.enabled=false"})
|
@TestPropertySource(properties = {"security.basic.enabled=false"})
|
||||||
public class SpringBootWithoutServletComponentIntegrationTest {
|
public class SpringBootWithoutServletComponentIntegrationTest {
|
||||||
|
|
||||||
@Autowired private ServletContext servletContext;
|
@Autowired
|
||||||
|
private ServletContext servletContext;
|
||||||
|
|
||||||
@Autowired private TestRestTemplate restTemplate;
|
@Autowired
|
||||||
|
private TestRestTemplate restTemplate;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenServletContext_whenAccessAttrs_thenNotFound() {
|
public void givenServletContext_whenAccessAttrs_thenNotFound() {
|
||||||
|
@ -1,5 +1,8 @@
|
|||||||
package com.baeldung.autoconfiguration;
|
package com.baeldung.autoconfiguration;
|
||||||
|
|
||||||
|
import com.baeldung.autoconfiguration.example.AutoconfigurationApplication;
|
||||||
|
import com.baeldung.autoconfiguration.example.MyUser;
|
||||||
|
import com.baeldung.autoconfiguration.example.MyUserRepository;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
@ -7,10 +10,6 @@ import org.springframework.boot.test.context.SpringBootTest;
|
|||||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||||
|
|
||||||
import com.baeldung.autoconfiguration.example.AutoconfigurationApplication;
|
|
||||||
import com.baeldung.autoconfiguration.example.MyUser;
|
|
||||||
import com.baeldung.autoconfiguration.example.MyUserRepository;
|
|
||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@SpringBootTest(classes = AutoconfigurationApplication.class)
|
@SpringBootTest(classes = AutoconfigurationApplication.class)
|
||||||
@EnableJpaRepositories(basePackages = {"com.baeldung.autoconfiguration.example"})
|
@EnableJpaRepositories(basePackages = {"com.baeldung.autoconfiguration.example"})
|
||||||
|
@ -1,15 +1,5 @@
|
|||||||
package com.baeldung.displayallbeans;
|
package com.baeldung.displayallbeans;
|
||||||
|
|
||||||
import static org.assertj.core.api.BDDAssertions.then;
|
|
||||||
import static org.hamcrest.CoreMatchers.hasItem;
|
|
||||||
import static org.junit.Assert.assertThat;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
@ -23,7 +13,15 @@ import org.springframework.test.context.TestPropertySource;
|
|||||||
import org.springframework.test.context.junit4.SpringRunner;
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
import org.springframework.web.context.WebApplicationContext;
|
import org.springframework.web.context.WebApplicationContext;
|
||||||
|
|
||||||
import com.baeldung.displayallbeans.Application;
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.BDDAssertions.then;
|
||||||
|
import static org.hamcrest.CoreMatchers.hasItem;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||||
|
@ -1,9 +1,5 @@
|
|||||||
package com.baeldung.toggle;
|
package com.baeldung.toggle;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
|
||||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
|
||||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
|
||||||
|
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
@ -16,6 +12,10 @@ import org.springframework.test.web.servlet.MockMvc;
|
|||||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||||
import org.springframework.web.context.WebApplicationContext;
|
import org.springframework.web.context.WebApplicationContext;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = ToggleApplication.class)
|
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = ToggleApplication.class)
|
||||||
@AutoConfigureMockMvc
|
@AutoConfigureMockMvc
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
package com.baeldung.utils;
|
package com.baeldung.utils;
|
||||||
|
|
||||||
|
import com.baeldung.utils.controller.UtilsController;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.mockito.InjectMocks;
|
import org.mockito.InjectMocks;
|
||||||
@ -10,9 +11,6 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
|||||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
|
|
||||||
import com.baeldung.utils.controller.UtilsController;
|
|
||||||
|
|
||||||
public class UtilsControllerIntegrationTest {
|
public class UtilsControllerIntegrationTest {
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
|
@ -6,11 +6,6 @@ import org.mockito.Mockito;
|
|||||||
import org.springframework.messaging.simp.stomp.StompHeaders;
|
import org.springframework.messaging.simp.stomp.StompHeaders;
|
||||||
import org.springframework.messaging.simp.stomp.StompSession;
|
import org.springframework.messaging.simp.stomp.StompSession;
|
||||||
|
|
||||||
/**
|
|
||||||
* Test class for MyStompSessionHandler
|
|
||||||
* @author Kalyan
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public class MyStompSessionHandlerIntegrationTest {
|
public class MyStompSessionHandlerIntegrationTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -1,9 +1,5 @@
|
|||||||
package org.baeldung.boot.boottest;
|
package org.baeldung.boot.boottest;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
@ -11,6 +7,10 @@ import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
|||||||
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
|
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
|
||||||
import org.springframework.test.context.junit4.SpringRunner;
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
@DataJpaTest
|
@DataJpaTest
|
||||||
public class EmployeeRepositoryIntegrationTest {
|
public class EmployeeRepositoryIntegrationTest {
|
||||||
|
@ -1,19 +1,5 @@
|
|||||||
package org.baeldung.boot.boottest;
|
package org.baeldung.boot.boottest;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
|
||||||
import static org.hamcrest.CoreMatchers.is;
|
|
||||||
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
|
|
||||||
import static org.hamcrest.Matchers.hasSize;
|
|
||||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
|
||||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
|
||||||
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
|
|
||||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
|
||||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
|
||||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import org.baeldung.boot.DemoApplication;
|
import org.baeldung.boot.DemoApplication;
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
@ -27,6 +13,20 @@ import org.springframework.http.MediaType;
|
|||||||
import org.springframework.test.context.junit4.SpringRunner;
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
import org.springframework.test.web.servlet.MockMvc;
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
|
||||||
|
import static org.hamcrest.Matchers.hasSize;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = DemoApplication.class)
|
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = DemoApplication.class)
|
||||||
@AutoConfigureMockMvc
|
@AutoConfigureMockMvc
|
||||||
|
@ -1,10 +1,5 @@
|
|||||||
package org.baeldung.boot.boottest;
|
package org.baeldung.boot.boottest;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
@ -16,6 +11,11 @@ import org.springframework.boot.test.mock.mockito.MockBean;
|
|||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.test.context.junit4.SpringRunner;
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
public class EmployeeServiceImplIntegrationTest {
|
public class EmployeeServiceImplIntegrationTest {
|
||||||
|
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
package org.baeldung.boot.boottest;
|
package org.baeldung.boot.boottest;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
class JsonUtil {
|
class JsonUtil {
|
||||||
static byte[] toJson(Object object) throws IOException {
|
static byte[] toJson(Object object) throws IOException {
|
||||||
ObjectMapper mapper = new ObjectMapper();
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
@ -115,7 +115,7 @@
|
|||||||
|
|
||||||
<org.springframework.version>4.3.4.RELEASE</org.springframework.version>
|
<org.springframework.version>4.3.4.RELEASE</org.springframework.version>
|
||||||
|
|
||||||
<org.springframework.data.version>1.9.6.RELEASE</org.springframework.data.version>
|
<org.springframework.data.version>1.10.4.RELEASE</org.springframework.data.version>
|
||||||
|
|
||||||
<rest-assured.version>2.9.0</rest-assured.version>
|
<rest-assured.version>2.9.0</rest-assured.version>
|
||||||
<querydsl.version>4.1.4</querydsl.version>
|
<querydsl.version>4.1.4</querydsl.version>
|
||||||
|
@ -3,6 +3,7 @@ package org.baeldung.event;
|
|||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.data.mongodb.core.MongoOperations;
|
import org.springframework.data.mongodb.core.MongoOperations;
|
||||||
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
|
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
|
||||||
|
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
|
||||||
import org.springframework.util.ReflectionUtils;
|
import org.springframework.util.ReflectionUtils;
|
||||||
|
|
||||||
public class CascadeSaveMongoEventListener extends AbstractMongoEventListener<Object> {
|
public class CascadeSaveMongoEventListener extends AbstractMongoEventListener<Object> {
|
||||||
@ -11,7 +12,8 @@ public class CascadeSaveMongoEventListener extends AbstractMongoEventListener<Ob
|
|||||||
private MongoOperations mongoOperations;
|
private MongoOperations mongoOperations;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onBeforeConvert(final Object source) {
|
public void onBeforeConvert(final BeforeConvertEvent<Object> event) {
|
||||||
|
final Object source = event.getSource();
|
||||||
ReflectionUtils.doWithFields(source.getClass(), new CascadeCallback(source, mongoOperations));
|
ReflectionUtils.doWithFields(source.getClass(), new CascadeCallback(source, mongoOperations));
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -4,14 +4,16 @@ import org.baeldung.model.User;
|
|||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.data.mongodb.core.MongoOperations;
|
import org.springframework.data.mongodb.core.MongoOperations;
|
||||||
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
|
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
|
||||||
|
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
|
||||||
|
|
||||||
public class UserCascadeSaveMongoEventListener extends AbstractMongoEventListener<Object> {
|
public class UserCascadeSaveMongoEventListener extends AbstractMongoEventListener<Object> {
|
||||||
@Autowired
|
@Autowired
|
||||||
private MongoOperations mongoOperations;
|
private MongoOperations mongoOperations;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onBeforeConvert(final Object source) {
|
public void onBeforeConvert(final BeforeConvertEvent<Object> event) {
|
||||||
if (source instanceof User && ((User) source).getEmailAddress() != null) {
|
final Object source = event.getSource();
|
||||||
|
if ((source instanceof User) && (((User) source).getEmailAddress() != null)) {
|
||||||
mongoOperations.save(((User) source).getEmailAddress());
|
mongoOperations.save(((User) source).getEmailAddress());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
24
spring-mustache/.gitignore
vendored
Normal file
24
spring-mustache/.gitignore
vendored
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
target/
|
||||||
|
!.mvn/wrapper/maven-wrapper.jar
|
||||||
|
|
||||||
|
### STS ###
|
||||||
|
.apt_generated
|
||||||
|
.classpath
|
||||||
|
.factorypath
|
||||||
|
.project
|
||||||
|
.settings
|
||||||
|
.springBeans
|
||||||
|
|
||||||
|
### IntelliJ IDEA ###
|
||||||
|
.idea
|
||||||
|
*.iws
|
||||||
|
*.iml
|
||||||
|
*.ipr
|
||||||
|
|
||||||
|
### NetBeans ###
|
||||||
|
nbproject/private/
|
||||||
|
build/
|
||||||
|
nbbuild/
|
||||||
|
dist/
|
||||||
|
nbdist/
|
||||||
|
.nb-gradle/
|
61
spring-mustache/pom.xml
Normal file
61
spring-mustache/pom.xml
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>spring-mustache</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<name>spring-mustache</name>
|
||||||
|
<description>Demo project for Spring Boot</description>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
|
<version>1.5.4.RELEASE</version>
|
||||||
|
<relativePath/>
|
||||||
|
<!-- lookup parent from repository -->
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||||
|
<java.version>1.8</java.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-mustache</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.webjars</groupId>
|
||||||
|
<artifactId>bootstrap</artifactId>
|
||||||
|
<version>3.3.7</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.fluttercode.datafactory</groupId>
|
||||||
|
<artifactId>datafactory</artifactId>
|
||||||
|
<version>0.8</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,34 @@
|
|||||||
|
package com.baeldung.springmustache;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.mustache.MustacheEnvironmentCollector;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
|
import org.springframework.core.env.Environment;
|
||||||
|
|
||||||
|
import com.samskivert.mustache.Mustache;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
@ComponentScan(basePackages = {"com.baeldung"})
|
||||||
|
public class SpringMustacheApplication {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(SpringMustacheApplication.class, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public Mustache.Compiler mustacheCompiler(Mustache.TemplateLoader templateLoader, Environment environment) {
|
||||||
|
|
||||||
|
MustacheEnvironmentCollector collector = new MustacheEnvironmentCollector();
|
||||||
|
collector.setEnvironment(environment);
|
||||||
|
|
||||||
|
Mustache.Compiler compiler = Mustache.compiler()
|
||||||
|
.defaultValue("Some Default Value")
|
||||||
|
.withLoader(templateLoader)
|
||||||
|
.withCollector(collector);
|
||||||
|
return compiler;
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,48 @@
|
|||||||
|
package com.baeldung.springmustache.controller;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.TreeMap;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
import org.fluttercode.datafactory.impl.DataFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Controller;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.servlet.ModelAndView;
|
||||||
|
|
||||||
|
import com.baeldung.springmustache.model.Article;
|
||||||
|
|
||||||
|
@Controller
|
||||||
|
public class ArticleController {
|
||||||
|
|
||||||
|
@RequestMapping("/article")
|
||||||
|
public ModelAndView displayArticle(Map<String, Object> model) {
|
||||||
|
|
||||||
|
List<Article> articles = new LinkedList<>();
|
||||||
|
IntStream.range(0, 10)
|
||||||
|
.forEach(count -> {
|
||||||
|
articles.add(generateArticle("Article Title " + count));
|
||||||
|
});
|
||||||
|
|
||||||
|
Map<String, Object> modelMap = new HashMap<>();
|
||||||
|
modelMap.put("articles", articles);
|
||||||
|
|
||||||
|
return new ModelAndView("index", modelMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Article generateArticle(String title) {
|
||||||
|
Article article = new Article();
|
||||||
|
DataFactory factory = new DataFactory();
|
||||||
|
article.setTitle(title);
|
||||||
|
article.setBody(
|
||||||
|
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur faucibus tempor diam. In molestie arcu eget ante facilisis sodales. Maecenas porta tellus sapien, eget rutrum nisi blandit in. Mauris tempor auctor ante, ut blandit velit venenatis id. Ut varius, augue aliquet feugiat congue, arcu ipsum finibus purus, dapibus semper velit sapien venenatis magna. Nunc quam ex, aliquet at rutrum sed, vestibulum quis libero. In laoreet libero cursus maximus vulputate. Nullam in fermentum sem. Duis aliquam ullamcorper dui, et dictum justo placerat id. Aliquam pretium orci quis sapien convallis, non blandit est tempus.");
|
||||||
|
article.setPublishDate(factory.getBirthDate().toString());
|
||||||
|
article.setAuthor(factory.getName());
|
||||||
|
return article;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -0,0 +1,41 @@
|
|||||||
|
package com.baeldung.springmustache.model;
|
||||||
|
|
||||||
|
public class Article {
|
||||||
|
private String title;
|
||||||
|
private String body;
|
||||||
|
private String author;
|
||||||
|
private String publishDate;
|
||||||
|
|
||||||
|
public String getTitle() {
|
||||||
|
return title;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTitle(String title) {
|
||||||
|
this.title = title;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getBody() {
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBody(String body) {
|
||||||
|
this.body = body;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAuthor() {
|
||||||
|
return author;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAuthor(String author) {
|
||||||
|
this.author = author;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPublishDate() {
|
||||||
|
return publishDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPublishDate(String publishDate) {
|
||||||
|
this.publishDate = publishDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user