Merge branch 'master' into master

This commit is contained in:
Ahmed Tawila 2017-08-09 07:48:06 +03:00 committed by GitHub
commit 1fdbaa24d7
185 changed files with 3682 additions and 803 deletions

11
bootique/config.yml Normal file
View File

@ -0,0 +1,11 @@
log:
level: warn
appenders:
- type: file
logFormat: '%c{20}: %m%n'
file: /home/logger.log
jetty:
context: /hello
connector:
port: 10001

View File

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>bootique-parent</artifactId>
<groupId>io.bootique.parent</groupId>
<version>0.12</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.bootique</groupId>
<artifactId>bootique</artifactId>
<name>bootique</name>
<version>1.0-SNAPSHOT</version>
<url>http://maven.apache.org</url>
<build>
<plugins>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>io.bootique</groupId>
<artifactId>bootique-test</artifactId>
<version>0.23</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.bootique.bom</groupId>
<artifactId>bootique-bom</artifactId>
<version>0.23</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<properties>
<main.class>com.baeldung.bootique.App</main.class>
</properties>
</project>

66
bootique/pom.xml Normal file
View File

@ -0,0 +1,66 @@
<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.bootique</groupId>
<artifactId>bootique</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>bootique</name>
<url>http://maven.apache.org</url>
<properties>
<main.class>com.baeldung.bootique.App</main.class>
</properties>
<parent>
<groupId>io.bootique.parent</groupId>
<artifactId>bootique-parent</artifactId>
<version>0.12</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.bootique.bom</groupId>
<artifactId>bootique-bom</artifactId>
<version>0.23</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.bootique.jersey</groupId>
<artifactId>bootique-jersey</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.bootique.logback</groupId>
<artifactId>bootique-logback</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.bootique</groupId>
<artifactId>bootique-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,41 @@
package com.baeldung.bootique;
import com.baeldung.bootique.module.ModuleBinder;
import com.baeldung.bootique.router.IndexController;
import com.baeldung.bootique.router.SaveController;
import com.google.inject.Module;
import io.bootique.Bootique;
import io.bootique.jersey.JerseyModule;
import io.bootique.log.BootLogger;
import java.util.function.Supplier;
public class App {
public static void main(String[] args) {
Module module = binder -> JerseyModule.extend(binder).addResource(IndexController.class)
.addResource(SaveController.class);
Bootique.app(args).module(module).module(ModuleBinder.class).bootLogger(new BootLogger() {
@Override
public void trace(Supplier<String> arg0) {
// ...
}
@Override
public void stdout(String arg0) {
// ...
}
@Override
public void stderr(String arg0, Throwable arg1) {
// ...
}
@Override
public void stderr(String arg0) {
// ...
}
}).autoLoadModules().exec();
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.bootique.module;
import com.baeldung.bootique.service.HelloService;
import com.baeldung.bootique.service.impl.HelloServiceImpl;
import com.google.inject.Binder;
import com.google.inject.Module;
public class ModuleBinder implements Module {
@Override
public void configure(Binder binder) {
binder.bind(HelloService.class).to(HelloServiceImpl.class);
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.bootique.module;
import com.google.inject.Module;
import io.bootique.BQModuleProvider;
public class ModuleProvider implements BQModuleProvider {
@Override
public Module module() {
return new ModuleBinder();
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.bootique.router;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@Path("/")
public class IndexController {
@GET
public String index() {
return "Hello, baeldung!";
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.bootique.router;
import com.baeldung.bootique.service.HelloService;
import com.google.inject.Inject;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
@Path("/save")
public class SaveController {
@Inject
HelloService helloService;
@POST
public String save() {
return "Data Saved!";
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.bootique.service;
public interface HelloService {
boolean save();
}

View File

@ -0,0 +1,12 @@
package com.baeldung.bootique.service.impl;
import com.baeldung.bootique.service.HelloService;
public class HelloServiceImpl implements HelloService {
@Override
public boolean save() {
return true;
}
}

View File

@ -0,0 +1 @@
com.baeldung.bootique.module.ModuleProvider

View File

@ -0,0 +1,27 @@
package com.baeldung.bootique;
import com.baeldung.bootique.service.HelloService;
import io.bootique.BQRuntime;
import io.bootique.test.junit.BQDaemonTestFactory;
import io.bootique.test.junit.BQTestFactory;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class AppTest {
@Rule
public BQTestFactory bqTestFactory = new BQTestFactory();
@Rule
public BQDaemonTestFactory bqDaemonTestFactory = new BQDaemonTestFactory();
@Test
public void givenService_expectBoolen() {
BQRuntime runtime = bqTestFactory.app("--server").autoLoadModules().createRuntime();
HelloService service = runtime.getInstance(HelloService.class);
assertEquals(true, service.save());
}
}

View File

@ -1,39 +0,0 @@
<?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>

View File

@ -1,30 +0,0 @@
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());
}
}

View File

@ -80,7 +80,11 @@
</dependency> </dependency>
<!-- logging --> <!-- logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId> <artifactId>slf4j-api</artifactId>
@ -391,7 +395,7 @@
<logback.version>1.1.7</logback.version> <logback.version>1.1.7</logback.version>
<!-- util --> <!-- util -->
<guava.version>21.0</guava.version> <guava.version>22.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version> <commons-lang3.version>3.5</commons-lang3.version>
<bouncycastle.version>1.55</bouncycastle.version> <bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version> <commons-codec.version>1.10</commons-codec.version>

View File

@ -15,14 +15,12 @@ public class CyclicBarrierDemo {
private int NUM_PARTIAL_RESULTS; private int NUM_PARTIAL_RESULTS;
private int NUM_WORKERS; private int NUM_WORKERS;
private void runSimulation(int numWorkers, int numberOfPartialResults) { private void runSimulation(int numWorkers, int numberOfPartialResults) {
NUM_PARTIAL_RESULTS = numberOfPartialResults; NUM_PARTIAL_RESULTS = numberOfPartialResults;
NUM_WORKERS = numWorkers; NUM_WORKERS = numWorkers;
cyclicBarrier = new CyclicBarrier(NUM_WORKERS, new AggregatorThread()); cyclicBarrier = new CyclicBarrier(NUM_WORKERS, new AggregatorThread());
System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute " System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute " + NUM_PARTIAL_RESULTS + " partial results each");
+ NUM_PARTIAL_RESULTS + " partial results each");
for (int i = 0; i < NUM_WORKERS; i++) { for (int i = 0; i < NUM_WORKERS; i++) {
Thread worker = new Thread(new NumberCruncherThread()); Thread worker = new Thread(new NumberCruncherThread());
worker.setName("Thread " + i); worker.setName("Thread " + i);
@ -38,8 +36,7 @@ public class CyclicBarrierDemo {
List<Integer> partialResult = new ArrayList<>(); List<Integer> partialResult = new ArrayList<>();
for (int i = 0; i < NUM_PARTIAL_RESULTS; i++) { for (int i = 0; i < NUM_PARTIAL_RESULTS; i++) {
Integer num = random.nextInt(10); Integer num = random.nextInt(10);
System.out.println(thisThreadName System.out.println(thisThreadName + ": Crunching some numbers! Final result - " + num);
+ ": Crunching some numbers! Final result - " + num);
partialResult.add(num); partialResult.add(num);
} }
partialResults.add(partialResult); partialResults.add(partialResult);
@ -57,13 +54,12 @@ public class CyclicBarrierDemo {
@Override @Override
public void run() { public void run() {
String thisThreadName = Thread.currentThread().getName(); String thisThreadName = Thread.currentThread().getName();
System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS + " workers, having " + NUM_PARTIAL_RESULTS + " results each.");
+ " workers, having " + NUM_PARTIAL_RESULTS + " results each.");
int sum = 0; int sum = 0;
for (List<Integer> threadResult : partialResults) { for (List<Integer> threadResult : partialResults) {
System.out.print("Adding "); System.out.print("Adding ");
for (Integer partialResult : threadResult) { for (Integer partialResult : threadResult) {
System.out.print(partialResult+" "); System.out.print(partialResult + " ");
sum += partialResult; sum += partialResult;
} }
System.out.println(); System.out.println();

View File

@ -15,7 +15,8 @@ public class Philosopher implements Runnable {
Thread.sleep(((int) (Math.random() * 100))); Thread.sleep(((int) (Math.random() * 100)));
} }
@Override public void run() { @Override
public void run() {
try { try {
while (true) { while (true) {
doAction(System.nanoTime() + ": Thinking"); // thinking doAction(System.nanoTime() + ": Thinking"); // thinking

View File

@ -6,22 +6,22 @@ import java.util.concurrent.TimeUnit;
public class ExecutorServiceDemo { public class ExecutorServiceDemo {
ExecutorService executor = Executors.newFixedThreadPool(10); ExecutorService executor = Executors.newFixedThreadPool(10);
public void execute() { public void execute() {
executor.submit(() -> { executor.submit(() -> {
new Task(); new Task();
}); });
executor.shutdown(); executor.shutdown();
executor.shutdownNow(); executor.shutdownNow();
try { try {
executor.awaitTermination(20l, TimeUnit.NANOSECONDS); executor.awaitTermination(20l, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }

View File

@ -9,36 +9,36 @@ import java.util.concurrent.TimeoutException;
public class FutureDemo { public class FutureDemo {
public String invoke() { public String invoke() {
String str = null; String str = null;
ExecutorService executorService = Executors.newFixedThreadPool(10); ExecutorService executorService = Executors.newFixedThreadPool(10);
Future<String> future = executorService.submit(() -> { Future<String> future = executorService.submit(() -> {
// Task // Task
Thread.sleep(10000l); Thread.sleep(10000l);
return "Hellow world"; return "Hellow world";
}); });
future.cancel(false); future.cancel(false);
try { try {
future.get(20, TimeUnit.SECONDS); future.get(20, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e1) { } catch (InterruptedException | ExecutionException | TimeoutException e1) {
e1.printStackTrace(); e1.printStackTrace();
} }
if (future.isDone() && !future.isCancelled()) { if (future.isDone() && !future.isCancelled()) {
try { try {
str = future.get(); str = future.get();
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
return str; return str;
} }
} }

View File

@ -4,20 +4,20 @@ import java.util.concurrent.ThreadFactory;
public class BaeldungThreadFactory implements ThreadFactory { public class BaeldungThreadFactory implements ThreadFactory {
private int threadId; private int threadId;
private String name; private String name;
public BaeldungThreadFactory(String name) { public BaeldungThreadFactory(String name) {
threadId = 1; threadId = 1;
this.name = name; this.name = name;
} }
@Override @Override
public Thread newThread(Runnable r) { public Thread newThread(Runnable r) {
Thread t = new Thread(r, name + "-Thread_" + threadId); Thread t = new Thread(r, name + "-Thread_" + threadId);
System.out.println("created new thread with id : " + threadId + " and name : " + t.getName()); System.out.println("created new thread with id : " + threadId + " and name : " + t.getName());
threadId++; threadId++;
return t; return t;
} }
} }

View File

@ -2,9 +2,9 @@ package com.baeldung.concurrent.threadfactory;
public class Task implements Runnable { public class Task implements Runnable {
@Override @Override
public void run() { public void run() {
// task details // task details
} }
} }

View File

@ -0,0 +1,13 @@
package com.baeldung.designpatterns.adapter;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class AdapterPatternDriver {
public static void main(String args[]) {
LuxuryCarsSpeedAdapter luxuryCars = new LuxuryCarsSpeedAdapterImpl();
LOG.info("Bugatti Veyron Super Sport's top speed is " + luxuryCars.bugattiVeyronInKMPH() + " Kmph.");
LOG.info("McLaren F1 top speed is " + luxuryCars.mcLarenInKMPH() + " Kmph.");
LOG.info("Aston Martin One-77 top speed is " + luxuryCars.astonMartinInKMPH() + " Kmph.");
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.designpatterns.adapter;
public class LuxuryCarsSpeed {
public double bugattiVeyronInMPH() {
return 268;
}
public double mcLarenInMPH() {
return 241;
}
public double astonMartinInMPH() {
return 220;
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.designpatterns.adapter;
public interface LuxuryCarsSpeedAdapter {
public double bugattiVeyronInKMPH();
public double mcLarenInKMPH();
public double astonMartinInKMPH();
}

View File

@ -0,0 +1,26 @@
package com.baeldung.designpatterns.adapter;
public class LuxuryCarsSpeedAdapterImpl extends LuxuryCarsSpeed implements LuxuryCarsSpeedAdapter {
@Override
public double bugattiVeyronInKMPH() {
double mph = super.bugattiVeyronInMPH();
return convertMPHtoKMPH(mph);
}
@Override
public double mcLarenInKMPH() {
double mph = super.mcLarenInMPH();
return convertMPHtoKMPH(mph);
}
@Override
public double astonMartinInKMPH() {
double mph = super.astonMartinInMPH();
return convertMPHtoKMPH(mph);
}
private double convertMPHtoKMPH(double mph) {
return mph * 1.60934;
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.designpatterns.bridge;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class Blue implements Color {
@Override
public void fillColor() {
LOG.info("Color : Blue");
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.designpatterns.bridge;
public class BridgePatternDriver {
public static void main(String[] args) {
//a square with red color
Shape square = new Square(new Red());
square.drawShape();
//a triangle with blue color
Shape triangle = new Triangle(new Blue());
triangle.drawShape();
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.designpatterns.bridge;
public interface Color {
public void fillColor();
}

View File

@ -0,0 +1,12 @@
package com.baeldung.designpatterns.bridge;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class Red implements Color {
@Override
public void fillColor() {
LOG.info("Color : Red");
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.designpatterns.bridge;
public abstract class Shape {
protected Color color;
public Shape(Color color) {
this.color = color;
}
abstract public void drawShape();
}

View File

@ -0,0 +1,16 @@
package com.baeldung.designpatterns.bridge;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class Square extends Shape {
public Square(Color color) {
super(color);
}
@Override
public void drawShape() {
LOG.info("Square drawn. ");
color.fillColor();
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.designpatterns.bridge;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class Triangle extends Shape {
public Triangle(Color color) {
super(color);
}
@Override
public void drawShape() {
LOG.info("Triangle drawn. ");
color.fillColor();
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.designpatterns.decorator;
public class BubbleLights extends TreeDecorator {
public BubbleLights(ChristmasTree tree) {
super(tree);
}
public String decorate() {
return super.decorate() + decorateWithBubbleLights();
}
private String decorateWithBubbleLights() {
return " with Bubble Lights";
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.designpatterns.decorator;
public interface ChristmasTree {
public String decorate();
}

View File

@ -0,0 +1,10 @@
package com.baeldung.designpatterns.decorator;
public class ChristmasTreeImpl implements ChristmasTree {
@Override
public String decorate() {
return "Christmas tree";
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.designpatterns.decorator;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class DecoratorPatternDriver {
public static void main(String[] args) {
//christmas tree with just one Garland
ChristmasTree tree1 = new Garland(new ChristmasTreeImpl());
LOG.info(tree1.decorate());
//christmas tree with two Garlands and one Bubble lights
ChristmasTree tree2 = new BubbleLights(new Garland(
new Garland(new ChristmasTreeImpl()))
);
LOG.info(tree2.decorate());
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.designpatterns.decorator;
public class Garland extends TreeDecorator {
public Garland(ChristmasTree tree) {
super(tree);
}
public String decorate() {
return super.decorate() + decorateWithGarland();
}
private String decorateWithGarland() {
return " with Garland";
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.designpatterns.decorator;
public abstract class TreeDecorator implements ChristmasTree {
private ChristmasTree tree;
public TreeDecorator(ChristmasTree tree) {
this.tree = tree;
}
@Override
public String decorate() {
return tree.decorate();
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.designpatterns.proxy;
public interface ExpensiveObject {
public void process();
}

View File

@ -0,0 +1,20 @@
package com.baeldung.designpatterns.proxy;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;;
public class ExpensiveObjectImpl implements ExpensiveObject {
public ExpensiveObjectImpl() {
heavyInitialConfiguration();
}
@Override
public void process() {
LOG.info("processing complete.");
}
private void heavyInitialConfiguration() {
LOG.info("Loading initial configuration...");
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.designpatterns.proxy;
public class ExpensiveObjectProxy implements ExpensiveObject{
private static ExpensiveObject object;
@Override
public void process() {
if(object == null) {
object = new ExpensiveObjectImpl();
}
object.process();
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.designpatterns.proxy;
public class ProxyPatternDriver {
public static void main(String[] args) {
ExpensiveObject object = new ExpensiveObjectProxy();
object.process();
object.process();
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.designpatterns.singleton;
public class ClassSingleton {
private static ClassSingleton INSTANCE;
private String info = "Initial class info";
private ClassSingleton(){
}
public static ClassSingleton getInstance(){
if(INSTANCE == null){
INSTANCE = new ClassSingleton();
}
return INSTANCE;
}
// getters and setters
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.designpatterns.singleton;
public enum EnumSingleton {
INSTANCE("Initial enum info"); //Name of the single instance
private String info;
private EnumSingleton(String info) {
this.info = info;
}
public EnumSingleton getInstance(){
return INSTANCE;
}
//getters and setters
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.designpatterns.singleton;
public class Sandbox {
public static void main(String[] args) {
//Class singleton
ClassSingleton classSingleton1 = ClassSingleton.getInstance();
//OurSingleton object1 = new OurSingleton(); // The constructor OurSingleton() is not visible
System.out.println(classSingleton1.getInfo()); //Initial class info
ClassSingleton classSingleton2 = ClassSingleton.getInstance();
classSingleton2.setInfo("New class info");
System.out.println(classSingleton1.getInfo()); //New class info
System.out.println(classSingleton2.getInfo()); //New class info
//Enum singleton
EnumSingleton enumSingleton1 = EnumSingleton.INSTANCE.getInstance();
System.out.println(enumSingleton1.getInfo()); //Initial enum info
EnumSingleton enumSingleton2 = EnumSingleton.INSTANCE.getInstance();
enumSingleton2.setInfo("New enum info");
System.out.println(enumSingleton1.getInfo()); //New enum info
System.out.println(enumSingleton2.getInfo()); //New enum info
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.designpatterns.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class LogerUtil {
public final static Logger LOG = Logger.getLogger("GLOBAL");
static {
configuration();
}
private static void configuration() {
Properties props = new Properties();
try {
props.load(
new BufferedReader(
new InputStreamReader(
LogerUtil.class.getResourceAsStream("/log4jstructuraldp.properties")
)
)
);
} catch (IOException e) {
System.out.println("log4jstructuraldp.properties file not configured properly");
System.exit(0);
}
PropertyConfigurator.configure(props);
}
}

View File

@ -14,26 +14,25 @@ public class LookupFSJNDI {
super(); super();
init(); init();
} }
private void init() throws NamingException { private void init() throws NamingException {
Hashtable<String, String> env = new Hashtable<String, String>(); Hashtable<String, String> env = new Hashtable<String, String>();
env.put (Context.INITIAL_CONTEXT_FACTORY, env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
"com.sun.jndi.fscontext.RefFSContextFactory");
// URI to namespace (actual directory) // URI to namespace (actual directory)
env.put(Context.PROVIDER_URL, "file:./src/test/resources"); env.put(Context.PROVIDER_URL, "file:./src/test/resources");
ctx = new InitialContext(env); ctx = new InitialContext(env);
} }
public InitialContext getCtx() { public InitialContext getCtx() {
return ctx; return ctx;
} }
public File getFile(String fileName) { public File getFile(String fileName) {
File file; File file;
try { try {
file = (File)getCtx().lookup(fileName); file = (File) getCtx().lookup(fileName);
} catch (NamingException e) { } catch (NamingException e) {
file = null; file = null;
} }

View File

@ -1,4 +1,4 @@
package com.baeldung.entities; package com.baeldung.hashcode.entities;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -18,13 +18,16 @@ public class User {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o)
if (o == null) return false; return true;
if (this.getClass() != o.getClass()) return false; if (o == null)
return false;
if (this.getClass() != o.getClass())
return false;
User user = (User) o; User user = (User) o;
return id != user.id && (!name.equals(user.name) && !email.equals(user.email)); return id != user.id && (!name.equals(user.name) && !email.equals(user.email));
} }
@Override @Override
public int hashCode() { public int hashCode() {
int hash = 7; int hash = 7;

View File

@ -10,7 +10,6 @@ public class JMXTutorialMainlauncher {
private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class); private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class);
public static void main(String[] args) { public static void main(String[] args) {
// TODO Auto-generated method stub // TODO Auto-generated method stub

View File

@ -8,9 +8,8 @@ import java.net.*;
public class EchoClient { public class EchoClient {
private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class); private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class);
private Socket clientSocket; private Socket clientSocket;
private PrintWriter out; private PrintWriter out;
private BufferedReader in; private BufferedReader in;

View File

@ -1,6 +1,5 @@
package com.baeldung.stream; package com.baeldung.stream;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;

View File

@ -12,15 +12,10 @@ class StringHelper {
} }
static String removeLastCharOptional(String s) { static String removeLastCharOptional(String s) {
return Optional.ofNullable(s) return Optional.ofNullable(s).filter(str -> str.length() != 0).map(str -> str.substring(0, str.length() - 1)).orElse(s);
.filter(str -> str.length() != 0)
.map(str -> str.substring(0, str.length() - 1))
.orElse(s);
} }
static String removeLastCharRegexOptional(String s) { static String removeLastCharRegexOptional(String s) {
return Optional.ofNullable(s) return Optional.ofNullable(s).map(str -> str.replaceAll(".$", "")).orElse(s);
.map(str -> str.replaceAll(".$", ""))
.orElse(s);
} }
} }

View File

@ -25,11 +25,7 @@ public class MyTokenizer {
} }
public List<String> getTokensWithCollection(String str) { public List<String> getTokensWithCollection(String str) {
return Collections return Collections.list(new StringTokenizer(str, ",")).stream().map(token -> (String) token).collect(Collectors.toList());
.list(new StringTokenizer(str, ","))
.stream()
.map(token -> (String) token)
.collect(Collectors.toList());
} }
public List<String> getTokensFromFile(String path, String delim) { public List<String> getTokensFromFile(String path, String delim) {

View File

@ -11,12 +11,12 @@ public class CustomTemporalAdjuster implements TemporalAdjuster {
@Override @Override
public Temporal adjustInto(Temporal temporal) { public Temporal adjustInto(Temporal temporal) {
switch (DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK))) { switch (DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK))) {
case FRIDAY: case FRIDAY:
return temporal.plus(3, ChronoUnit.DAYS); return temporal.plus(3, ChronoUnit.DAYS);
case SATURDAY: case SATURDAY:
return temporal.plus(2, ChronoUnit.DAYS); return temporal.plus(2, ChronoUnit.DAYS);
default: default:
return temporal.plus(1, ChronoUnit.DAYS); return temporal.plus(1, ChronoUnit.DAYS);
} }
} }
} }

View File

@ -9,7 +9,6 @@ import java.util.concurrent.atomic.AtomicInteger;
public class Consumer implements Runnable { public class Consumer implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(Consumer.class); private static final Logger LOG = LoggerFactory.getLogger(Consumer.class);
private final TransferQueue<String> transferQueue; private final TransferQueue<String> transferQueue;
private final String name; private final String name;
private final int numberOfMessagesToConsume; private final int numberOfMessagesToConsume;

View File

@ -0,0 +1,9 @@
# Root logger
log4j.rootLogger=INFO, file, stdout
# Write to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

View File

@ -15,28 +15,24 @@ public class LongAccumulatorUnitTest {
@Test @Test
public void givenLongAccumulator_whenApplyActionOnItFromMultipleThrads_thenShouldProduceProperResult() throws InterruptedException { public void givenLongAccumulator_whenApplyActionOnItFromMultipleThrads_thenShouldProduceProperResult() throws InterruptedException {
//given // given
ExecutorService executorService = Executors.newFixedThreadPool(8); ExecutorService executorService = Executors.newFixedThreadPool(8);
LongBinaryOperator sum = Long::sum; LongBinaryOperator sum = Long::sum;
LongAccumulator accumulator = new LongAccumulator(sum, 0L); LongAccumulator accumulator = new LongAccumulator(sum, 0L);
int numberOfThreads = 4; int numberOfThreads = 4;
int numberOfIncrements = 100; int numberOfIncrements = 100;
//when // when
Runnable accumulateAction = () -> IntStream Runnable accumulateAction = () -> IntStream.rangeClosed(0, numberOfIncrements).forEach(accumulator::accumulate);
.rangeClosed(0, numberOfIncrements)
.forEach(accumulator::accumulate);
for (int i = 0; i < numberOfThreads; i++) { for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(accumulateAction); executorService.execute(accumulateAction);
} }
// then
//then
executorService.awaitTermination(500, TimeUnit.MILLISECONDS); executorService.awaitTermination(500, TimeUnit.MILLISECONDS);
executorService.shutdown(); executorService.shutdown();
assertEquals(accumulator.get(), 20200); assertEquals(accumulator.get(), 20200);
} }
} }

View File

@ -0,0 +1,20 @@
package com.baeldung.designpatterns;
import static org.junit.Assert.*;
import org.junit.Test;
import com.baeldung.designpatterns.adapter.LuxuryCarsSpeedAdapter;
import com.baeldung.designpatterns.adapter.LuxuryCarsSpeedAdapterImpl;
public class AdapterPatternIntegrationTest {
@Test
public void givenLuxuryCarsAdapter_WhenConvertingMPHToKMPH_thenSuccessfullyConverted() {
LuxuryCarsSpeedAdapter luxuryCars = new LuxuryCarsSpeedAdapterImpl();
assertEquals(luxuryCars.bugattiVeyronInKMPH(), 431.30312, 0.00001);
assertEquals(luxuryCars.mcLarenInKMPH(), 387.85094, 0.00001);
assertEquals(luxuryCars.astonMartinInKMPH(), 354.0548, 0.00001);
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.designpatterns;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.designpatterns.bridge.Blue;
import com.baeldung.designpatterns.bridge.Red;
import com.baeldung.designpatterns.bridge.Shape;
import com.baeldung.designpatterns.bridge.Square;
import com.baeldung.designpatterns.bridge.Triangle;
public class BridgePatternIntegrationTest {
public static TestAppenderDP appender;
@Before
public void setUp() {
appender = new TestAppenderDP();
LOG.addAppender(appender);
}
@Test
public void whenBridgePatternInvoked_thenConfigSuccess() {
//a square with red color
Shape square = new Square(new Red());
square.drawShape();
//a triangle with blue color
Shape triangle = new Triangle(new Blue());
triangle.drawShape();
final List<LoggingEvent> log = appender.getLog();
assertThat((String) log.get(0).getMessage(), is("Square drawn. "));
assertThat((String) log.get(1).getMessage(), is("Color : Red"));
assertThat((String) log.get(2).getMessage(), is("Triangle drawn. "));
assertThat((String) log.get(3).getMessage(), is("Color : Blue"));
}
@After
public void tearDown() {
LOG.removeAppender(appender);
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.designpatterns;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.baeldung.designpatterns.decorator.BubbleLights;
import com.baeldung.designpatterns.decorator.ChristmasTree;
import com.baeldung.designpatterns.decorator.ChristmasTreeImpl;
import com.baeldung.designpatterns.decorator.Garland;
public class DecoratorPatternIntegrationTest {
private ChristmasTree tree;
@Test
public void givenDecoratorPattern_WhenDecoratorsInjectedAtRuntime_thenConfigSuccess() {
//christmas tree with just one Garland
tree = new Garland(new ChristmasTreeImpl());
assertEquals(tree.decorate(), "Christmas tree with Garland");
//christmas tree with two Garlands and one Bubble lights
tree = new BubbleLights(new Garland(
new Garland(new ChristmasTreeImpl()))
);
assertEquals(tree.decorate(), "Christmas tree with Garland with Garland with Bubble Lights");
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.designpatterns;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.designpatterns.proxy.ExpensiveObject;
import com.baeldung.designpatterns.proxy.ExpensiveObjectProxy;
public class ProxyPatternIntegrationTest {
public static TestAppenderDP appender;
@Before
public void setUp() {
appender = new TestAppenderDP();
LOG.addAppender(appender);
}
@Test
public void givenExpensiveObjectProxy_WhenObjectInitialized_thenInitializedOnlyOnce() {
ExpensiveObject object = new ExpensiveObjectProxy();
object.process();
object.process();
final List<LoggingEvent> log = appender.getLog();
assertThat((String) log.get(0).getMessage(), is("Loading initial configuration..."));
assertThat((String) log.get(1).getMessage(), is("processing complete."));
assertThat((String) log.get(2).getMessage(), is("processing complete."));
}
@After
public void tearDown() {
LOG.removeAppender(appender);
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.designpatterns;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
public class TestAppenderDP extends AppenderSkeleton {
private final List<LoggingEvent> log = new ArrayList<LoggingEvent>();
@Override
public boolean requiresLayout() {
return false;
}
@Override
protected void append(final LoggingEvent loggingEvent) {
log.add(loggingEvent);
}
@Override
public void close() {
}
public List<LoggingEvent> getLog() {
return new ArrayList<LoggingEvent>(log);
}
}

View File

@ -1,12 +1,17 @@
package com.baeldung.application; package com.baeldung.hashcode.application;
import com.baeldung.hashcode.entities.User;
import org.junit.Test;
import com.baeldung.entities.User;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class Application { import static org.junit.Assert.assertTrue;
public static void main(String[] args) { public class ApplicationTest {
@Test
public void main_NoInputState_TextPrintedToConsole() throws Exception {
Map<User, User> users = new HashMap<>(); Map<User, User> users = new HashMap<>();
User user1 = new User(1L, "John", "john@domain.com"); User user1 = new User(1L, "John", "john@domain.com");
User user2 = new User(2L, "Jennifer", "jennifer@domain.com"); User user2 = new User(2L, "Jennifer", "jennifer@domain.com");
@ -16,8 +21,6 @@ public class Application {
users.put(user2, user2); users.put(user2, user2);
users.put(user3, user3); users.put(user3, user3);
if (users.containsKey(user1)) { assertTrue(users.containsKey(user1));
System.out.print("User found in the collection");
}
} }
} }

View File

@ -1,4 +1,4 @@
package com.baeldung.entities; package com.baeldung.hashcode.entities;
import org.junit.After; import org.junit.After;
import org.junit.Assert; import org.junit.Assert;
@ -23,7 +23,7 @@ public class UserTest {
} }
@Test @Test
public void equals_EqualUserInstance_TrueAssertion(){ public void equals_EqualUserInstance_TrueAssertion() {
Assert.assertTrue(user.equals(comparisonUser)); Assert.assertTrue(user.equals(comparisonUser));
} }

View File

@ -15,7 +15,6 @@ public class LambdaExceptionWrappersUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(LambdaExceptionWrappersUnitTest.class); private static final Logger LOG = LoggerFactory.getLogger(LambdaExceptionWrappersUnitTest.class);
private List<Integer> integers; private List<Integer> integers;
@Before @Before

View File

@ -29,12 +29,9 @@ public class ListOfListsUnitTest {
@Test @Test
public void givenListOfLists_thenCheckNames() { public void givenListOfLists_thenCheckNames() {
assertEquals("Pen 1", ((Pen) listOfLists.get(0) assertEquals("Pen 1", ((Pen) listOfLists.get(0).get(0)).getName());
.get(0)).getName()); assertEquals("Pencil 1", ((Pencil) listOfLists.get(1).get(0)).getName());
assertEquals("Pencil 1", ((Pencil) listOfLists.get(1) assertEquals("Rubber 1", ((Rubber) listOfLists.get(2).get(0)).getName());
.get(0)).getName());
assertEquals("Rubber 1", ((Rubber) listOfLists.get(2)
.get(0)).getName());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -43,11 +40,9 @@ public class ListOfListsUnitTest {
((ArrayList<Pencil>) listOfLists.get(1)).remove(0); ((ArrayList<Pencil>) listOfLists.get(1)).remove(0);
listOfLists.remove(1); listOfLists.remove(1);
assertEquals("Rubber 1", ((Rubber) listOfLists.get(1) assertEquals("Rubber 1", ((Rubber) listOfLists.get(1).get(0)).getName());
.get(0)).getName());
listOfLists.remove(0); listOfLists.remove(0);
assertEquals("Rubber 1", ((Rubber) listOfLists.get(0) assertEquals("Rubber 1", ((Rubber) listOfLists.get(0).get(0)).getName());
.get(0)).getName());
} }
@Test @Test
@ -67,11 +62,8 @@ public class ListOfListsUnitTest {
list.add(pencils); list.add(pencils);
list.add(rubbers); list.add(rubbers);
assertEquals("Pen 1", ((Pen) list.get(0) assertEquals("Pen 1", ((Pen) list.get(0).get(0)).getName());
.get(0)).getName()); assertEquals("Pencil 1", ((Pencil) list.get(1).get(0)).getName());
assertEquals("Pencil 1", ((Pencil) list.get(1) assertEquals("Rubber 1", ((Rubber) list.get(2).get(0)).getName());
.get(0)).getName());
assertEquals("Rubber 1", ((Rubber) list.get(2)
.get(0)).getName());
} }
} }

View File

@ -1,190 +1,190 @@
package com.baeldung.money; package com.baeldung.money;
import org.javamoney.moneta.FastMoney; import org.javamoney.moneta.FastMoney;
import org.javamoney.moneta.Money; import org.javamoney.moneta.Money;
import org.javamoney.moneta.format.CurrencyStyle; import org.javamoney.moneta.format.CurrencyStyle;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import javax.money.CurrencyUnit; import javax.money.CurrencyUnit;
import javax.money.Monetary; import javax.money.Monetary;
import javax.money.MonetaryAmount; import javax.money.MonetaryAmount;
import javax.money.UnknownCurrencyException; import javax.money.UnknownCurrencyException;
import javax.money.convert.CurrencyConversion; import javax.money.convert.CurrencyConversion;
import javax.money.convert.MonetaryConversions; import javax.money.convert.MonetaryConversions;
import javax.money.format.AmountFormatQueryBuilder; import javax.money.format.AmountFormatQueryBuilder;
import javax.money.format.MonetaryAmountFormat; import javax.money.format.MonetaryAmountFormat;
import javax.money.format.MonetaryFormats; import javax.money.format.MonetaryFormats;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public class JavaMoneyUnitTest { public class JavaMoneyUnitManualTest {
@Test @Test
public void givenCurrencyCode_whenString_thanExist() { public void givenCurrencyCode_whenString_thanExist() {
CurrencyUnit usd = Monetary.getCurrency("USD"); CurrencyUnit usd = Monetary.getCurrency("USD");
assertNotNull(usd); assertNotNull(usd);
assertEquals(usd.getCurrencyCode(), "USD"); assertEquals(usd.getCurrencyCode(), "USD");
assertEquals(usd.getNumericCode(), 840); assertEquals(usd.getNumericCode(), 840);
assertEquals(usd.getDefaultFractionDigits(), 2); assertEquals(usd.getDefaultFractionDigits(), 2);
} }
@Test(expected = UnknownCurrencyException.class) @Test(expected = UnknownCurrencyException.class)
public void givenCurrencyCode_whenNoExist_thanThrowsError() { public void givenCurrencyCode_whenNoExist_thanThrowsError() {
Monetary.getCurrency("AAA"); Monetary.getCurrency("AAA");
} }
@Test @Test
public void givenAmounts_whenStringified_thanEquals() { public void givenAmounts_whenStringified_thanEquals() {
CurrencyUnit usd = Monetary.getCurrency("USD"); CurrencyUnit usd = Monetary.getCurrency("USD");
MonetaryAmount fstAmtUSD = Monetary MonetaryAmount fstAmtUSD = Monetary
.getDefaultAmountFactory() .getDefaultAmountFactory()
.setCurrency(usd) .setCurrency(usd)
.setNumber(200) .setNumber(200)
.create(); .create();
Money moneyof = Money.of(12, usd); Money moneyof = Money.of(12, usd);
FastMoney fastmoneyof = FastMoney.of(2, usd); FastMoney fastmoneyof = FastMoney.of(2, usd);
assertEquals("USD", usd.toString()); assertEquals("USD", usd.toString());
assertEquals("USD 200", fstAmtUSD.toString()); assertEquals("USD 200", fstAmtUSD.toString());
assertEquals("USD 12", moneyof.toString()); assertEquals("USD 12", moneyof.toString());
assertEquals("USD 2.00000", fastmoneyof.toString()); assertEquals("USD 2.00000", fastmoneyof.toString());
} }
@Test @Test
public void givenCurrencies_whenCompared_thanNotequal() { public void givenCurrencies_whenCompared_thanNotequal() {
MonetaryAmount oneDolar = Monetary MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory() .getDefaultAmountFactory()
.setCurrency("USD") .setCurrency("USD")
.setNumber(1) .setNumber(1)
.create(); .create();
Money oneEuro = Money.of(1, "EUR"); Money oneEuro = Money.of(1, "EUR");
assertFalse(oneEuro.equals(FastMoney.of(1, "EUR"))); assertFalse(oneEuro.equals(FastMoney.of(1, "EUR")));
assertTrue(oneDolar.equals(Money.of(1, "USD"))); assertTrue(oneDolar.equals(Money.of(1, "USD")));
} }
@Test(expected = ArithmeticException.class) @Test(expected = ArithmeticException.class)
public void givenAmount_whenDivided_thanThrowsException() { public void givenAmount_whenDivided_thanThrowsException() {
MonetaryAmount oneDolar = Monetary MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory() .getDefaultAmountFactory()
.setCurrency("USD") .setCurrency("USD")
.setNumber(1) .setNumber(1)
.create(); .create();
oneDolar.divide(3); oneDolar.divide(3);
fail(); // if no exception fail(); // if no exception
} }
@Test @Test
public void givenAmounts_whenSummed_thanCorrect() { public void givenAmounts_whenSummed_thanCorrect() {
List<MonetaryAmount> monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF")); List<MonetaryAmount> monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF"));
Money sumAmtCHF = (Money) monetaryAmounts Money sumAmtCHF = (Money) monetaryAmounts
.stream() .stream()
.reduce(Money.of(0, "CHF"), MonetaryAmount::add); .reduce(Money.of(0, "CHF"), MonetaryAmount::add);
assertEquals("CHF 111.35", sumAmtCHF.toString()); assertEquals("CHF 111.35", sumAmtCHF.toString());
} }
@Test @Test
public void givenArithmetic_whenStringified_thanEqualsAmount() { public void givenArithmetic_whenStringified_thanEqualsAmount() {
CurrencyUnit usd = Monetary.getCurrency("USD"); CurrencyUnit usd = Monetary.getCurrency("USD");
Money moneyof = Money.of(12, usd); Money moneyof = Money.of(12, usd);
MonetaryAmount fstAmtUSD = Monetary MonetaryAmount fstAmtUSD = Monetary
.getDefaultAmountFactory() .getDefaultAmountFactory()
.setCurrency(usd) .setCurrency(usd)
.setNumber(200.50) .setNumber(200.50)
.create(); .create();
MonetaryAmount oneDolar = Monetary MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory() .getDefaultAmountFactory()
.setCurrency("USD") .setCurrency("USD")
.setNumber(1) .setNumber(1)
.create(); .create();
Money subtractedAmount = Money Money subtractedAmount = Money
.of(1, "USD") .of(1, "USD")
.subtract(fstAmtUSD); .subtract(fstAmtUSD);
MonetaryAmount multiplyAmount = oneDolar.multiply(0.25); MonetaryAmount multiplyAmount = oneDolar.multiply(0.25);
MonetaryAmount divideAmount = oneDolar.divide(0.25); MonetaryAmount divideAmount = oneDolar.divide(0.25);
assertEquals("USD", usd.toString()); assertEquals("USD", usd.toString());
assertEquals("USD 1", oneDolar.toString()); assertEquals("USD 1", oneDolar.toString());
assertEquals("USD 200.5", fstAmtUSD.toString()); assertEquals("USD 200.5", fstAmtUSD.toString());
assertEquals("USD 12", moneyof.toString()); assertEquals("USD 12", moneyof.toString());
assertEquals("USD -199.5", subtractedAmount.toString()); assertEquals("USD -199.5", subtractedAmount.toString());
assertEquals("USD 0.25", multiplyAmount.toString()); assertEquals("USD 0.25", multiplyAmount.toString());
assertEquals("USD 4", divideAmount.toString()); assertEquals("USD 4", divideAmount.toString());
} }
@Test @Test
public void givenAmount_whenRounded_thanEquals() { public void givenAmount_whenRounded_thanEquals() {
MonetaryAmount fstAmtEUR = Monetary MonetaryAmount fstAmtEUR = Monetary
.getDefaultAmountFactory() .getDefaultAmountFactory()
.setCurrency("EUR") .setCurrency("EUR")
.setNumber(1.30473908) .setNumber(1.30473908)
.create(); .create();
MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding()); MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding());
assertEquals("EUR 1.30473908", fstAmtEUR.toString()); assertEquals("EUR 1.30473908", fstAmtEUR.toString());
assertEquals("EUR 1.3", roundEUR.toString()); assertEquals("EUR 1.3", roundEUR.toString());
} }
@Test @Test
@Ignore("Currency providers are not always available") @Ignore("Currency providers are not always available")
public void givenAmount_whenConversion_thenNotNull() { public void givenAmount_whenConversion_thenNotNull() {
MonetaryAmount oneDollar = Monetary MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory() .getDefaultAmountFactory()
.setCurrency("USD") .setCurrency("USD")
.setNumber(1) .setNumber(1)
.create(); .create();
CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR"); CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR");
MonetaryAmount convertedAmountUSDtoEUR = oneDollar.with(conversionEUR); MonetaryAmount convertedAmountUSDtoEUR = oneDollar.with(conversionEUR);
assertEquals("USD 1", oneDollar.toString()); assertEquals("USD 1", oneDollar.toString());
assertNotNull(convertedAmountUSDtoEUR); assertNotNull(convertedAmountUSDtoEUR);
} }
@Test @Test
public void givenLocale_whenFormatted_thanEquals() { public void givenLocale_whenFormatted_thanEquals() {
MonetaryAmount oneDollar = Monetary MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory() .getDefaultAmountFactory()
.setCurrency("USD") .setCurrency("USD")
.setNumber(1) .setNumber(1)
.create(); .create();
MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US); MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US);
String usFormatted = formatUSD.format(oneDollar); String usFormatted = formatUSD.format(oneDollar);
assertEquals("USD 1", oneDollar.toString()); assertEquals("USD 1", oneDollar.toString());
assertNotNull(formatUSD); assertNotNull(formatUSD);
assertEquals("USD1.00", usFormatted); assertEquals("USD1.00", usFormatted);
} }
@Test @Test
public void givenAmount_whenCustomFormat_thanEquals() { public void givenAmount_whenCustomFormat_thanEquals() {
MonetaryAmount oneDollar = Monetary MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory() .getDefaultAmountFactory()
.setCurrency("USD") .setCurrency("USD")
.setNumber(1) .setNumber(1)
.create(); .create();
MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder
.of(Locale.US) .of(Locale.US)
.set(CurrencyStyle.NAME) .set(CurrencyStyle.NAME)
.set("pattern", "00000.00 ¤") .set("pattern", "00000.00 <EFBFBD>")
.build()); .build());
String customFormatted = customFormat.format(oneDollar); String customFormatted = customFormat.format(oneDollar);
assertNotNull(customFormat); assertNotNull(customFormat);
assertEquals("USD 1", oneDollar.toString()); assertEquals("USD 1", oneDollar.toString());
assertEquals("00001.00 US Dollar", customFormatted); assertEquals("00001.00 US Dollar", customFormatted);
} }
} }

View File

@ -0,0 +1,65 @@
package com.baeldung.stream;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.IntStream;
import org.junit.Test;
import com.baeldung.stream.mycollectors.MyImmutableListCollector;
import com.google.common.collect.ImmutableList;
public class StreamToImmutableTest {
@Test
public void whenUsingCollectingToImmutableSet_thenSuccess() {
List<String> givenList = Arrays.asList("a", "b", "c");
List<String> result = givenList.stream()
.collect(collectingAndThen(toSet(), ImmutableList::copyOf));
System.out.println(result.getClass());
}
@Test
public void whenUsingCollectingToUnmodifiableList_thenSuccess() {
List<String> givenList = new ArrayList<>(Arrays.asList("a", "b", "c"));
List<String> result = givenList.stream()
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
System.out.println(result.getClass());
}
@Test
public void whenCollectToImmutableList_thenSuccess() {
List<Integer> list = IntStream.range(0, 9)
.boxed()
.collect(ImmutableList.toImmutableList());
System.out.println(list.getClass());
}
@Test
public void whenCollectToMyImmutableListCollector_thenSuccess() {
List<String> givenList = Arrays.asList("a", "b", "c", "d");
List<String> result = givenList.stream()
.collect(MyImmutableListCollector.toImmutableList());
System.out.println(result.getClass());
}
@Test
public void whenPassingSupplier_thenSuccess() {
List<String> givenList = Arrays.asList("a", "b", "c", "d");
List<String> result = givenList.stream()
.collect(MyImmutableListCollector.toImmutableList(LinkedList::new));
System.out.println(result.getClass());
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.stream.mycollectors;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collector;
public class MyImmutableListCollector {
public static <T, A extends List<T>> Collector<T, A, List<T>> toImmutableList(Supplier<A> supplier) {
return Collector.of(supplier, List::add, (left, right) -> {
left.addAll(right);
return left;
}, Collections::unmodifiableList);
}
public static <T> Collector<T, List<T>, List<T>> toImmutableList() {
return toImmutableList(ArrayList::new);
}
}

View File

@ -13,7 +13,6 @@ public class CoreThreadPoolIntegrationTest {
private static final Logger LOG = LoggerFactory.getLogger(CoreThreadPoolIntegrationTest.class); private static final Logger LOG = LoggerFactory.getLogger(CoreThreadPoolIntegrationTest.class);
@Test(timeout = 1000) @Test(timeout = 1000)
public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException { public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException {

View File

@ -4,5 +4,5 @@ This is the implementation of a [spring-hypermedia-api][1] client using Feign.
[1]: https://github.com/eugenp/spring-hypermedia-api [1]: https://github.com/eugenp/spring-hypermedia-api
###Relevant Articles: ### Relevant Articles:
- [Intro to Feign](http://www.baeldung.com/intro-to-feign) - [Intro to Feign](http://www.baeldung.com/intro-to-feign)

74
grpc/pom.xml Normal file
View File

@ -0,0 +1,74 @@
<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>grpc</groupId>
<artifactId>grpc-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>grpc-demo</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<io.grpc.version>1.5.0</io.grpc.version>
</properties>
<dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>${io.grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${io.grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${io.grpc.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.5.0.Final</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.0</version>
<configuration>
<protocArtifact>
com.google.protobuf:protoc:3.3.0:exe:${os.detected.classifier}
</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>
io.grpc:protoc-gen-grpc-java:1.4.0:exe:${os.detected.classifier}
</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,28 @@
package org.baeldung.grpc.client;
import org.baeldung.grpc.HelloRequest;
import org.baeldung.grpc.HelloResponse;
import org.baeldung.grpc.HelloServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
public class GrpcClient {
public static void main(String[] args) throws InterruptedException {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8080)
.usePlaintext(true)
.build();
HelloServiceGrpc.HelloServiceBlockingStub stub
= HelloServiceGrpc.newBlockingStub(channel);
HelloResponse helloResponse = stub.hello(HelloRequest.newBuilder()
.setFirstName("Baeldung")
.setLastName("gRPC")
.build());
System.out.println("Response received from server:\n" + helloResponse);
channel.shutdown();
}
}

View File

@ -0,0 +1,18 @@
package org.baeldung.grpc.server;
import java.io.IOException;
import io.grpc.Server;
import io.grpc.ServerBuilder;
public class GrpcServer {
public static void main(String[] args) throws IOException, InterruptedException {
Server server = ServerBuilder.forPort(8080)
.addService(new HelloServiceImpl()).build();
System.out.println("Starting server...");
server.start();
System.out.println("Server started!");
server.awaitTermination();
}
}

View File

@ -0,0 +1,29 @@
package org.baeldung.grpc.server;
import org.baeldung.grpc.HelloRequest;
import org.baeldung.grpc.HelloResponse;
import org.baeldung.grpc.HelloServiceGrpc.HelloServiceImplBase;
import io.grpc.stub.StreamObserver;
public class HelloServiceImpl extends HelloServiceImplBase {
@Override
public void hello(
HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
System.out.println("Request received from client:\n" + request);
String greeting = new StringBuilder().append("Hello, ")
.append(request.getFirstName())
.append(" ")
.append(request.getLastName())
.toString();
HelloResponse response = HelloResponse.newBuilder()
.setGreeting(greeting)
.build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}

View File

@ -0,0 +1,16 @@
syntax = "proto3";
option java_multiple_files = true;
package org.baeldung.grpc;
message HelloRequest {
string firstName = 1;
string lastName = 2;
}
message HelloResponse {
string greeting = 1;
}
service HelloService {
rpc hello(HelloRequest) returns (HelloResponse);
}

5
jee7/.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
/classes/
/.idea/
/target/
/jee7.iml

View File

@ -6,8 +6,10 @@
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>jee7</artifactId> <artifactId>jee7</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<description>JavaEE 7 Arquillian Archetype Sample</description> <description>JavaEE 7 Arquillian Archetype Sample</description>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId> <artifactId>parent-modules</artifactId>
@ -174,6 +176,7 @@
<artifactId>maven-war-plugin</artifactId> <artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version> <version>${maven-war-plugin.version}</version>
<configuration> <configuration>
<warSourceDirectory>webapp</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml> <failOnMissingWebXml>false</failOnMissingWebXml>
</configuration> </configuration>
</plugin> </plugin>

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<b:beans xmlns="http://www.springframework.org/schema/security"
xmlns:b="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user" password="user123" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
<http auto-config='true' use-expressions="true">
<form-login default-target-url="/secure.jsp" />
<intercept-url pattern="/" access="isAnonymous()" />
<intercept-url pattern="/index.jsp" access="isAnonymous()" />
<intercept-url pattern="/secure.jsp" access="hasRole('ROLE_USER')" />
</http>
</b:beans>

View File

@ -32,6 +32,33 @@
<!-- If you go to http://host/project/ (with no file name), it will <!-- If you go to http://host/project/ (with no file name), it will
try index.jsf first, welcome.jsf next, and so forth. try index.jsf first, welcome.jsf next, and so forth.
--> -->
<!-- UNCOMMENT THE FOLLOWING SECTION FOR SPRING SECURITY XML CONFIGURATION-->
<!--<context-param>-->
<!--<param-name>contextConfigLocation</param-name>-->
<!--<param-value>-->
<!--/WEB-INF/spring/*.xml-->
<!--</param-value>-->
<!--</context-param>-->
<!--<filter>-->
<!--<filter-name>springSecurityFilterChain</filter-name>-->
<!--<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>-->
<!--</filter>-->
<!--<filter-mapping>-->
<!--<filter-name>springSecurityFilterChain</filter-name>-->
<!--<url-pattern>/*</url-pattern>-->
<!--</filter-mapping>-->
<!--<listener>-->
<!--<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>-->
<!--</listener>-->
<!-- END SPRING SECURITY XML CONFIGURATION-->
<welcome-file-list> <welcome-file-list>
<welcome-file>index.jsf</welcome-file> <welcome-file>index.jsf</welcome-file>
<welcome-file>welcome.jsf</welcome-file> <welcome-file>welcome.jsf</welcome-file>

View File

@ -0,0 +1,11 @@
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Index Page</title>
</head>
<body>
Non-secured Index Page
<br>
<a href="/login">Login</a>
</body>
</html>

View File

@ -0,0 +1,24 @@
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Home Page</title>
</head>
<body>
<h3>Home Page</h3>
<p>
Hello <b><c:out value="${pageContext.request.remoteUser}"/></b><br>
Roles: <b><sec:authentication property="principal.authorities" /></b>
</p>
<form action="logout" method="post">
<input type="submit" value="Logout" />
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
</body>
</html>

View File

@ -1,3 +0,0 @@
### Relevant articles
- [Introduction to jOOL](http://www.baeldung.com/jool)

View File

@ -1,25 +0,0 @@
<?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">
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>jooq</artifactId>
<dependencies>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jool</artifactId>
<version>${jool.version}</version>
</dependency>
</dependencies>
<properties>
<jool.version>0.9.12</jool.version>
</properties>
</project>

View File

@ -0,0 +1,19 @@
package com.baeldung.kotlin
sealed class Result<out S, out F> {
abstract fun <R> map(func: (S) -> R) : Result<R, F>
abstract fun <R> mapFailure(func: (F) -> R) : Result<S, R>
abstract fun get() : S?
}
data class Success<out S, out F>(val success: S) : Result<S, F>() {
override fun <R> map(func: (S) -> R) : Result<R, F> = Success(func(success))
override fun <R> mapFailure(func: (F) -> R): Result<S, R> = Success(success)
override fun get(): S? = success
}
data class Failure<out S, out F>(val failure: F) : Result<S, F>() {
override fun <R> map(func: (S) -> R) : Result<R, F> = Failure(failure)
override fun <R> mapFailure(func: (F) -> R): Result<S, R> = Failure(func(failure))
override fun get(): S? = null
}

View File

@ -0,0 +1,35 @@
package com.baeldung.kotlin.delegates
val data = arrayOf<MutableMap<String, Any?>>(
mutableMapOf(
"id" to 1,
"name" to "George",
"age" to 4
),
mutableMapOf(
"id" to 2,
"name" to "Charlotte",
"age" to 2
)
)
class NoRecordFoundException(id: Int) : Exception("No record found for id $id") {
init {
println("No record found for ID $id")
}
}
fun queryForValue(field: String, id: Int): Any {
println("Loading record $id from the fake database")
val value = data.firstOrNull { it["id"] == id }
?.get(field) ?: throw NoRecordFoundException(id)
println("Loaded value $value for field $field of record $id")
return value
}
fun update(field: String, id: Int, value: Any?) {
println("Updating field $field of record $id to value $value in the fake database")
data.firstOrNull { it["id"] == id }
?.put(field, value)
?: throw NoRecordFoundException(id)
}

View File

@ -0,0 +1,13 @@
package com.baeldung.kotlin.delegates
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class DatabaseDelegate<in R, T>(private val field: String, private val id: Int) : ReadWriteProperty<R, T> {
override fun getValue(thisRef: R, property: KProperty<*>): T =
queryForValue(field, id) as T
override fun setValue(thisRef: R, property: KProperty<*>, value: T) {
update(field, id, value)
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.kotlin.delegates
class User(val id: Int) {
var name: String by DatabaseDelegate("name", id)
var age: Int by DatabaseDelegate("age", id)
}

View File

@ -0,0 +1,84 @@
package com.baeldung.kotlin
import org.junit.Assert
import org.junit.Test
class SealedTest {
fun divide(a: Int, b: Int) : Result<Float, String> = when (b) {
0 -> Failure("Division by zero")
else -> Success(a.toFloat() / b)
}
@Test
fun testSuccess() {
val result = divide(10, 5)
Assert.assertEquals(Success<Float, String>(2.0f), result)
}
@Test
fun testError() {
val result = divide(10, 0)
Assert.assertEquals(Failure<Float, String>("Division by zero"), result)
}
@Test
fun testMatchOnSuccess() {
val result = divide(10, 5)
when (result) {
is Success -> {
// Expected
}
is Failure -> Assert.fail("Expected Success")
}
}
@Test
fun testMatchOnError() {
val result = divide(10, 0)
when (result) {
is Failure -> {
// Expected
}
}
}
@Test
fun testGetSuccess() {
val result = divide(10, 5)
Assert.assertEquals(2.0f, result.get())
}
@Test
fun testGetError() {
val result = divide(10, 0)
Assert.assertNull(result.get())
}
@Test
fun testMapOnSuccess() {
val result = divide(10, 5)
.map { "Result: $it" }
Assert.assertEquals(Success<String, String>("Result: 2.0"), result)
}
@Test
fun testMapOnError() {
val result = divide(10, 0)
.map { "Result: $it" }
Assert.assertEquals(Failure<Float, String>("Division by zero"), result)
}
@Test
fun testMapFailureOnSuccess() {
val result = divide(10, 5)
.mapFailure { "Failure: $it" }
Assert.assertEquals(Success<Float, String>(2.0f), result)
}
@Test
fun testMapFailureOnError() {
val result = divide(10, 0)
.mapFailure { "Failure: $it" }
Assert.assertEquals(Failure<Float, String>("Failure: Division by zero"), result)
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.kotlin.delegates
import org.junit.Test
import kotlin.test.assertEquals
class DatabaseDelegatesTest {
@Test
fun testGetKnownFields() {
val user = User(1)
assertEquals("George", user.name)
assertEquals(4, user.age)
}
@Test
fun testSetKnownFields() {
val user = User(2)
user.age = 3
assertEquals(3, user.age)
}
@Test(expected = NoRecordFoundException::class)
fun testGetKnownField() {
val user = User(3)
user.name
}
}

22
libraries-data/pom.xml Normal file
View File

@ -0,0 +1,22 @@
<?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>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>libraries-data</artifactId>
<name>libraries-data</name>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.esotericsoftware</groupId>
<artifactId>kryo</artifactId>
<version>${kryo.version}</version>
</dependency>
</dependencies>
<properties>
<kryo.version>4.0.1</kryo.version>
</properties>
</project>

View File

@ -0,0 +1,16 @@
package com.baeldung.kryo;
import java.io.Serializable;
public class ComplexClass implements Serializable{
private static final long serialVersionUID = 123456L;
private String name = "Bael";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.kryo;
import com.esotericsoftware.kryo.DefaultSerializer;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.KryoSerializable;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import java.util.Date;
@DefaultSerializer(PersonSerializer.class)
public class Person implements KryoSerializable {
private String name = "John Doe";
private int age = 18;
private Date birthDate = new Date(933191282821L);
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
@Override
public void write(Kryo kryo, Output output) {
output.writeString(name);
output.writeLong(birthDate.getTime());
output.writeInt(age);
}
@Override
public void read(Kryo kryo, Input input) {
name = input.readString();
birthDate = new Date(input.readLong());
age = input.readInt();
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.kryo;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import java.util.Date;
public class PersonSerializer extends Serializer<Person> {
@Override
public void write(Kryo kryo, Output output, Person object) {
output.writeString(object.getName());
output.writeLong(object.getBirthDate()
.getTime());
}
@Override
public Person read(Kryo kryo, Input input, Class<Person> type) {
Person person = new Person();
person.setName(input.readString());
long birthDate = input.readLong();
person.setBirthDate(new Date(birthDate));
person.setAge(calculateAge(birthDate));
return person;
}
private int calculateAge(long birthDate) {
// Some custom logic
return 18;
}
}

View File

@ -0,0 +1,125 @@
package com.baeldung.kryo;
import static org.junit.Assert.assertEquals;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Before;
import org.junit.Test;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.JavaSerializer;
public class KryoUnitTest {
private Kryo kryo;
private Output output;
private Input input;
@Before
public void init() {
kryo = new Kryo();
try {
output = new Output(new FileOutputStream("file.dat"));
input = new Input(new FileInputStream("file.dat"));
} catch (FileNotFoundException ex) {
Logger.getLogger(KryoUnitTest.class.getName())
.log(Level.SEVERE, null, ex);
}
}
@Test
public void givenObject_whenSerializing_thenReadCorrectly() {
Object someObject = "Some string";
kryo.writeClassAndObject(output, someObject);
output.close();
Object theObject = kryo.readClassAndObject(input);
input.close();
assertEquals(theObject, "Some string");
}
@Test
public void givenObjects_whenSerializing_thenReadCorrectly() {
String someString = "Multiple Objects";
Date someDate = new Date(915170400000L);
kryo.writeObject(output, someString);
kryo.writeObject(output, someDate);
output.close();
String readString = kryo.readObject(input, String.class);
Date readDate = kryo.readObject(input, Date.class);
input.close();
assertEquals(readString, "Multiple Objects");
assertEquals(readDate.getTime(), 915170400000L);
}
@Test
public void givenPerson_whenSerializing_thenReadCorrectly() {
Person person = new Person();
kryo.writeObject(output, person);
output.close();
Person readPerson = kryo.readObject(input, Person.class);
input.close();
assertEquals(readPerson.getName(), "John Doe");
}
@Test
public void givenPerson_whenUsingCustomSerializer_thenReadCorrectly() {
Person person = new Person();
person.setAge(0);
kryo.register(Person.class, new PersonSerializer());
kryo.writeObject(output, person);
output.close();
Person readPerson = kryo.readObject(input, Person.class);
input.close();
assertEquals(readPerson.getName(), "John Doe");
assertEquals(readPerson.getAge(), 18);
}
@Test
public void givenPerson_whenCustomSerialization_thenReadCorrectly() {
Person person = new Person();
kryo.writeObject(output, person);
output.close();
Person readPerson = kryo.readObject(input, Person.class);
input.close();
assertEquals(readPerson.getName(), "John Doe");
assertEquals(readPerson.getAge(), 18);
}
@Test
public void givenJavaSerializable_whenSerializing_thenReadCorrectly() {
ComplexClass complexClass = new ComplexClass();
kryo.register(ComplexClass.class, new JavaSerializer());
kryo.writeObject(output, complexClass);
output.close();
ComplexClass readComplexObject = kryo.readObject(input, ComplexClass.class);
input.close();
assertEquals(readComplexObject.getName(), "Bael");
}
}

View File

@ -27,6 +27,8 @@
- [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing) - [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing)
- [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog) - [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog)
- [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph) - [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph)
- [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue)
- [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss)
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.

View File

@ -20,7 +20,6 @@
<artifactId>maven-bundle-plugin</artifactId> <artifactId>maven-bundle-plugin</artifactId>
<version>3.3.0</version> <version>3.3.0</version>
<type>maven-plugin</type> <type>maven-plugin</type>
</dependency> </dependency>
</dependencies> </dependencies>
<extensions>true</extensions> <extensions>true</extensions>
@ -182,6 +181,16 @@
<artifactId>jetty-servlet</artifactId> <artifactId>jetty-servlet</artifactId>
<version>${jetty.version}</version> <version>${jetty.version}</version>
</dependency> </dependency>
<dependency>
<groupId>rome</groupId>
<artifactId>rome</artifactId>
<version>${rome.version}</version>
</dependency>
<dependency>
<groupId>io.specto</groupId>
<artifactId>hoverfly-java</artifactId>
<version>0.8.0</version>
</dependency>
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId> <artifactId>httpclient</artifactId>
@ -453,12 +462,11 @@
<artifactId>pcollections</artifactId> <artifactId>pcollections</artifactId>
<version>${pcollections.version}</version> <version>${pcollections.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.eclipse.collections</groupId> <groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId> <artifactId>eclipse-collections</artifactId>
<version>${eclipse-collections.version}</version> <version>${eclipse-collections.version}</version>
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<multiverse.version>0.7.0</multiverse.version> <multiverse.version>0.7.0</multiverse.version>
@ -499,6 +507,7 @@
<hll.version>1.6.0</hll.version> <hll.version>1.6.0</hll.version>
<bytebuddy.version>1.7.1</bytebuddy.version> <bytebuddy.version>1.7.1</bytebuddy.version>
<pcollections.version>2.1.2</pcollections.version> <pcollections.version>2.1.2</pcollections.version>
<eclipse-collections.version>8.2.0</eclipse-collections.version> <rome.version>1.0</rome.version>
<eclipse-collections.version>8.2.0</eclipse-collections.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,76 @@
package com.baeldung.rome;
import com.sun.syndication.feed.synd.*;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.SyndFeedOutput;
import com.sun.syndication.io.XmlReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RSSRomeExample {
public static void main(String[] args) throws IOException, FeedException {
SyndFeed feed = createFeed();
addEntryToFeed(feed);
publishFeed(feed);
readFeed();
}
private static SyndFeed createFeed() {
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType("rss_1.0");
feed.setTitle("Test title");
feed.setLink("http://www.somelink.com");
feed.setDescription("Basic description");
return feed;
}
private static void addEntryToFeed(SyndFeed feed) {
SyndEntry entry = new SyndEntryImpl();
entry.setTitle("Entry title");
entry.setLink("http://www.somelink.com/entry1");
addDescriptionToEntry(entry);
addCategoryToEntry(entry);
feed.setEntries(Arrays.asList(entry));
}
private static void addDescriptionToEntry(SyndEntry entry) {
SyndContent description = new SyndContentImpl();
description.setType("text/html");
description.setValue("First entry");
entry.setDescription(description);
}
private static void addCategoryToEntry(SyndEntry entry) {
List<SyndCategory> categories = new ArrayList<>();
SyndCategory category = new SyndCategoryImpl();
category.setName("Sophisticated category");
categories.add(category);
entry.setCategories(categories);
}
private static void publishFeed(SyndFeed feed) throws IOException, FeedException {
Writer writer = new FileWriter("xyz.txt");
SyndFeedOutput syndFeedOutput = new SyndFeedOutput();
syndFeedOutput.output(feed, writer);
writer.close();
}
private static SyndFeed readFeed() throws IOException, FeedException {
URL feedSource = new URL("http://rssblog.whatisrss.com/feed/");
SyndFeedInput input = new SyndFeedInput();
return input.build(new XmlReader(feedSource));
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.streamutils;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import org.apache.commons.io.IOUtils;
import org.springframework.util.StreamUtils;
public class CopyStream {
public static String getStringFromInputStream(InputStream input) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(input, writer, "UTF-8");
return writer.toString();
}
public InputStream getNonClosingInputStream() throws IOException {
InputStream in = new FileInputStream("src/test/resources/input.txt");
return StreamUtils.nonClosing(in);
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.streamutils;
import java.io.InputStream;
import org.springframework.util.StreamUtils;
public class DrainStream {
public InputStream getInputStream() {
return StreamUtils.emptyInput();
}
}

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