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>
<!-- logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
@ -391,7 +395,7 @@
<logback.version>1.1.7</logback.version>
<!-- util -->
<guava.version>21.0</guava.version>
<guava.version>22.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<bouncycastle.version>1.55</bouncycastle.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_WORKERS;
private void runSimulation(int numWorkers, int numberOfPartialResults) {
NUM_PARTIAL_RESULTS = numberOfPartialResults;
NUM_WORKERS = numWorkers;
cyclicBarrier = new CyclicBarrier(NUM_WORKERS, new AggregatorThread());
System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute "
+ NUM_PARTIAL_RESULTS + " partial results each");
System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute " + NUM_PARTIAL_RESULTS + " partial results each");
for (int i = 0; i < NUM_WORKERS; i++) {
Thread worker = new Thread(new NumberCruncherThread());
worker.setName("Thread " + i);
@ -38,8 +36,7 @@ public class CyclicBarrierDemo {
List<Integer> partialResult = new ArrayList<>();
for (int i = 0; i < NUM_PARTIAL_RESULTS; i++) {
Integer num = random.nextInt(10);
System.out.println(thisThreadName
+ ": Crunching some numbers! Final result - " + num);
System.out.println(thisThreadName + ": Crunching some numbers! Final result - " + num);
partialResult.add(num);
}
partialResults.add(partialResult);
@ -57,13 +54,12 @@ public class CyclicBarrierDemo {
@Override
public void run() {
String thisThreadName = Thread.currentThread().getName();
System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS
+ " workers, having " + NUM_PARTIAL_RESULTS + " results each.");
System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS + " workers, having " + NUM_PARTIAL_RESULTS + " results each.");
int sum = 0;
for (List<Integer> threadResult : partialResults) {
System.out.print("Adding ");
for (Integer partialResult : threadResult) {
System.out.print(partialResult+" ");
System.out.print(partialResult + " ");
sum += partialResult;
}
System.out.println();

View File

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

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

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

View File

@ -1,4 +1,4 @@
package com.baeldung.entities;
package com.baeldung.hashcode.entities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -18,9 +18,12 @@ public class User {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (this.getClass() != o.getClass()) return false;
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));
}

View File

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

View File

@ -8,7 +8,6 @@ import java.net.*;
public class EchoClient {
private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class);
private Socket clientSocket;

View File

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

View File

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

View File

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

View File

@ -9,7 +9,6 @@ import java.util.concurrent.atomic.AtomicInteger;
public class Consumer implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(Consumer.class);
private final TransferQueue<String> transferQueue;
private final String name;
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
public void givenLongAccumulator_whenApplyActionOnItFromMultipleThrads_thenShouldProduceProperResult() throws InterruptedException {
//given
// given
ExecutorService executorService = Executors.newFixedThreadPool(8);
LongBinaryOperator sum = Long::sum;
LongAccumulator accumulator = new LongAccumulator(sum, 0L);
int numberOfThreads = 4;
int numberOfIncrements = 100;
//when
Runnable accumulateAction = () -> IntStream
.rangeClosed(0, numberOfIncrements)
.forEach(accumulator::accumulate);
// when
Runnable accumulateAction = () -> IntStream.rangeClosed(0, numberOfIncrements).forEach(accumulator::accumulate);
for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(accumulateAction);
}
//then
// then
executorService.awaitTermination(500, TimeUnit.MILLISECONDS);
executorService.shutdown();
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.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<>();
User user1 = new User(1L, "John", "john@domain.com");
User user2 = new User(2L, "Jennifer", "jennifer@domain.com");
@ -16,8 +21,6 @@ public class Application {
users.put(user2, user2);
users.put(user3, user3);
if (users.containsKey(user1)) {
System.out.print("User found in the collection");
}
assertTrue(users.containsKey(user1));
}
}

View File

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

View File

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

View File

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

View File

