Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
e05929081a
@ -1,9 +1,10 @@
|
||||
package com.baeldung.s3;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
|
||||
import com.amazonaws.auth.AWSCredentials;
|
||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
||||
import com.amazonaws.auth.BasicAWSCredentials;
|
||||
@ -28,7 +29,7 @@ public class S3Application {
|
||||
"<AWS accesskey>",
|
||||
"<AWS secretkey>"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
//set-up the client
|
||||
@ -74,15 +75,7 @@ public class S3Application {
|
||||
//downloading an object
|
||||
S3Object s3object = awsService.getObject(bucketName, "Document/hello.txt");
|
||||
S3ObjectInputStream inputStream = s3object.getObjectContent();
|
||||
FileOutputStream fos = new FileOutputStream(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();
|
||||
FileUtils.copyInputStreamToFile(inputStream, new File("/Users/user/Desktop/hello.txt"));
|
||||
|
||||
//copying an object
|
||||
awsService.copyObject(
|
||||
|
@ -13,14 +13,13 @@ import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
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.ComponentScan;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@SpringBootApplication
|
||||
@ComponentScan(basePackages="com.baeldung.camel")
|
||||
public class Application extends SpringBootServletInitializer {
|
||||
public class Application{
|
||||
|
||||
@Value("${server.port}")
|
||||
String serverPort;
|
||||
@ -62,10 +61,12 @@ public class Application extends SpringBootServletInitializer {
|
||||
.bindingMode(RestBindingMode.json)
|
||||
.dataFormatProperty("prettyPrint", "true");
|
||||
/**
|
||||
The Rest DSL supports automatic binding json/xml contents to/from POJOs using Camels Data Format.
|
||||
By default the binding mode is off, meaning there is no automatic 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.
|
||||
This allows you, as a developer, to work with the POJOs in Java code.
|
||||
The Rest DSL supports automatic binding json/xml contents to/from
|
||||
POJOs using Camels Data Format.
|
||||
By default the binding mode is off, meaning there is no automatic
|
||||
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")
|
||||
|
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
|
||||
}
|
||||
|
||||
}
|
@ -4,12 +4,12 @@ import java.io.Serializable;
|
||||
|
||||
public class AppleProduct implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1234567L; // user-defined (i.e. not default or generated)
|
||||
// private static final long serialVersionUID = 7654321L; // user-defined (i.e. not default or generated)
|
||||
private static final long serialVersionUID = 1234567L; // user-defined (i.e. not default or generated)
|
||||
// private static final long serialVersionUID = 7654321L; // user-defined (i.e. not default or generated)
|
||||
|
||||
public String headphonePort;
|
||||
public String thunderboltPort;
|
||||
public String lighteningPort;
|
||||
public String lightningPort;
|
||||
|
||||
public String getHeadphonePort() {
|
||||
return headphonePort;
|
||||
@ -23,4 +23,8 @@ public class AppleProduct implements Serializable {
|
||||
return serialVersionUID;
|
||||
}
|
||||
|
||||
public String getLightningPort() {
|
||||
return lightningPort;
|
||||
}
|
||||
|
||||
}
|
@ -9,11 +9,12 @@ public class DeserializationUtility {
|
||||
|
||||
public static void main(String[] args) throws ClassNotFoundException, IOException {
|
||||
|
||||
String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
|
||||
String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADWxpZ2h0bmluZ1BvcnRxAH4AAUwAD3RodW5kZXJib2x0UG9ydHEAfgABeHB0ABFoZWFkcGhvbmVQb3J0MjAyMHQAEWxpZ2h0bmluZ1BvcnQyMDIwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
|
||||
System.out.println("Deserializing AppleProduct...");
|
||||
AppleProduct deserializedObj = (AppleProduct) deSerializeObjectFromString(serializedObj);
|
||||
System.out.println("Headphone port of AppleProduct:" + deserializedObj.getHeadphonePort());
|
||||
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 {
|
||||
|
@ -13,6 +13,7 @@ public class SerializationUtility {
|
||||
AppleProduct macBook = new AppleProduct();
|
||||
macBook.headphonePort = "headphonePort2020";
|
||||
macBook.thunderboltPort = "thunderboltPort2020";
|
||||
macBook.lightningPort = "lightningPort2020";
|
||||
|
||||
String serializedObj = serializeObjectToString(macBook);
|
||||
System.out.println("Serialized AppleProduct object to string:");
|
||||
|
@ -10,14 +10,13 @@ public class CustomTemporalAdjuster implements TemporalAdjuster {
|
||||
|
||||
@Override
|
||||
public Temporal adjustInto(Temporal temporal) {
|
||||
DayOfWeek dayOfWeek = DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK));
|
||||
int daysToAdd;
|
||||
if (dayOfWeek == DayOfWeek.FRIDAY)
|
||||
daysToAdd = 3;
|
||||
else if (dayOfWeek == DayOfWeek.SATURDAY)
|
||||
daysToAdd = 2;
|
||||
else
|
||||
daysToAdd = 1;
|
||||
return temporal.plus(daysToAdd, ChronoUnit.DAYS);
|
||||
switch (DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK))) {
|
||||
case FRIDAY:
|
||||
return temporal.plus(3, ChronoUnit.DAYS);
|
||||
case SATURDAY:
|
||||
return temporal.plus(2, ChronoUnit.DAYS);
|
||||
default:
|
||||
return temporal.plus(1, 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 {
|
||||
|
||||
private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
|
||||
private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAdMuxAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADWxpZ2h0bmluZ1BvcnRxAH4AAUwAD3RodW5kZXJib2x0UG9ydHEAfgABeHB0ABFoZWFkcGhvbmVQb3J0MjAyMHQAEWxpZ2h0bmluZ1BvcnQyMDIwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA";
|
||||
|
||||
private static long userDefinedSerialVersionUID = 1234567L;
|
||||
|
||||
@ -25,20 +25,22 @@ public class DeserializationUnitTest {
|
||||
public void testDeserializeObj_compatible() throws IOException, ClassNotFoundException {
|
||||
|
||||
assertEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
|
||||
|
||||
|
||||
AppleProduct macBook = new AppleProduct();
|
||||
macBook.headphonePort = "headphonePort2020";
|
||||
macBook.thunderboltPort = "thunderboltPort2020";
|
||||
|
||||
macBook.lightningPort = "lightningPort2020";
|
||||
|
||||
// serializes the "AppleProduct" object
|
||||
String serializedProduct = SerializationUtility.serializeObjectToString(macBook);
|
||||
|
||||
// deserializes the "AppleProduct" object
|
||||
AppleProduct deserializedProduct = (AppleProduct) DeserializationUtility.deSerializeObjectFromString(serializedProduct);
|
||||
|
||||
|
||||
assertTrue(deserializedProduct.headphonePort.equalsIgnoreCase(macBook.headphonePort));
|
||||
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 {
|
||||
|
||||
assertNotEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
|
||||
|
||||
// attempts to deserialize the "AppleProduct" object
|
||||
DeserializationUtility.deSerializeObjectFromString(serializedObj);
|
||||
}
|
||||
|
@ -1,34 +1,34 @@
|
||||
package com.baeldung.temporaladjusters;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
import java.time.temporal.TemporalAdjuster;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
|
||||
import com.baeldung.temporaladjuster.CustomTemporalAdjuster;
|
||||
import org.junit.Assert;
|
||||
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 {
|
||||
|
||||
private static final TemporalAdjuster NEXT_WORKING_DAY = new CustomTemporalAdjuster();
|
||||
|
||||
@Test
|
||||
public void whenAdjustAndImplementInterface_thenNextWorkingDay() {
|
||||
LocalDate localDate = LocalDate.of(2017, 07, 8);
|
||||
CustomTemporalAdjuster temporalAdjuster = new CustomTemporalAdjuster();
|
||||
LocalDate nextWorkingDay = localDate.with(temporalAdjuster);
|
||||
|
||||
Assert.assertEquals("2017-07-10", nextWorkingDay.toString());
|
||||
assertEquals("2017-07-10", nextWorkingDay.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAdjust_thenNextWorkingDay() {
|
||||
LocalDate localDate = LocalDate.of(2017, 07, 8);
|
||||
TemporalAdjuster temporalAdjuster = NEXT_WORKING_DAY;
|
||||
LocalDate date = localDate.with(temporalAdjuster);
|
||||
LocalDate date = localDate.with(NEXT_WORKING_DAY);
|
||||
|
||||
Assert.assertEquals("2017-07-10", date.toString());
|
||||
assertEquals("2017-07-10", date.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -39,18 +39,6 @@ public class CustomTemporalAdjusterTest {
|
||||
|
||||
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>
|
||||
|
||||
<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 -->
|
||||
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
||||
|
@ -101,12 +101,7 @@ public class HttpAsyncClientLiveTest {
|
||||
|
||||
@Test
|
||||
public void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception {
|
||||
final TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
|
||||
@Override
|
||||
public final boolean isTrusted(final X509Certificate[] certificate, final String authType) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
|
||||
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).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 HttpGet request;
|
||||
|
||||
public GetThread(final CloseableHttpAsyncClient client, final HttpGet request) {
|
||||
GetThread(final CloseableHttpAsyncClient client, final HttpGet request) {
|
||||
this.client = client;
|
||||
context = HttpClientContext.create();
|
||||
this.request = request;
|
||||
|
@ -1,11 +1,7 @@
|
||||
package org.baeldung.httpclient;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpHeaders;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
@ -20,7 +16,8 @@ import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
public class HttpClientHeadersLiveTest {
|
||||
|
||||
@ -37,19 +34,7 @@ public class HttpClientHeadersLiveTest {
|
||||
|
||||
@After
|
||||
public final void after() throws IllegalStateException, IOException {
|
||||
if (response == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final HttpEntity entity = response.getEntity();
|
||||
if (entity != null) {
|
||||
final InputStream instream = entity.getContent();
|
||||
instream.close();
|
||||
}
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
ResponseUtil.closeResponse(response);
|
||||
}
|
||||
|
||||
// tests - headers - deprecated
|
||||
|
@ -1,22 +1,7 @@
|
||||
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.HttpStatus;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.entity.ContentType;
|
||||
@ -30,6 +15,20 @@ import org.junit.After;
|
||||
import org.junit.Before;
|
||||
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 {
|
||||
|
||||
// No longer available
|
||||
@ -48,7 +47,7 @@ public class HttpClientMultipartLiveTest {
|
||||
@Before
|
||||
public final void before() {
|
||||
client = HttpClientBuilder.create()
|
||||
.build();
|
||||
.build();
|
||||
post = new HttpPost(SERVER);
|
||||
}
|
||||
|
||||
@ -67,15 +66,7 @@ public class HttpClientMultipartLiveTest {
|
||||
LOGGER.log(Level.SEVERE, e.getMessage(), e);
|
||||
throw e;
|
||||
}
|
||||
try {
|
||||
final HttpEntity entity = response.getEntity();
|
||||
if (entity != null) {
|
||||
final InputStream instream = entity.getContent();
|
||||
instream.close();
|
||||
}
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
ResponseUtil.closeResponse(response);
|
||||
}
|
||||
|
||||
// tests
|
||||
@ -83,8 +74,8 @@ public class HttpClientMultipartLiveTest {
|
||||
@Test
|
||||
public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
|
||||
final URL url = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + TEXTFILENAME);
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + TEXTFILENAME);
|
||||
|
||||
final File file = new File(url.getPath());
|
||||
final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
|
||||
@ -102,7 +93,7 @@ public class HttpClientMultipartLiveTest {
|
||||
response = client.execute(post);
|
||||
|
||||
final int statusCode = response.getStatusLine()
|
||||
.getStatusCode();
|
||||
.getStatusCode();
|
||||
final String responseString = getContent();
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
@ -113,10 +104,10 @@ public class HttpClientMultipartLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws ClientProtocolException, IOException {
|
||||
public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException {
|
||||
final URL url = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + TEXTFILENAME);
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + TEXTFILENAME);
|
||||
final File file = new File(url.getPath());
|
||||
final String message = "This is a multipart post";
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
@ -127,7 +118,7 @@ public class HttpClientMultipartLiveTest {
|
||||
post.setEntity(entity);
|
||||
response = client.execute(post);
|
||||
final int statusCode = response.getStatusLine()
|
||||
.getStatusCode();
|
||||
.getStatusCode();
|
||||
final String responseString = getContent();
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
@ -138,13 +129,13 @@ public class HttpClientMultipartLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException {
|
||||
public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
|
||||
final URL url = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + ZIPFILENAME);
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + ZIPFILENAME);
|
||||
final URL url2 = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + IMAGEFILENAME);
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + IMAGEFILENAME);
|
||||
final InputStream inputStream = new FileInputStream(url.getPath());
|
||||
final File file = new File(url2.getPath());
|
||||
final String message = "This is a multipart post";
|
||||
@ -157,7 +148,7 @@ public class HttpClientMultipartLiveTest {
|
||||
post.setEntity(entity);
|
||||
response = client.execute(post);
|
||||
final int statusCode = response.getStatusLine()
|
||||
.getStatusCode();
|
||||
.getStatusCode();
|
||||
final String responseString = getContent();
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
@ -169,7 +160,7 @@ public class HttpClientMultipartLiveTest {
|
||||
}
|
||||
|
||||
@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 byte[] bytes = "binary code".getBytes();
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
@ -180,7 +171,7 @@ public class HttpClientMultipartLiveTest {
|
||||
post.setEntity(entity);
|
||||
response = client.execute(post);
|
||||
final int statusCode = response.getStatusLine()
|
||||
.getStatusCode();
|
||||
.getStatusCode();
|
||||
final String responseString = getContent();
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
@ -192,21 +183,21 @@ public class HttpClientMultipartLiveTest {
|
||||
|
||||
// UTIL
|
||||
|
||||
final String getContent() throws IOException {
|
||||
private String getContent() throws IOException {
|
||||
rd = new BufferedReader(new InputStreamReader(response.getEntity()
|
||||
.getContent()));
|
||||
.getContent()));
|
||||
String body = "";
|
||||
String content = "";
|
||||
StringBuilder content = new StringBuilder();
|
||||
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()
|
||||
.getContentType()
|
||||
.toString();
|
||||
.getContentType()
|
||||
.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,20 +1,10 @@
|
||||
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.HttpResponse;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.auth.AuthenticationException;
|
||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.fluent.Form;
|
||||
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.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
|
||||
*/
|
||||
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 DEFAULT_USER = "test";
|
||||
private static final String DEFAULT_PASS = "test";
|
||||
|
||||
@Test
|
||||
public void whenSendPostRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
|
||||
public void whenSendPostRequestUsingHttpClient_thenCorrect() throws IOException {
|
||||
final CloseableHttpClient client = HttpClients.createDefault();
|
||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
|
||||
|
||||
@ -54,7 +53,7 @@ public class HttpClientPostingLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException, AuthenticationException {
|
||||
public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException, AuthenticationException {
|
||||
final CloseableHttpClient client = HttpClients.createDefault();
|
||||
final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);
|
||||
|
||||
@ -68,7 +67,7 @@ public class HttpClientPostingLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPostJsonUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
|
||||
public void whenPostJsonUsingHttpClient_thenCorrect() throws IOException {
|
||||
final CloseableHttpClient client = HttpClients.createDefault();
|
||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/detail");
|
||||
|
||||
@ -84,14 +83,14 @@ public class HttpClientPostingLiveTest {
|
||||
}
|
||||
|
||||
@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();
|
||||
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
|
||||
public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws IOException {
|
||||
final CloseableHttpClient client = HttpClients.createDefault();
|
||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/multipart");
|
||||
|
||||
@ -109,7 +108,7 @@ public class HttpClientPostingLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUploadFileUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
|
||||
public void whenUploadFileUsingHttpClient_thenCorrect() throws IOException {
|
||||
final CloseableHttpClient client = HttpClients.createDefault();
|
||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload");
|
||||
|
||||
@ -125,7 +124,7 @@ public class HttpClientPostingLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
|
||||
public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws IOException {
|
||||
final CloseableHttpClient client = HttpClients.createDefault();
|
||||
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");
|
||||
final HttpEntity multipart = builder.build();
|
||||
|
||||
final ProgressEntityWrapper.ProgressListener pListener = new ProgressEntityWrapper.ProgressListener() {
|
||||
@Override
|
||||
public void progress(final float percentage) {
|
||||
assertFalse(Float.compare(percentage, 100) > 0);
|
||||
}
|
||||
};
|
||||
final ProgressEntityWrapper.ProgressListener pListener = percentage -> assertFalse(Float.compare(percentage, 100) > 0);
|
||||
|
||||
httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener));
|
||||
|
||||
|
@ -1,13 +1,5 @@
|
||||
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.HttpGet;
|
||||
import org.apache.http.client.methods.HttpHead;
|
||||
@ -21,6 +13,12 @@ import org.junit.After;
|
||||
import org.junit.Before;
|
||||
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 {
|
||||
|
||||
private CloseableHttpClient instance;
|
||||
@ -34,25 +32,13 @@ public class HttpClientRedirectLiveTest {
|
||||
|
||||
@After
|
||||
public final void after() throws IllegalStateException, IOException {
|
||||
if (response == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final HttpEntity entity = response.getEntity();
|
||||
if (entity != null) {
|
||||
final InputStream instream = entity.getContent();
|
||||
instream.close();
|
||||
}
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
ResponseUtil.closeResponse(response);
|
||||
}
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public final void givenRedirectsAreDisabledViaNewApi_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException {
|
||||
public final void givenRedirectsAreDisabledViaNewApi_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
|
||||
instance = HttpClients.custom().disableRedirectHandling().build();
|
||||
|
||||
final HttpGet httpGet = new HttpGet("http://t.co/I5YYd9tddw");
|
||||
@ -62,7 +48,7 @@ public class HttpClientRedirectLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException {
|
||||
public final void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
|
||||
instance = HttpClientBuilder.create().disableRedirectHandling().build();
|
||||
response = instance.execute(new HttpGet("http://t.co/I5YYd9tddw"));
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
|
||||
@ -71,26 +57,22 @@ public class HttpClientRedirectLiveTest {
|
||||
// redirect with POST
|
||||
|
||||
@Test
|
||||
public final void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException {
|
||||
public final void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
|
||||
instance = HttpClientBuilder.create().build();
|
||||
response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
|
||||
}
|
||||
|
||||
@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() {
|
||||
/** 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
|
||||
protected boolean isRedirectable(final String method) {
|
||||
for (final String m : REDIRECT_METHODS) {
|
||||
if (m.equalsIgnoreCase(method)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
return Arrays.stream(REDIRECT_METHODS)
|
||||
.anyMatch(m -> m.equalsIgnoreCase(method));
|
||||
}
|
||||
}).build();
|
||||
|
||||
@ -99,7 +81,7 @@ public class HttpClientRedirectLiveTest {
|
||||
}
|
||||
|
||||
@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();
|
||||
|
||||
response = client.execute(new HttpPost("http://t.co/I5YYd9tddw"));
|
||||
@ -107,7 +89,7 @@ public class HttpClientRedirectLiveTest {
|
||||
}
|
||||
|
||||
@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();
|
||||
response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
|
@ -1,13 +1,5 @@
|
||||
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.methods.CloseableHttpResponse;
|
||||
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.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class HttpClientTimeoutLiveTest {
|
||||
|
||||
private CloseableHttpResponse response;
|
||||
|
||||
@After
|
||||
public final void after() throws IllegalStateException, IOException {
|
||||
if (response == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final HttpEntity entity = response.getEntity();
|
||||
if (entity != null) {
|
||||
final InputStream instream = entity.getContent();
|
||||
instream.close();
|
||||
}
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
ResponseUtil.closeResponse(response);
|
||||
}
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public final void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrect() throws ClientProtocolException, IOException {
|
||||
public final void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrect() throws IOException {
|
||||
final int timeout = 2;
|
||||
final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
|
||||
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
|
||||
@ -56,7 +41,7 @@ public class HttpClientTimeoutLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingNewApi_whenSettingTimeoutViaSocketConfig_thenCorrect() throws ClientProtocolException, IOException {
|
||||
public final void givenUsingNewApi_whenSettingTimeoutViaSocketConfig_thenCorrect() throws IOException {
|
||||
final int timeout = 2;
|
||||
|
||||
final SocketConfig config = SocketConfig.custom().setSoTimeout(timeout * 1000).build();
|
||||
@ -70,7 +55,7 @@ public class HttpClientTimeoutLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingNewApi_whenSettingTimeoutViaHighLevelApi_thenCorrect() throws ClientProtocolException, IOException {
|
||||
public final void givenUsingNewApi_whenSettingTimeoutViaHighLevelApi_thenCorrect() throws IOException {
|
||||
final int timeout = 5;
|
||||
|
||||
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)
|
||||
*/
|
||||
@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 RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
|
||||
|
@ -1,14 +1,5 @@
|
||||
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.client.methods.HttpGet;
|
||||
import org.apache.http.conn.ClientConnectionManager;
|
||||
@ -28,6 +19,14 @@ import org.apache.http.ssl.SSLContextBuilder;
|
||||
import org.apache.http.ssl.SSLContexts;
|
||||
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>
|
||||
* 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 {
|
||||
private final ProgressListener listener;
|
||||
|
||||
public ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) {
|
||||
ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) {
|
||||
super(entity);
|
||||
this.listener = listener;
|
||||
}
|
||||
@ -20,7 +20,7 @@ public class ProgressEntityWrapper extends HttpEntityWrapper {
|
||||
super.writeTo(new CountingOutputStream(outstream, listener, getContentLength()));
|
||||
}
|
||||
|
||||
public static interface ProgressListener {
|
||||
public interface ProgressListener {
|
||||
void progress(float percentage);
|
||||
}
|
||||
|
||||
@ -30,7 +30,7 @@ public class ProgressEntityWrapper extends HttpEntityWrapper {
|
||||
private long transferred;
|
||||
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);
|
||||
this.listener = listener;
|
||||
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 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;
|
||||
|
||||
public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||
@ -40,9 +47,9 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||
//given
|
||||
String userAgent = "BaeldungAgent/1.0";
|
||||
serviceMock.stubFor(get(urlEqualTo("/detail"))
|
||||
.withHeader("User-Agent", equalTo(userAgent))
|
||||
.willReturn(aResponse()
|
||||
.withStatus(200)));
|
||||
.withHeader("User-Agent", equalTo(userAgent))
|
||||
.willReturn(aResponse()
|
||||
.withStatus(200)));
|
||||
|
||||
HttpClient httpClient = HttpClients.createDefault();
|
||||
HttpGet httpGet = new HttpGet("http://localhost:8089/detail");
|
||||
@ -60,10 +67,10 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||
//given
|
||||
String xmlBody = "<xml><id>1</id></xml>";
|
||||
serviceMock.stubFor(post(urlEqualTo("/person"))
|
||||
.withHeader("Content-Type", equalTo("application/xml"))
|
||||
.withRequestBody(equalTo(xmlBody))
|
||||
.willReturn(aResponse()
|
||||
.withStatus(200)));
|
||||
.withHeader("Content-Type", equalTo("application/xml"))
|
||||
.withRequestBody(equalTo(xmlBody))
|
||||
.willReturn(aResponse()
|
||||
.withStatus(200)));
|
||||
|
||||
HttpClient httpClient = HttpClients.createDefault();
|
||||
HttpPost httpPost = new HttpPost("http://localhost:8089/person");
|
||||
@ -83,17 +90,17 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||
public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException {
|
||||
//given
|
||||
proxyMock.stubFor(get(urlMatching(".*"))
|
||||
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
|
||||
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
|
||||
|
||||
serviceMock.stubFor(get(urlEqualTo("/private"))
|
||||
.willReturn(aResponse().withStatus(200)));
|
||||
.willReturn(aResponse().withStatus(200)));
|
||||
|
||||
|
||||
HttpHost proxy = new HttpHost("localhost", 8090);
|
||||
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
|
||||
HttpClient httpclient = HttpClients.custom()
|
||||
.setRoutePlanner(routePlanner)
|
||||
.build();
|
||||
.setRoutePlanner(routePlanner)
|
||||
.build();
|
||||
|
||||
//when
|
||||
final HttpGet httpGet = new HttpGet("http://localhost:8089/private");
|
||||
@ -109,9 +116,9 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||
public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException {
|
||||
//given
|
||||
proxyMock.stubFor(get(urlMatching("/private"))
|
||||
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
|
||||
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
|
||||
serviceMock.stubFor(get(urlEqualTo("/private"))
|
||||
.willReturn(aResponse().withStatus(200)));
|
||||
.willReturn(aResponse().withStatus(200)));
|
||||
|
||||
|
||||
HttpHost proxy = new HttpHost("localhost", 8090);
|
||||
@ -120,7 +127,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||
// Client credentials
|
||||
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
|
||||
credentialsProvider.setCredentials(new AuthScope(proxy),
|
||||
new UsernamePasswordCredentials("username_admin", "secret_password"));
|
||||
new UsernamePasswordCredentials("username_admin", "secret_password"));
|
||||
|
||||
|
||||
// Create AuthCache instance
|
||||
@ -135,9 +142,9 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||
|
||||
|
||||
HttpClient httpclient = HttpClients.custom()
|
||||
.setRoutePlanner(routePlanner)
|
||||
.setDefaultCredentialsProvider(credentialsProvider)
|
||||
.build();
|
||||
.setRoutePlanner(routePlanner)
|
||||
.setDefaultCredentialsProvider(credentialsProvider)
|
||||
.build();
|
||||
|
||||
|
||||
//when
|
||||
|
@ -1,13 +1,5 @@
|
||||
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.client.ClientProtocolException;
|
||||
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.HttpClientBuilder;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.baeldung.httpclient.ResponseUtil;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
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 {
|
||||
|
||||
private static final String SAMPLE_URL = "http://www.github.com";
|
||||
@ -35,19 +34,7 @@ public class HttpClientBasicLiveTest {
|
||||
|
||||
@After
|
||||
public final void after() throws IllegalStateException, IOException {
|
||||
if (response == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final HttpEntity entity = response.getEntity();
|
||||
if (entity != null) {
|
||||
final InputStream instream = entity.getContent();
|
||||
instream.close();
|
||||
}
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
ResponseUtil.closeResponse(response);
|
||||
}
|
||||
|
||||
// tests
|
||||
|
@ -1,22 +1,20 @@
|
||||
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.UsernamePasswordCredentials;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.auth.BasicScheme;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.baeldung.httpclient.ResponseUtil;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class HttpClientBasicPostLiveTest {
|
||||
|
||||
private static final String SAMPLE_URL = "http://www.github.com";
|
||||
@ -32,37 +30,25 @@ public class HttpClientBasicPostLiveTest {
|
||||
|
||||
@After
|
||||
public final void after() throws IllegalStateException, IOException {
|
||||
if (response == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final HttpEntity entity = response.getEntity();
|
||||
if (entity != null) {
|
||||
final InputStream instream = entity.getContent();
|
||||
instream.close();
|
||||
}
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
ResponseUtil.closeResponse(response);
|
||||
}
|
||||
|
||||
// tests - non-GET
|
||||
|
||||
@Test
|
||||
public final void whenExecutingPostRequest_thenNoExceptions() throws ClientProtocolException, IOException {
|
||||
public final void whenExecutingPostRequest_thenNoExceptions() throws IOException {
|
||||
instance.execute(new HttpPost(SAMPLE_URL));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws ClientProtocolException, IOException {
|
||||
public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException {
|
||||
final HttpPost request = new HttpPost(SAMPLE_URL);
|
||||
request.setEntity(new StringEntity("in the body of the POST"));
|
||||
instance.execute(request);
|
||||
}
|
||||
|
||||
@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);
|
||||
request.setEntity(new StringEntity("in the body of the POST"));
|
||||
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.HttpClients;
|
||||
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
|
||||
import org.baeldung.httpclient.ResponseUtil;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import static org.hamcrest.Matchers.emptyArray;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
@ -37,19 +37,7 @@ public class HttpClientLiveTest {
|
||||
|
||||
@After
|
||||
public final void after() throws IllegalStateException, IOException {
|
||||
if (response == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final HttpEntity entity = response.getEntity();
|
||||
if (entity != null) {
|
||||
final InputStream instream = entity.getContent();
|
||||
instream.close();
|
||||
}
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
ResponseUtil.closeResponse(response);
|
||||
}
|
||||
|
||||
// tests
|
||||
|
@ -1,9 +1,5 @@
|
||||
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.UsernamePasswordCredentials;
|
||||
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.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.baeldung.httpclient.ResponseUtil;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/*
|
||||
* NOTE : Need module spring-security-rest-basic-auth to be running
|
||||
*/
|
||||
@ -32,15 +31,6 @@ public class HttpClientSandboxLiveTest {
|
||||
|
||||
System.out.println(response.getStatusLine());
|
||||
|
||||
try {
|
||||
final HttpEntity entity = response.getEntity();
|
||||
if (entity != null) {
|
||||
// EntityUtils.consume(entity);
|
||||
final InputStream instream = entity.getContent();
|
||||
instream.close();
|
||||
}
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
ResponseUtil.closeResponse(response);
|
||||
}
|
||||
}
|
||||
|
@ -1,11 +1,5 @@
|
||||
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.HeaderElementIterator;
|
||||
import org.apache.http.HttpClientConnection;
|
||||
@ -36,6 +30,12 @@ import org.junit.Before;
|
||||
import org.junit.Ignore;
|
||||
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 {
|
||||
private static final String SERVER1 = "http://www.petrikainulainen.net/";
|
||||
private static final String SERVER7 = "http://www.baeldung.com/";
|
||||
@ -129,7 +129,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||
@Test
|
||||
// @Ignore
|
||||
// Example 3.2. TESTER VERSION
|
||||
/*tester*/public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException {
|
||||
/*tester*/ public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException {
|
||||
poolingConnManager = new PoolingHttpClientConnectionManager();
|
||||
final CloseableHttpClient client1 = HttpClients.custom().setConnectionManager(poolingConnManager).build();
|
||||
final CloseableHttpClient client2 = HttpClients.custom().setConnectionManager(poolingConnManager).build();
|
||||
@ -173,7 +173,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||
@Test
|
||||
// @Ignore
|
||||
// 4.2 Tester Version
|
||||
/*tester*/public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException, IOException {
|
||||
/*tester*/ public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException, IOException {
|
||||
poolingConnManager = new PoolingHttpClientConnectionManager();
|
||||
client = HttpClients.custom().setConnectionManager(poolingConnManager).build();
|
||||
final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager);
|
||||
@ -266,7 +266,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||
@Test
|
||||
// @Ignore
|
||||
// 6.2 TESTER VERSION
|
||||
/*tester*/public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException {
|
||||
/*tester*/ public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException {
|
||||
poolingConnManager = new PoolingHttpClientConnectionManager();
|
||||
poolingConnManager.setDefaultMaxPerRoute(5);
|
||||
poolingConnManager.setMaxTotal(5);
|
||||
@ -333,7 +333,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||
@Test
|
||||
@Ignore("Very Long Running")
|
||||
// 8.2 TESTER VERSION
|
||||
/*tester*/public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException, IOException {
|
||||
/*tester*/ public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException, IOException {
|
||||
poolingConnManager = new PoolingHttpClientConnectionManager();
|
||||
client = HttpClients.custom().setConnectionManager(poolingConnManager).build();
|
||||
final IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(poolingConnManager);
|
||||
|
@ -9,7 +9,7 @@ public class IdleConnectionMonitorThread extends Thread {
|
||||
private final HttpClientConnectionManager connMgr;
|
||||
private volatile boolean shutdown;
|
||||
|
||||
public IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) {
|
||||
IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) {
|
||||
super();
|
||||
this.connMgr = connMgr;
|
||||
}
|
||||
@ -31,7 +31,7 @@ public class IdleConnectionMonitorThread extends Thread {
|
||||
}
|
||||
}
|
||||
|
||||
public final void shutdown() {
|
||||
private void shutdown() {
|
||||
shutdown = true;
|
||||
synchronized (this) {
|
||||
notifyAll();
|
||||
|
@ -18,23 +18,23 @@ public class MultiHttpClientConnThread extends Thread {
|
||||
private final HttpGet get;
|
||||
|
||||
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.get = get;
|
||||
this.connManager = connManager;
|
||||
leasedConn = 0;
|
||||
}
|
||||
|
||||
public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) {
|
||||
MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) {
|
||||
this.client = client;
|
||||
this.get = get;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public final int getLeasedConn() {
|
||||
final int getLeasedConn() {
|
||||
return leasedConn;
|
||||
}
|
||||
|
||||
@ -61,8 +61,6 @@ public class MultiHttpClientConnThread extends Thread {
|
||||
}
|
||||
|
||||
EntityUtils.consume(response.getEntity());
|
||||
} catch (final ClientProtocolException ex) {
|
||||
logger.error("", ex);
|
||||
} catch (final IOException ex) {
|
||||
logger.error("", ex);
|
||||
}
|
||||
|
@ -18,7 +18,7 @@ public class TesterVersion_MultiHttpClientConnThread extends Thread {
|
||||
private final HttpGet get;
|
||||
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.get = get;
|
||||
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 - Available Connections = " + connManager.getTotalStats().getAvailable());
|
||||
} catch (final ClientProtocolException ex) {
|
||||
logger.error("", ex);
|
||||
} catch (final IOException ex) {
|
||||
logger.error("", ex);
|
||||
}
|
||||
|
@ -1,12 +1,7 @@
|
||||
package org.baeldung.httpclient.rare;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import com.google.common.collect.Lists;
|
||||
import org.apache.commons.lang3.tuple.ImmutablePair;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.apache.http.Header;
|
||||
@ -20,8 +15,12 @@ import org.apache.http.util.EntityUtils;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import com.google.common.collect.Lists;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class HttpClientUnshortenLiveTest {
|
||||
|
||||
@ -52,7 +51,7 @@ public class HttpClientUnshortenLiveTest {
|
||||
|
||||
// API
|
||||
|
||||
final String expand(final String urlArg) throws IOException {
|
||||
private String expand(final String urlArg) throws IOException {
|
||||
String originalUrl = urlArg;
|
||||
String newUrl = expandSingleLevel(originalUrl);
|
||||
while (!originalUrl.equals(newUrl)) {
|
||||
@ -81,7 +80,7 @@ public class HttpClientUnshortenLiveTest {
|
||||
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;
|
||||
HttpEntity httpEntity = null;
|
||||
InputStream entityContentStream = null;
|
||||
@ -95,15 +94,15 @@ public class HttpClientUnshortenLiveTest {
|
||||
|
||||
final int statusCode = httpResponse.getStatusLine().getStatusCode();
|
||||
if (statusCode != 301 && statusCode != 302) {
|
||||
return new ImmutablePair<Integer, String>(statusCode, url);
|
||||
return new ImmutablePair<>(statusCode, url);
|
||||
}
|
||||
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
|
||||
Preconditions.checkState(headers.length == 1);
|
||||
final String newUrl = headers[0].getValue();
|
||||
|
||||
return new ImmutablePair<Integer, String>(statusCode, newUrl);
|
||||
return new ImmutablePair<>(statusCode, newUrl);
|
||||
} catch (final IllegalArgumentException uriEx) {
|
||||
return new ImmutablePair<Integer, String>(500, url);
|
||||
return new ImmutablePair<>(500, url);
|
||||
} finally {
|
||||
if (request != null) {
|
||||
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;
|
||||
|
||||
try {
|
||||
@ -130,9 +129,8 @@ public class HttpClientUnshortenLiveTest {
|
||||
}
|
||||
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
|
||||
Preconditions.checkState(headers.length == 1);
|
||||
final String newUrl = headers[0].getValue();
|
||||
|
||||
return newUrl;
|
||||
return headers[0].getValue();
|
||||
} catch (final IllegalArgumentException uriEx) {
|
||||
return url;
|
||||
} finally {
|
||||
|
@ -1,21 +1,12 @@
|
||||
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.http.HttpEntity;
|
||||
import org.apache.http.HttpHeaders;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.apache.http.auth.AuthScope;
|
||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||
import org.apache.http.client.AuthCache;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.CredentialsProvider;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
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.HttpClientBuilder;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.baeldung.httpclient.ResponseUtil;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
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
|
||||
*/
|
||||
@ -51,25 +49,13 @@ public class HttpClientAuthLiveTest {
|
||||
|
||||
@After
|
||||
public final void after() throws IllegalStateException, IOException {
|
||||
if (response == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final HttpEntity entity = response.getEntity();
|
||||
if (entity != null) {
|
||||
final InputStream instream = entity.getContent();
|
||||
instream.close();
|
||||
}
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
ResponseUtil.closeResponse(response);
|
||||
}
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws ClientProtocolException, IOException {
|
||||
public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException {
|
||||
client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider()).build();
|
||||
|
||||
response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION));
|
||||
@ -79,7 +65,7 @@ public class HttpClientAuthLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws ClientProtocolException, IOException {
|
||||
public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException {
|
||||
client = HttpClientBuilder.create().build();
|
||||
response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context());
|
||||
|
||||
@ -88,7 +74,7 @@ public class HttpClientAuthLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws ClientProtocolException, IOException {
|
||||
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws IOException {
|
||||
client = HttpClientBuilder.create().build();
|
||||
|
||||
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
|
||||
@ -100,7 +86,7 @@ public class HttpClientAuthLiveTest {
|
||||
}
|
||||
|
||||
@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 String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
|
||||
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
|
||||
@ -116,14 +102,14 @@ public class HttpClientAuthLiveTest {
|
||||
|
||||
// UTILS
|
||||
|
||||
private final CredentialsProvider provider() {
|
||||
private CredentialsProvider provider() {
|
||||
final CredentialsProvider provider = new BasicCredentialsProvider();
|
||||
final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
|
||||
provider.setCredentials(AuthScope.ANY, credentials);
|
||||
return provider;
|
||||
}
|
||||
|
||||
private final HttpContext context() {
|
||||
private HttpContext context() {
|
||||
final HttpHost targetHost = new HttpHost("localhost", 8080, "http");
|
||||
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
|
||||
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS));
|
||||
@ -141,12 +127,11 @@ public class HttpClientAuthLiveTest {
|
||||
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 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;
|
||||
|
||||
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.methods.CloseableHttpResponse;
|
||||
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.protocol.BasicHttpContext;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.baeldung.httpclient.ResponseUtil;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class HttpClientCookieLiveTest {
|
||||
|
||||
private CloseableHttpClient instance;
|
||||
@ -35,25 +33,13 @@ public class HttpClientCookieLiveTest {
|
||||
|
||||
@After
|
||||
public final void after() throws IllegalStateException, IOException {
|
||||
if (response == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final HttpEntity entity = response.getEntity();
|
||||
if (entity != null) {
|
||||
final InputStream instream = entity.getContent();
|
||||
instream.close();
|
||||
}
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
ResponseUtil.closeResponse(response);
|
||||
}
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public final void whenSettingCookiesOnARequest_thenCorrect() throws ClientProtocolException, IOException {
|
||||
public final void whenSettingCookiesOnARequest_thenCorrect() throws IOException {
|
||||
instance = HttpClientBuilder.create().build();
|
||||
final HttpGet request = new HttpGet("http://www.github.com");
|
||||
request.setHeader("Cookie", "JSESSIONID=1234");
|
||||
@ -64,7 +50,7 @@ public class HttpClientCookieLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws ClientProtocolException, IOException {
|
||||
public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws IOException {
|
||||
final BasicCookieStore cookieStore = new BasicCookieStore();
|
||||
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
|
||||
cookie.setDomain(".github.com");
|
||||
@ -80,7 +66,7 @@ public class HttpClientCookieLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws ClientProtocolException, IOException {
|
||||
public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws IOException {
|
||||
final BasicCookieStore cookieStore = new BasicCookieStore();
|
||||
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
|
||||
cookie.setDomain(".github.com");
|
||||
@ -96,7 +82,7 @@ public class HttpClientCookieLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws ClientProtocolException, IOException {
|
||||
public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws IOException {
|
||||
final BasicCookieStore cookieStore = new BasicCookieStore();
|
||||
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
|
||||
cookie.setDomain(".github.com");
|
||||
|
100
jmh/pom.xml
100
jmh/pom.xml
@ -1,52 +1,60 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>jmh</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>jmh</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>jmh</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>jmh</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<maven.compiler.source>1.6</maven.compiler.source>
|
||||
<maven.compiler.target>1.6</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>1.19</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>1.19</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>1.19</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>1.19</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>com.baeldung.Application</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>21.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>com.baeldung.BenchmarkRunner</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
@ -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;
|
||||
|
||||
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 {
|
||||
|
||||
@Benchmark
|
||||
public void init() {
|
||||
|
||||
}
|
||||
@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
|
||||
@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() {
|
||||
// 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)
|
||||
- [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)
|
||||
|
||||
- [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.
|
||||
|
||||
|
@ -7,7 +7,6 @@
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>libraries</artifactId>
|
||||
<name>libraries</name>
|
||||
<build>
|
||||
@ -71,79 +70,51 @@
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<!-- Vaadin -->
|
||||
<!-- Neuroph -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>3.0.0</version>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.0.2</version>
|
||||
<configuration>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
<packagingExcludes>WEB-INF/classes/VAADIN/widgetsets/WEB-INF/**</packagingExcludes>
|
||||
<excludes>
|
||||
<exclude>**/log4j.properties</exclude>
|
||||
</excludes>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>com.baeldung.neuroph.NeurophXOR</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>com.vaadin</groupId>
|
||||
<artifactId>vaadin-maven-plugin</artifactId>
|
||||
<version>${vaadin.plugin.version}</version>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.18.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>test</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>update-theme</goal>
|
||||
<goal>update-widgetset</goal>
|
||||
<goal>compile</goal>
|
||||
<goal>compile-theme</goal>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<includes>
|
||||
<include>test/java/com/baeldung/neuroph/XORTest.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<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 -->
|
||||
<!-- /Neuroph -->
|
||||
</plugins>
|
||||
</build>
|
||||
<!-- Vaadin -->
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>vaadin-addons</id>
|
||||
<url>http://maven.vaadin.com/vaadin-addons</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.vaadin</groupId>
|
||||
<artifactId>vaadin-bom</artifactId>
|
||||
<version>${vaadin.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
<!-- /Vaadin -->
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.beykery/neuroph/2.92 -->
|
||||
<dependency>
|
||||
<groupId>org.beykery</groupId>
|
||||
<artifactId>neuroph</artifactId>
|
||||
<version>${neuroph.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
|
||||
<dependency>
|
||||
<groupId>cglib</groupId>
|
||||
@ -227,11 +198,16 @@
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons.io.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-chain</groupId>
|
||||
<artifactId>commons-chain</artifactId>
|
||||
<version>${commons-chain.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-dbutils</groupId>
|
||||
<artifactId>commons-dbutils</artifactId>
|
||||
<version>${commons.dbutils.version}</version>
|
||||
</dependency>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.flink</groupId>
|
||||
<artifactId>flink-core</artifactId>
|
||||
@ -392,7 +368,6 @@
|
||||
<artifactId>quartz</artifactId>
|
||||
<version>2.3.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>one.util</groupId>
|
||||
<artifactId>streamex</artifactId>
|
||||
@ -458,68 +433,6 @@
|
||||
<version>${org.hamcrest.java-hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</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>
|
||||
<groupId>net.agkn</groupId>
|
||||
<artifactId>hll</artifactId>
|
||||
@ -535,6 +448,16 @@
|
||||
<artifactId>byte-buddy-agent</artifactId>
|
||||
<version>${bytebuddy.version}</version>
|
||||
</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>
|
||||
<properties>
|
||||
<multiverse.version>0.7.0</multiverse.version>
|
||||
@ -542,6 +465,7 @@
|
||||
<commons-lang.version>3.5</commons-lang.version>
|
||||
<commons-text.version>1.1</commons-text.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>
|
||||
<javatuples.version>1.2</javatuples.version>
|
||||
<javaassist.version>3.21.0-GA</javaassist.version>
|
||||
@ -558,6 +482,7 @@
|
||||
<commons.io.version>2.5</commons.io.version>
|
||||
<flink.version>1.2.0</flink.version>
|
||||
<jackson.version>2.8.5</jackson.version>
|
||||
<neuroph.version>2.92</neuroph.version>
|
||||
<serenity.version>1.4.0</serenity.version>
|
||||
<serenity.jbehave.version>1.24.0</serenity.jbehave.version>
|
||||
<serenity.jira.version>1.1.3-rc.5</serenity.jira.version>
|
||||
@ -570,54 +495,7 @@
|
||||
<pact.version>3.5.0</pact.version>
|
||||
<awaitility.version>3.0.0</awaitility.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>
|
||||
<bytebuddy.version>1.7.1</bytebuddy.version>
|
||||
</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>
|
||||
|
@ -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.PredicateUtils;
|
||||
import org.apache.commons.collections4.TransformerUtils;
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
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.collection.IsMapContaining.hasEntry;
|
||||
import static org.hamcrest.collection.IsMapWithSize.aMapWithSize;
|
||||
@ -63,19 +68,7 @@ public class MapUtilsTest {
|
||||
|
||||
@Test
|
||||
public void whenVerbosePrintMap_thenMustPrintFormattedMap() {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
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);
|
||||
MapUtils.verbosePrint(System.out, "Optional Label", this.colorMap);
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -97,19 +90,12 @@ public class MapUtilsTest {
|
||||
@Test
|
||||
public void whenInvertMap_thenMustReturnInvertedMap() {
|
||||
Map<String, String> invColorMap = MapUtils.invertMap(this.colorMap);
|
||||
assertEquals(this.colorMap.size(), invColorMap.size());
|
||||
|
||||
MapIterator<String, String> itColorMap
|
||||
= MapUtils.iterableMap(this.colorMap).mapIterator();
|
||||
|
||||
while (itColorMap.hasNext()) {
|
||||
String colorMapKey = itColorMap.next();
|
||||
String colorMapValue = itColorMap.getValue();
|
||||
|
||||
String invColorMapValue = MapUtils.getString(invColorMap, colorMapValue);
|
||||
|
||||
assertTrue(invColorMapValue.equals(colorMapKey));
|
||||
}
|
||||
int size = invColorMap.size();
|
||||
Assertions.assertThat(invColorMap)
|
||||
.hasSameSizeAs(colorMap)
|
||||
.containsKeys(this.colorMap.values().toArray(new String[size]))
|
||||
.containsValues(this.colorMap.keySet().toArray(new String[size]));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
|
@ -4,6 +4,7 @@ package com.baeldung.hll;
|
||||
import com.google.common.hash.HashFunction;
|
||||
import com.google.common.hash.Hashing;
|
||||
import net.agkn.hll.HLL;
|
||||
import org.assertj.core.data.Offset;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.stream.LongStream;
|
||||
@ -15,8 +16,8 @@ public class HLLUnitTest {
|
||||
@Test
|
||||
public void givenHLL_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinality() {
|
||||
//given
|
||||
int numberOfElements = 100_000_000;
|
||||
int toleratedDifference = 1_000_000;
|
||||
long numberOfElements = 100_000_000;
|
||||
long toleratedDifference = 1_000_000;
|
||||
HashFunction hashFunction = Hashing.murmur3_128();
|
||||
HLL hll = new HLL(14, 5);
|
||||
|
||||
@ -29,14 +30,14 @@ public class HLLUnitTest {
|
||||
|
||||
//then
|
||||
long cardinality = hll.cardinality();
|
||||
assertThat(isSimilarTo(cardinality, numberOfElements, toleratedDifference)).isTrue();
|
||||
assertThat(cardinality).isCloseTo(numberOfElements, Offset.offset(toleratedDifference));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoHLLs_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinalityForUnionOfHLLs() {
|
||||
//given
|
||||
int numberOfElements = 100_000_000;
|
||||
int toleratedDifference = 1_000_000;
|
||||
long numberOfElements = 100_000_000;
|
||||
long toleratedDifference = 1_000_000;
|
||||
HashFunction hashFunction = Hashing.murmur3_128();
|
||||
HLL firstHll = new HLL(15, 5);
|
||||
HLL secondHLL = new HLL(15, 5);
|
||||
@ -57,12 +58,6 @@ public class HLLUnitTest {
|
||||
//then
|
||||
firstHll.union(secondHLL);
|
||||
long cardinality = firstHll.cardinality();
|
||||
assertThat(isSimilarTo(cardinality, numberOfElements * 2,
|
||||
toleratedDifference * 2)).isTrue();
|
||||
}
|
||||
|
||||
private boolean isSimilarTo(long cardinality, int numberOfElements, int maxToleratedDifference) {
|
||||
System.out.println(cardinality);
|
||||
return Math.abs(cardinality - numberOfElements) <= maxToleratedDifference;
|
||||
assertThat(cardinality).isCloseTo(numberOfElements * 2, Offset.offset(toleratedDifference * 2));
|
||||
}
|
||||
}
|
||||
|
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
@ -210,6 +210,7 @@
|
||||
<module>spring-zuul</module>
|
||||
<module>spring-reactor</module>
|
||||
<module>spring-vertx</module>
|
||||
|
||||
|
||||
<module>testing</module>
|
||||
<module>testng</module>
|
||||
@ -230,6 +231,7 @@
|
||||
<module>drools</module>
|
||||
<module>liquibase</module>
|
||||
<module>spring-boot-property-exp</module>
|
||||
<module>mockserver</module>
|
||||
</modules>
|
||||
|
||||
<dependencies>
|
||||
|
@ -14,15 +14,18 @@ import org.springframework.test.context.junit4.SpringRunner;
|
||||
import javax.servlet.FilterRegistration;
|
||||
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)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class)
|
||||
@AutoConfigureMockMvc
|
||||
@TestPropertySource(properties = { "security.basic.enabled=false" })
|
||||
@TestPropertySource(properties = {"security.basic.enabled=false"})
|
||||
public class SpringBootWithServletComponentIntegrationTest {
|
||||
|
||||
@Autowired private ServletContext servletContext;
|
||||
@Autowired
|
||||
private ServletContext servletContext;
|
||||
|
||||
@Test
|
||||
public void givenServletContext_whenAccessAttrs_thenFoundAttrsPutInServletListner() {
|
||||
@ -42,7 +45,8 @@ public class SpringBootWithServletComponentIntegrationTest {
|
||||
.contains("echo servlet"));
|
||||
}
|
||||
|
||||
@Autowired private TestRestTemplate restTemplate;
|
||||
@Autowired
|
||||
private TestRestTemplate restTemplate;
|
||||
|
||||
@Test
|
||||
public void givenServletFilter_whenGetHello_thenRequestFiltered() {
|
||||
@ -59,7 +63,6 @@ public class SpringBootWithServletComponentIntegrationTest {
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
@ -14,17 +14,21 @@ import org.springframework.test.context.junit4.SpringRunner;
|
||||
import javax.servlet.FilterRegistration;
|
||||
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)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class)
|
||||
@AutoConfigureMockMvc
|
||||
@TestPropertySource(properties = { "security.basic.enabled=false" })
|
||||
@TestPropertySource(properties = {"security.basic.enabled=false"})
|
||||
public class SpringBootWithoutServletComponentIntegrationTest {
|
||||
|
||||
@Autowired private ServletContext servletContext;
|
||||
@Autowired
|
||||
private ServletContext servletContext;
|
||||
|
||||
@Autowired private TestRestTemplate restTemplate;
|
||||
@Autowired
|
||||
private TestRestTemplate restTemplate;
|
||||
|
||||
@Test
|
||||
public void givenServletContext_whenAccessAttrs_thenNotFound() {
|
||||
|
@ -1,5 +1,8 @@
|
||||
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.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@ -7,13 +10,9 @@ import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
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)
|
||||
@SpringBootTest(classes = AutoconfigurationApplication.class)
|
||||
@EnableJpaRepositories(basePackages = { "com.baeldung.autoconfiguration.example" })
|
||||
@EnableJpaRepositories(basePackages = {"com.baeldung.autoconfiguration.example"})
|
||||
public class AutoconfigurationIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
|
@ -1,15 +1,5 @@
|
||||
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.runner.RunWith;
|
||||
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.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)
|
||||
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
@ -46,10 +44,10 @@ public class DisplayBeanIntegrationTest {
|
||||
public void givenRestTemplate_whenAccessServerUrl_thenHttpStatusOK() throws Exception {
|
||||
ResponseEntity<String> entity = this.testRestTemplate.getForEntity(
|
||||
"http://localhost:" + this.port + "/displayallbeans", String.class);
|
||||
|
||||
|
||||
then(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenRestTemplate_whenAccessEndpointUrl_thenHttpStatusOK() throws Exception {
|
||||
@SuppressWarnings("rawtypes")
|
||||
@ -68,14 +66,14 @@ public class DisplayBeanIntegrationTest {
|
||||
List<Map<String, Object>> allBeans = (List) ((Map) entity.getBody().get(0)).get("beans");
|
||||
List<String> beanNamesList = allBeans.stream().map(x -> (String) x.get("bean")).collect(Collectors.toList());
|
||||
|
||||
assertThat( beanNamesList, hasItem("fooController"));
|
||||
assertThat( beanNamesList, hasItem("fooService"));
|
||||
assertThat(beanNamesList, hasItem("fooController"));
|
||||
assertThat(beanNamesList, hasItem("fooService"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenWebApplicationContext_whenAccessGetBeanDefinitionNames_thenReturnsBeanNames() throws Exception {
|
||||
String[] beanNames = context.getBeanDefinitionNames();
|
||||
|
||||
|
||||
List<String> beanNamesList = Arrays.asList(beanNames);
|
||||
assertTrue(beanNamesList.contains("fooController"));
|
||||
assertTrue(beanNamesList.contains("fooService"));
|
||||
|
@ -18,7 +18,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@TestPropertySource(properties = { "security.basic.enabled=false" })
|
||||
@TestPropertySource(properties = {"security.basic.enabled=false"})
|
||||
public class AppLiveTest {
|
||||
|
||||
@Autowired
|
||||
@ -27,15 +27,15 @@ public class AppLiveTest {
|
||||
@Test
|
||||
public void getIndex() throws Exception {
|
||||
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(equalTo("Index Page")));
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(equalTo("Index Page")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getLocal() throws Exception {
|
||||
mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(equalTo("/local")));
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(equalTo("/local")));
|
||||
}
|
||||
|
||||
}
|
@ -1,9 +1,5 @@
|
||||
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.Test;
|
||||
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.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)
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = ToggleApplication.class)
|
||||
@AutoConfigureMockMvc
|
||||
|
@ -1,5 +1,6 @@
|
||||
package com.baeldung.utils;
|
||||
|
||||
import com.baeldung.utils.controller.UtilsController;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.InjectMocks;
|
||||
@ -10,32 +11,29 @@ 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.result.MockMvcResultMatchers.status;
|
||||
|
||||
|
||||
import com.baeldung.utils.controller.UtilsController;
|
||||
|
||||
public class UtilsControllerIntegrationTest {
|
||||
|
||||
@InjectMocks
|
||||
@InjectMocks
|
||||
private UtilsController utilsController;
|
||||
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController)
|
||||
.build();
|
||||
.build();
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception {
|
||||
String param = "testparam";
|
||||
this.mockMvc.perform(
|
||||
post("/setParam")
|
||||
.param("param", param)
|
||||
.sessionAttr("parameter", param))
|
||||
.andExpect(status().isOk());
|
||||
String param = "testparam";
|
||||
this.mockMvc.perform(
|
||||
post("/setParam")
|
||||
.param("param", param)
|
||||
.sessionAttr("parameter", param))
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
@ -6,11 +6,6 @@ import org.mockito.Mockito;
|
||||
import org.springframework.messaging.simp.stomp.StompHeaders;
|
||||
import org.springframework.messaging.simp.stomp.StompSession;
|
||||
|
||||
/**
|
||||
* Test class for MyStompSessionHandler
|
||||
* @author Kalyan
|
||||
*
|
||||
*/
|
||||
public class MyStompSessionHandlerIntegrationTest {
|
||||
|
||||
@Test
|
||||
|
@ -45,9 +45,9 @@ public class EmployeeControllerIntegrationTest {
|
||||
given(service.save(Mockito.anyObject())).willReturn(alex);
|
||||
|
||||
mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON)
|
||||
.content(JsonUtil.toJson(alex)))
|
||||
.andExpect(status().isCreated())
|
||||
.andExpect(jsonPath("$.name", is("alex")));
|
||||
.content(JsonUtil.toJson(alex)))
|
||||
.andExpect(status().isCreated())
|
||||
.andExpect(jsonPath("$.name", is("alex")));
|
||||
verify(service, VerificationModeFactory.times(1)).save(Mockito.anyObject());
|
||||
reset(service);
|
||||
}
|
||||
@ -63,11 +63,11 @@ public class EmployeeControllerIntegrationTest {
|
||||
given(service.getAllEmployees()).willReturn(allEmployees);
|
||||
|
||||
mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$", hasSize(3)))
|
||||
.andExpect(jsonPath("$[0].name", is(alex.getName())))
|
||||
.andExpect(jsonPath("$[1].name", is(john.getName())))
|
||||
.andExpect(jsonPath("$[2].name", is(bob.getName())));
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$", hasSize(3)))
|
||||
.andExpect(jsonPath("$[0].name", is(alex.getName())))
|
||||
.andExpect(jsonPath("$[1].name", is(john.getName())))
|
||||
.andExpect(jsonPath("$[2].name", is(bob.getName())));
|
||||
verify(service, VerificationModeFactory.times(1)).getAllEmployees();
|
||||
reset(service);
|
||||
}
|
||||
|
@ -1,9 +1,5 @@
|
||||
package org.baeldung.boot.boottest;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
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.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@DataJpaTest
|
||||
public class EmployeeRepositoryIntegrationTest {
|
||||
@ -65,7 +65,7 @@ public class EmployeeRepositoryIntegrationTest {
|
||||
List<Employee> allEmployees = employeeRepository.findAll();
|
||||
|
||||
assertThat(allEmployees).hasSize(3)
|
||||
.extracting(Employee::getName)
|
||||
.containsOnly(alex.getName(), ron.getName(), bob.getName());
|
||||
.extracting(Employee::getName)
|
||||
.containsOnly(alex.getName(), ron.getName(), bob.getName());
|
||||
}
|
||||
}
|
||||
|
@ -1,19 +1,5 @@
|
||||
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.junit.After;
|
||||
import org.junit.Test;
|
||||
@ -27,6 +13,20 @@ import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
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)
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = DemoApplication.class)
|
||||
@AutoConfigureMockMvc
|
||||
@ -49,11 +49,11 @@ public class EmployeeRestControllerIntegrationTest {
|
||||
public void whenValidInput_thenCreateEmployee() throws IOException, Exception {
|
||||
Employee bob = new Employee("bob");
|
||||
mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON)
|
||||
.content(JsonUtil.toJson(bob)));
|
||||
.content(JsonUtil.toJson(bob)));
|
||||
|
||||
List<Employee> found = repository.findAll();
|
||||
assertThat(found).extracting(Employee::getName)
|
||||
.containsOnly("bob");
|
||||
.containsOnly("bob");
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -63,12 +63,12 @@ public class EmployeeRestControllerIntegrationTest {
|
||||
createTestEmployee("alex");
|
||||
|
||||
mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2))))
|
||||
.andExpect(jsonPath("$[0].name", is("bob")))
|
||||
.andExpect(jsonPath("$[1].name", is("alex")));
|
||||
.andDo(print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2))))
|
||||
.andExpect(jsonPath("$[0].name", is("bob")))
|
||||
.andExpect(jsonPath("$[1].name", is("alex")));
|
||||
}
|
||||
|
||||
private void createTestEmployee(String name) {
|
||||
|
@ -1,10 +1,5 @@
|
||||
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.Test;
|
||||
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.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
public class EmployeeServiceImplIntegrationTest {
|
||||
|
||||
@ -44,27 +44,27 @@ public class EmployeeServiceImplIntegrationTest {
|
||||
List<Employee> allEmployees = Arrays.asList(john, bob, alex);
|
||||
|
||||
Mockito.when(employeeRepository.findByName(john.getName()))
|
||||
.thenReturn(john);
|
||||
.thenReturn(john);
|
||||
Mockito.when(employeeRepository.findByName(alex.getName()))
|
||||
.thenReturn(alex);
|
||||
.thenReturn(alex);
|
||||
Mockito.when(employeeRepository.findByName("wrong_name"))
|
||||
.thenReturn(null);
|
||||
.thenReturn(null);
|
||||
Mockito.when(employeeRepository.findById(john.getId()))
|
||||
.thenReturn(john);
|
||||
.thenReturn(john);
|
||||
Mockito.when(employeeRepository.findAll())
|
||||
.thenReturn(allEmployees);
|
||||
.thenReturn(allEmployees);
|
||||
Mockito.when(employeeRepository.findById(-99L))
|
||||
.thenReturn(null);
|
||||
.thenReturn(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidName_thenEmployeeShouldBeFound() {
|
||||
String name = "alex";
|
||||
Employee found = employeeService.getEmployeeByName(name);
|
||||
|
||||
assertThat(found.getName())
|
||||
|
||||
assertThat(found.getName())
|
||||
.isEqualTo(name);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInValidName_thenEmployeeShouldNotBeFound() {
|
||||
@ -114,25 +114,25 @@ public class EmployeeServiceImplIntegrationTest {
|
||||
List<Employee> allEmployees = employeeService.getAllEmployees();
|
||||
verifyFindAllEmployeesIsCalledOnce();
|
||||
assertThat(allEmployees).hasSize(3)
|
||||
.extracting(Employee::getName)
|
||||
.contains(alex.getName(), john.getName(), bob.getName());
|
||||
.extracting(Employee::getName)
|
||||
.contains(alex.getName(), john.getName(), bob.getName());
|
||||
}
|
||||
|
||||
private void verifyFindByNameIsCalledOnce(String name) {
|
||||
Mockito.verify(employeeRepository, VerificationModeFactory.times(1))
|
||||
.findByName(name);
|
||||
.findByName(name);
|
||||
Mockito.reset(employeeRepository);
|
||||
}
|
||||
|
||||
private void verifyFindByIdIsCalledOnce() {
|
||||
Mockito.verify(employeeRepository, VerificationModeFactory.times(1))
|
||||
.findById(Mockito.anyLong());
|
||||
.findById(Mockito.anyLong());
|
||||
Mockito.reset(employeeRepository);
|
||||
}
|
||||
|
||||
private void verifyFindAllEmployeesIsCalledOnce() {
|
||||
Mockito.verify(employeeRepository, VerificationModeFactory.times(1))
|
||||
.findAll();
|
||||
.findAll();
|
||||
Mockito.reset(employeeRepository);
|
||||
}
|
||||
}
|
||||
|
@ -1,10 +1,10 @@
|
||||
package org.baeldung.boot.boottest;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
class JsonUtil {
|
||||
static byte[] toJson(Object object) throws IOException {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
|
@ -115,7 +115,7 @@
|
||||
|
||||
<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>
|
||||
<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.data.mongodb.core.MongoOperations;
|
||||
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
|
||||
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
public class CascadeSaveMongoEventListener extends AbstractMongoEventListener<Object> {
|
||||
@ -11,7 +12,8 @@ public class CascadeSaveMongoEventListener extends AbstractMongoEventListener<Ob
|
||||
private MongoOperations mongoOperations;
|
||||
|
||||
@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));
|
||||
}
|
||||
}
|
@ -4,14 +4,16 @@ import org.baeldung.model.User;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.mongodb.core.MongoOperations;
|
||||
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
|
||||
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
|
||||
|
||||
public class UserCascadeSaveMongoEventListener extends AbstractMongoEventListener<Object> {
|
||||
@Autowired
|
||||
private MongoOperations mongoOperations;
|
||||
|
||||
@Override
|
||||
public void onBeforeConvert(final Object source) {
|
||||
if (source instanceof User && ((User) source).getEmailAddress() != null) {
|
||||
public void onBeforeConvert(final BeforeConvertEvent<Object> event) {
|
||||
final Object source = event.getSource();
|
||||
if ((source instanceof User) && (((User) source).getEmailAddress() != null)) {
|
||||
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;
|
||||
|
||||
}
|
||||
}
|
||||
|
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