@ -25,7 +25,7 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class JavaMoneyUnitTest {
public class JavaMoneyUnitManualTest {
@Test
public void givenCurrencyCode_whenString_thanExist() {
@ -179,7 +179,7 @@ public class JavaMoneyUnitTest {
MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder
.of(Locale.US)
.set(CurrencyStyle.NAME)
.set("pattern", "00000.00 ¤")
.set("pattern", "00000.00 <EFBFBD>")
.build());
String customFormatted = customFormat.format(oneDollar);

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);
@Test(timeout = 1000)
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
###Relevant Articles:
### Relevant Articles:
- [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>
<artifactId>jee7</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<description>JavaEE 7 Arquillian Archetype Sample</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
@ -174,6 +176,7 @@
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<warSourceDirectory>webapp</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</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
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>index.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)
- [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog)
- [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.

View File

@ -20,7 +20,6 @@
<artifactId>maven-bundle-plugin</artifactId>
<version>3.3.0</version>
<type>maven-plugin</type>
</dependency>
</dependencies>
<extensions>true</extensions>
@ -181,6 +180,16 @@
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>${jetty.version}</version>
</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>
<groupId>org.apache.httpcomponents</groupId>
@ -458,7 +467,6 @@
<artifactId>eclipse-collections</artifactId>
<version>${eclipse-collections.version}</version>
</dependency>
</dependencies>
<properties>
<multiverse.version>0.7.0</multiverse.version>
@ -499,6 +507,7 @@
<hll.version>1.6.0</hll.version>
<bytebuddy.version>1.7.1</bytebuddy.version>
<pcollections.version>2.1.2</pcollections.version>
<rome.version>1.0</rome.version>
<eclipse-collections.version>8.2.0</eclipse-collections.version>
</properties>
</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();
}
}

View File

@ -0,0 +1,140 @@
package com.baeldung.hoverfly;
import static io.specto.hoverfly.junit.core.SimulationSource.dsl;
import static io.specto.hoverfly.junit.dsl.HoverflyDsl.service;
import static io.specto.hoverfly.junit.dsl.HttpBodyConverter.jsonWithSingleQuotes;
import static io.specto.hoverfly.junit.dsl.ResponseCreators.success;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.any;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsTo;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToJson;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToXml;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matches;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.startsWith;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesJsonPath;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesXPath;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.time.StopWatch;
import org.junit.ClassRule;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import io.specto.hoverfly.junit.core.SimulationSource;
import io.specto.hoverfly.junit.rule.HoverflyRule;
public class HoverflyApiTest {
private static final SimulationSource source = dsl(
service("http://www.baeldung.com")
.get("/api/courses/1")
.willReturn(success().body(
jsonWithSingleQuotes("{'id':'1','name':'HCI'}")))
.post("/api/courses")
.willReturn(success())
.andDelay(3, TimeUnit.SECONDS)
.forMethod("POST"),
service(matches("www.*dung.com"))
.get(startsWith("/api/student"))
.queryParam("page", any())
.willReturn(success())
.post(equalsTo("/api/student"))
.body(equalsToJson(jsonWithSingleQuotes("{'id':'1','name':'Joe'}")))
.willReturn(success())
.put("/api/student/1")
.body(matchesJsonPath("$.name"))
.willReturn(success())
.post("/api/student")
.body(equalsToXml("<student><id>2</id><name>John</name></student>"))
.willReturn(success())
.put("/api/student/2")
.body(matchesXPath("/student/name"))
.willReturn(success()));
@ClassRule
public static final HoverflyRule rule = HoverflyRule.inSimulationMode(source);
private final RestTemplate restTemplate = new RestTemplate();
@Test
public void givenGetCourseById_whenRequestSimulated_thenAPICalledSuccessfully() throws URISyntaxException {
final ResponseEntity<String> courseResponse = restTemplate.getForEntity(
"http://www.baeldung.com/api/courses/1", String.class);
assertEquals(HttpStatus.OK, courseResponse.getStatusCode());
assertEquals("{\"id\":\"1\",\"name\":\"HCI\"}", courseResponse.getBody());
}
@Test
public void givenPostCourse_whenDelayInRequest_thenResponseIsDelayed() throws URISyntaxException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
final ResponseEntity<Void> postResponse = restTemplate.postForEntity(
"http://www.baeldung.com/api/courses", null, Void.class);
stopWatch.stop();
long postTime = stopWatch.getTime();
assertEquals(HttpStatus.OK, postResponse.getStatusCode());
assertTrue(3L <= TimeUnit.MILLISECONDS.toSeconds(postTime));
}
@Test
public void givenGetStudent_whenRequestMatcher_thenAPICalledSuccessfully() throws URISyntaxException {
final ResponseEntity<Void> courseResponse = restTemplate.getForEntity(
"http://www.baeldung.com/api/student?page=3", Void.class);
assertEquals(HttpStatus.OK, courseResponse.getStatusCode());
}
@Test
public void givenPostStudent_whenBodyRequestMatcherJson_thenResponseContainsEqualJson() throws URISyntaxException {
final ResponseEntity<Void> postResponse = restTemplate.postForEntity(
"http://www.baeldung.com/api/student", "{\"id\":\"1\",\"name\":\"Joe\"}", Void.class);
assertEquals(HttpStatus.OK, postResponse.getStatusCode());
}
@Test
public void givenPutStudent_whenJsonPathMatcher_thenRequestJsonContainsElementInPath() throws URISyntaxException {
RequestEntity<String> putRequest = RequestEntity
.put(new URI("http://www.baeldung.com/api/student/1"))
.body("{\"id\":\"1\",\"name\":\"Trevor\"}");
ResponseEntity<String> putResponse = restTemplate.exchange(putRequest, String.class);
assertEquals(HttpStatus.OK, putResponse.getStatusCode());
}
@Test
public void givenPostStudent_whenBodyRequestMatcherXml_thenResponseContainsEqualXml() throws URISyntaxException {
final ResponseEntity<Void> postResponse = restTemplate.postForEntity(
"http://www.baeldung.com/api/student", "<student><id>2</id><name>John</name></student>", Void.class);
assertEquals(HttpStatus.OK, postResponse.getStatusCode());
}
@Test
public void givenPutStudent_whenXPathMatcher_thenRequestXmlContainsElementInXPath() throws URISyntaxException {
RequestEntity<String> putRequest = RequestEntity
.put(new URI("http://www.baeldung.com/api/student/2"))
.body("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
+ "<student><id>2</id><name>Monica</name></student>");
ResponseEntity<String> putResponse = restTemplate.exchange(putRequest, String.class);
assertEquals(HttpStatus.OK, putResponse.getStatusCode());
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung;
package com.baeldung.jool;
import org.jooq.lambda.Seq;
import org.jooq.lambda.Unchecked;
@ -13,6 +13,7 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@ -20,7 +21,7 @@ import static junit.framework.Assert.assertTrue;
import static junit.framework.TestCase.assertEquals;
import static org.jooq.lambda.tuple.Tuple.tuple;
public class JOOLUnitTest {
public class JOOLTest {
@Test
public void givenSeq_whenCheckContains_shouldReturnTrue() {
List<Integer> concat = Seq.of(1, 2, 3).concat(Seq.of(4, 5, 6)).toList();
@ -54,18 +55,18 @@ public class JOOLUnitTest {
@Test
public void givenSeq_whenJoin_shouldHaveElementsFromBothSeq() {
assertEquals(
Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), (a, b) -> a == b).toList(),
Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), Objects::equals).toList(),
Arrays.asList(tuple(1, 1), tuple(2, 2))
);
assertEquals(
Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), (a, b) -> a == b).toList(),
Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(),
Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null))
);
assertEquals(
Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), (a, b) -> a == b).toList(),
Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(),
Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3))
);
@ -197,7 +198,7 @@ public class JOOLUnitTest {
public void givenOperationThatThrowsCheckedException_whenExecuteUsingUncheckedFuction_shouldPass() {
//when
List<Integer> collect = Stream.of("a", "b", "c")
.map(Unchecked.function(elem -> methodThatThrowsChecked(elem)))
.map(Unchecked.function(this::methodThatThrowsChecked))
.collect(Collectors.toList());
//then
@ -236,5 +237,4 @@ public class JOOLUnitTest {
Arrays.asList(tuple("michael", "similar", "winter", "summer"), tuple("jodie", "variable", "winter", "summer"))
);
}
}

View File

@ -10,6 +10,10 @@ import static org.junit.Assert.*;
public class XORTest {
private NeuralNetwork ann = null;
private void print(String input, double output, double actual) {
System.out.println("Testing: " + input + " Expected: " + actual + " Result: " + output);
}
@Before
public void annInit() {
ann = NeurophXOR.trainNeuralNetwork(NeurophXOR.assembleNeuralNetwork());
@ -19,28 +23,32 @@ public class XORTest {
public void leftDisjunctTest() {
ann.setInput(0, 1);
ann.calculate();
assertEquals(ann.getOutput()[0], 1.0,0.0);
print("0, 1", ann.getOutput()[0], 1.0);
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);
print("1, 0", ann.getOutput()[0], 1.0);
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);
print("0, 0", ann.getOutput()[0], 0.0);
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);
print("1, 1", ann.getOutput()[0], 0.0);
assertEquals(ann.getOutput()[0], 0.0, 0.0);
}
@After

View File

@ -0,0 +1,100 @@
package com.baeldung.streamutils;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.util.StreamUtils;
import static com.baeldung.streamutils.CopyStream.getStringFromInputStream;
public class CopyStreamTest {
@Test
public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
String outputFileName = "src/test/resources/output.txt";
File outputFile = new File(outputFileName);
InputStream in = new FileInputStream(inputFileName);
OutputStream out = new FileOutputStream(outputFileName);
StreamUtils.copy(in, out);
assertTrue(outputFile.exists());
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
Assert.assertEquals(inputFileContent, outputFileContent);
}
@Test
public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
String outputFileName = "src/test/resources/output.txt";
File outputFile = new File(outputFileName);
InputStream in = new FileInputStream(inputFileName);
OutputStream out = new FileOutputStream(outputFileName);
StreamUtils.copyRange(in, out, 1, 10);
assertTrue(outputFile.exists());
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
Assert.assertEquals(inputFileContent.substring(1, 11), outputFileContent);
}
@Test
public void whenCopyStringToOutputStream_thenCorrect() throws IOException {
String string = "Should be copied to OutputStream.";
String outputFileName = "src/test/resources/output.txt";
File outputFile = new File(outputFileName);
OutputStream out = new FileOutputStream("src/test/resources/output.txt");
StreamUtils.copy(string, StandardCharsets.UTF_8, out);
assertTrue(outputFile.exists());
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
Assert.assertEquals(outputFileContent, string);
}
@Test
public void whenCopyInputStreamToString_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
InputStream is = new FileInputStream(inputFileName);
String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8);
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
Assert.assertEquals(inputFileContent, content);
}
@Test
public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException {
String outputFileName = "src/test/resources/output.txt";
String string = "Should be copied to OutputStream.";
byte[] byteArray = string.getBytes();
OutputStream out = new FileOutputStream("src/test/resources/output.txt");
StreamUtils.copy(byteArray, out);
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
Assert.assertEquals(outputFileContent, string);
}
@Test
public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
InputStream in = new FileInputStream(inputFileName);
byte[] out = StreamUtils.copyToByteArray(in);
String content = new String(out);
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
Assert.assertEquals(inputFileContent, content);
}
}

View File

@ -0,0 +1 @@
This file is merely for testing.

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