Merge branch 'master' into master

This commit is contained in:
Ahmed Tawila
2017-06-30 05:12:02 +03:00
committed by GitHub
391 changed files with 15815 additions and 1768 deletions
+1
View File
@@ -0,0 +1 @@
Out of the night that covers me
+10
View File
@@ -0,0 +1,10 @@
GOOD good morning /
GOOD good evening /
GOOD have a good day /
GOOD nice party! /
GOOD fine pants /
BAD nightmare volcano in the sea /
BAD darkest sky /
BAD greed and waste /
BAD army attacks /
BAD bomb explodes /
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+8
View File
@@ -11,6 +11,14 @@
- [Intro to JaVer](http://www.baeldung.com/javers)
- [Introduction to Apache Commons Math](http://www.baeldung.com/apache-commons-math)
- [Intro to JaVer](http://www.baeldung.com/serenity-bdd)
- [Introduction to Netty](http://www.baeldung.com/netty)
- [Guide to Java Data Objects](http://www.baeldung.com/jdo)
- [Software Transactional Memory in Java Using Multiverse](http://www.baeldung.com/java-multiverse-stm)
- [Introduction to HikariCP](http://www.baeldung.com/hikaricp)
- [Serenity BDD with Spring and JBehave](http://www.baeldung.com/serenity-spring-jbehave)
- [Locality-Sensitive Hashing in Java Using Java-LSH](http://www.baeldung.com/locality-sensitive-hashing)
- [Apache Commons Collections OrderedMap](http://www.baeldung.com/apache-commons-ordered-map)
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.
BIN
View File
Binary file not shown.
+92 -12
View File
@@ -1,6 +1,6 @@
<?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">
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>
@@ -26,6 +26,15 @@
</dependencies>
<extensions>true</extensions>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.20</version>
<configuration>
<systemProperties>
<webdriver.chrome.driver>chromedriver</webdriver.chrome.driver>
</systemProperties>
</configuration>
</plugin>
<plugin>
<groupId>net.serenity-bdd.maven.plugins</groupId>
<artifactId>serenity-maven-plugin</artifactId>
@@ -50,7 +59,7 @@
<props>${basedir}/datanucleus.properties</props>
<log4jConfiguration>${basedir}/log4j.properties</log4jConfiguration>
<verbose>true</verbose>
<fork>false</fork> <!-- Solve windows line too long error -->
<fork>false</fork> <!-- Solve windows line too long error -->
</configuration>
<executions>
<execution>
@@ -71,16 +80,26 @@
<artifactId>cglib</artifactId>
<version>${cglib.version}</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>${commons-beanutils.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons.collections.version}</version>
</dependency>
<dependency>
<groupId>org.jasypt</groupId>
<artifactId>jasypt</artifactId>
@@ -231,7 +250,7 @@
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-maven-plugin</artifactId>
<version>5.0.2</version>
</dependency>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-xml</artifactId>
@@ -248,6 +267,18 @@
<version>${serenity.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-screenplay</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-screenplay-webdriver</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>spring-mock-mvc</artifactId>
@@ -271,11 +302,11 @@
<version>1.4.195</version>
</dependency>
<dependency>
<groupId>pl.pragmatists</groupId>
<artifactId>JUnitParams</artifactId>
<version>${jUnitParams.version}</version>
<scope>test</scope>
</dependency>
<groupId>pl.pragmatists</groupId>
<artifactId>JUnitParams</artifactId>
<version>${jUnitParams.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
@@ -292,12 +323,56 @@
<artifactId>jool</artifactId>
<version>0.9.12</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>${netty.version}</version>
</dependency>
<!-- OpenNLP -->
<dependency>
<groupId>org.apache.opennlp</groupId>
<artifactId>opennlp-tools</artifactId>
<version>1.8.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.debatty</groupId>
<artifactId>java-lsh</artifactId>
<version>${java-lsh.version}</version>
</dependency>
<dependency>
<groupId>au.com.dius</groupId>
<artifactId>pact-jvm-consumer-junit_2.11</artifactId>
<version>${pact.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.10</version>
</dependency>
</dependencies>
<properties>
<multiverse.version>0.7.0</multiverse.version>
<cglib.version>3.2.4</cglib.version>
<commons-lang.version>3.5</commons-lang.version>
<commons-text.version>1.1</commons-text.version>
<commons-beanutils.version>1.9.3</commons-beanutils.version>
<jasypt.version>1.9.2</jasypt.version>
<javatuples.version>1.2</javatuples.version>
<javaassist.version>3.21.0-GA</javaassist.version>
@@ -317,6 +392,11 @@
<serenity.jira.version>1.1.3-rc.5</serenity.jira.version>
<serenity.plugin.version>1.4.0</serenity.plugin.version>
<jUnitParams.version>1.1.0</jUnitParams.version>
<netty.version>4.1.10.Final</netty.version>
<commons.collections.version>4.1</commons.collections.version>
<junit.version>4.12</junit.version>
<java-lsh.version>0.10</java-lsh.version>
<pact.version>3.5.0</pact.version>
</properties>
</project>
@@ -0,0 +1,35 @@
package com.baeldung.commons.beanutils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Course {
private String name;
private List<String> codes;
private Map<String, Student> enrolledStudent = new HashMap<String, Student>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getCodes() {
return codes;
}
public void setCodes(List<String> codes) {
this.codes = codes;
}
public void setEnrolledStudent(String enrolledId, Student student) {
enrolledStudent.put(enrolledId, student);
}
public Student getEnrolledStudent(String enrolledId) {
return enrolledStudent.get(enrolledId);
}
}
@@ -0,0 +1,34 @@
package com.baeldung.commons.beanutils;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.apache.commons.beanutils.PropertyUtils;
public class CourseService {
public static void setValues(Course course, String name, List<String> codes)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
// Setting the simple properties
PropertyUtils.setSimpleProperty(course, "name", name);
PropertyUtils.setSimpleProperty(course, "codes", codes);
}
public static void setIndexedValue(Course course, int codeIndex, String code)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
// Setting the indexed properties
PropertyUtils.setIndexedProperty(course, "codes[" + codeIndex + "]", code);
}
public static void setMappedValue(Course course, String enrollId, Student student)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
// Setting the mapped properties
PropertyUtils.setMappedProperty(course, "enrolledStudent(" + enrollId + ")", student);
}
public static String getNestedValue(Course course, String enrollId, String nestedPropertyName)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
return (String) PropertyUtils.getNestedProperty(
course, "enrolledStudent(" + enrollId + ")." + nestedPropertyName);
}
}
@@ -0,0 +1,13 @@
package com.baeldung.commons.beanutils;
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,12 @@
package com.baeldung.jmh;
import org.openjdk.jmh.annotations.Benchmark;
public class BenchMark {
@Benchmark
public void init() {
}
}
@@ -0,0 +1,12 @@
package com.baeldung.jmh;
import java.io.IOException;
import org.openjdk.jmh.Main;
import org.openjdk.jmh.runner.RunnerException;
public class JmhDemo {
public static void main(String[] args) throws RunnerException, IOException {
Main.main(args);
}
}
@@ -0,0 +1,19 @@
package com.baeldung.jmh.warmup;
public class MainApplication {
static {
long start = System.nanoTime();
ManualClassLoader.load();
long end = System.nanoTime();
System.out.println("Warm Up time : " + (end - start));
}
public static void main(String[] args) {
long start = System.nanoTime();
ManualClassLoader.load();
long end = System.nanoTime();
System.out.println("Total time taken : " + (end - start));
}
}
@@ -0,0 +1,17 @@
package com.baeldung.jmh.warmup;
import com.baeldung.jmh.warmup.dummy.Dummy;
public class ManualClassLoader {
public static void load() {
for (int i = 0; i < 100000; i++) {
// load all(or most) important classes
Dummy dummy = new Dummy();
dummy.m();
}
}
}
@@ -0,0 +1,9 @@
package com.baeldung.jmh.warmup.dummy;
public class Dummy {
public void m() {
}
}
@@ -0,0 +1,20 @@
package com.baeldung.netty;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class ClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
RequestData msg = new RequestData();
msg.setIntValue(123);
msg.setStringValue("all work and no play makes jack a dull boy");
ctx.writeAndFlush(msg);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println(msg);
ctx.close();
}
}
@@ -0,0 +1,37 @@
package com.baeldung.netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
public class NettyClient {
public static void main(String[] args) throws Exception {
String host = "localhost";
int port = 8080;
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new RequestDataEncoder(), new ResponseDataDecoder(), new ClientHandler());
}
});
ChannelFuture f = b.connect(host, port).sync();
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
}
}
@@ -0,0 +1,49 @@
package com.baeldung.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class NettyServer {
private int port;
public NettyServer(int port) {
this.port = port;
}
public static void main(String[] args) throws Exception {
int port;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
} else {
port = 8080;
}
new NettyServer(port).run();
}
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new RequestDecoder(), new ResponseDataEncoder(), new ProcessingHandler());
}
}).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.bind(port).sync();
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
@@ -0,0 +1,19 @@
package com.baeldung.netty;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class ProcessingHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
RequestData requestData = (RequestData) msg;
ResponseData responseData = new ResponseData();
responseData.setIntValue(requestData.getIntValue() * 2);
ChannelFuture future = ctx.writeAndFlush(responseData);
future.addListener(ChannelFutureListener.CLOSE);
System.out.println(requestData);
}
}
@@ -0,0 +1,30 @@
package com.baeldung.netty;
public class RequestData {
private int intValue;
private String stringValue;
public int getIntValue() {
return intValue;
}
public void setIntValue(int intValue) {
this.intValue = intValue;
}
public String getStringValue() {
return stringValue;
}
public void setStringValue(String stringValue) {
this.stringValue = stringValue;
}
@Override
public String toString() {
return "RequestData{" +
"intValue=" + intValue +
", stringValue='" + stringValue + '\'' +
'}';
}
}
@@ -0,0 +1,19 @@
package com.baeldung.netty;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import java.nio.charset.Charset;
public class RequestDataEncoder extends MessageToByteEncoder<RequestData> {
private final Charset charset = Charset.forName("UTF-8");
@Override
protected void encode(ChannelHandlerContext ctx, RequestData msg, ByteBuf out) throws Exception {
out.writeInt(msg.getIntValue());
out.writeInt(msg.getStringValue().length());
out.writeCharSequence(msg.getStringValue(), charset);
}
}
@@ -0,0 +1,22 @@
package com.baeldung.netty;
import java.nio.charset.Charset;
import java.util.List;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
public class RequestDecoder extends ReplayingDecoder<RequestData> {
private final Charset charset = Charset.forName("UTF-8");
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
RequestData data = new RequestData();
data.setIntValue(in.readInt());
int strLen = in.readInt();
data.setStringValue(in.readCharSequence(strLen, charset).toString());
out.add(data);
}
}
@@ -0,0 +1,20 @@
package com.baeldung.netty;
public class ResponseData {
private int intValue;
public int getIntValue() {
return intValue;
}
public void setIntValue(int intValue) {
this.intValue = intValue;
}
@Override
public String toString() {
return "ResponseData{" +
"intValue=" + intValue +
'}';
}
}
@@ -0,0 +1,17 @@
package com.baeldung.netty;
import java.util.List;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
public class ResponseDataDecoder extends ReplayingDecoder<ResponseData> {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
ResponseData data = new ResponseData();
data.setIntValue(in.readInt());
out.add(data);
}
}
@@ -0,0 +1,13 @@
package com.baeldung.netty;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
public class ResponseDataEncoder extends MessageToByteEncoder<ResponseData> {
@Override
protected void encode(ChannelHandlerContext ctx, ResponseData msg, ByteBuf out) throws Exception {
out.writeInt(msg.getIntValue());
}
}
@@ -0,0 +1,39 @@
package com.baeldung.netty;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class SimpleProcessingHandler extends ChannelInboundHandlerAdapter {
private ByteBuf tmp;
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
System.out.println("Handler added");
tmp = ctx.alloc().buffer(4);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
System.out.println("Handler removed");
tmp.release();
tmp = null;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf m = (ByteBuf) msg;
tmp.writeBytes(m);
m.release();
if (tmp.readableBytes() >= 4) {
RequestData requestData = new RequestData();
requestData.setIntValue(tmp.readInt());
ResponseData responseData = new ResponseData();
responseData.setIntValue(requestData.getIntValue() * 2);
ChannelFuture future = ctx.writeAndFlush(responseData);
future.addListener(ChannelFutureListener.CLOSE);
}
}
}
@@ -0,0 +1,188 @@
package com.baeldung.opennlp;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.logging.Logger;
import opennlp.tools.chunker.ChunkerME;
import opennlp.tools.chunker.ChunkerModel;
import opennlp.tools.cmdline.postag.POSModelLoader;
import opennlp.tools.doccat.DoccatFactory;
import opennlp.tools.doccat.DoccatModel;
import opennlp.tools.doccat.DocumentCategorizerME;
import opennlp.tools.doccat.DocumentSample;
import opennlp.tools.doccat.DocumentSampleStream;
import opennlp.tools.namefind.NameFinderME;
import opennlp.tools.namefind.TokenNameFinderModel;
import opennlp.tools.postag.POSModel;
import opennlp.tools.postag.POSSample;
import opennlp.tools.postag.POSTaggerME;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
import opennlp.tools.tokenize.Tokenizer;
import opennlp.tools.tokenize.TokenizerME;
import opennlp.tools.tokenize.TokenizerModel;
import opennlp.tools.tokenize.WhitespaceTokenizer;
import opennlp.tools.util.InputStreamFactory;
import opennlp.tools.util.InvalidFormatException;
import opennlp.tools.util.ObjectStream;
import opennlp.tools.util.PlainTextByLineStream;
import opennlp.tools.util.Span;
import opennlp.tools.util.TrainingParameters;
public class OpenNLP {
private final static Logger LOGGER = Logger.getLogger(OpenNLP.class.getName());
private final static String text = buildString();
private final static String sentence[] = new String[] { "James", "Jordan", "live", "in", "Oklahoma", "city", "." };
private DoccatModel docCatModel;
public static void main(String[] args) {
new OpenNLP();
}
public static String buildString(){
StringBuilder sb = new StringBuilder();
sb.append("To get to the south:");
sb.append(" Go to the store.");
sb.append(" Buy a compass.");
sb.append(" Use the compass.");
sb.append(" Then walk to the south.");
return sb.toString();
}
public OpenNLP() {
try {
sentenceDetector();
tokenizer();
nameFinder();
locationFinder();
trainDocumentCategorizer();
documentCategorizer();
partOfSpeechTagger();
chunker();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sentenceDetector() throws InvalidFormatException, IOException {
InputStream is = new FileInputStream("OpenNLP/en-sent.bin");
SentenceModel model = new SentenceModel(is);
SentenceDetectorME sdetector = new SentenceDetectorME(model);
String sentences[] = sdetector.sentDetect(text);
for (String sentence : sentences) {
LOGGER.info(sentence);
}
is.close();
}
public void tokenizer() throws InvalidFormatException, IOException {
InputStream is = new FileInputStream("OpenNLP/en-token.bin");
TokenizerModel model = new TokenizerModel(is);
Tokenizer tokenizer = new TokenizerME(model);
String tokens[] = tokenizer.tokenize(text);
for (String token : tokens) {
LOGGER.info(token);
}
is.close();
}
public static void nameFinder() throws IOException {
InputStream is = new FileInputStream("OpenNLP/en-ner-person.bin");
TokenNameFinderModel model = new TokenNameFinderModel(is);
is.close();
NameFinderME nameFinder = new NameFinderME(model);
Span nameSpans[] = nameFinder.find(sentence);
String[] names = Span.spansToStrings(nameSpans, sentence);
Arrays.stream(names).forEach(LOGGER::info);
for (String name : names) {
LOGGER.info(name);
}
}
public static void locationFinder() throws IOException {
InputStream is = new FileInputStream("OpenNLP/en-ner-location.bin");
TokenNameFinderModel model = new TokenNameFinderModel(is);
is.close();
NameFinderME nameFinder = new NameFinderME(model);
Span locationSpans[] = nameFinder.find(sentence);
String[] locations = Span.spansToStrings(locationSpans, sentence);
Arrays.stream(locations).forEach(LOGGER::info);
for (String location : locations) {
LOGGER.info(location);
}
}
public void trainDocumentCategorizer() {
try {
InputStreamFactory isf = new InputStreamFactory() {
public InputStream createInputStream() throws IOException {
return new FileInputStream("OpenNLP/doc-cat.train");
}
};
ObjectStream<String> lineStream = new PlainTextByLineStream(isf, "UTF-8");
ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);
DoccatFactory docCatFactory = new DoccatFactory();
docCatModel = DocumentCategorizerME.train("en", sampleStream, TrainingParameters.defaultParams(), docCatFactory);
} catch (IOException e) {
e.printStackTrace();
}
}
public void documentCategorizer() {
DocumentCategorizerME myCategorizer = new DocumentCategorizerME(docCatModel);
double[] outcomes = myCategorizer.categorize(sentence);
String category = myCategorizer.getBestCategory(outcomes);
if (category.equalsIgnoreCase("GOOD")) {
LOGGER.info("Document is positive :) ");
} else {
LOGGER.info("Document is negative :( ");
}
}
public static void partOfSpeechTagger() throws IOException {
try {
POSModel posModel = new POSModelLoader().load(new File("OpenNLP/en-pos-maxent.bin"));
POSTaggerME posTaggerME = new POSTaggerME(posModel);
InputStreamFactory isf = new InputStreamFactory() {
public InputStream createInputStream() throws IOException {
return new FileInputStream("OpenNLP/PartOfSpeechTag.txt");
}
};
ObjectStream<String> lineStream = new PlainTextByLineStream(isf, "UTF-8");
String line;
while ((line = lineStream.read()) != null) {
String whitespaceTokenizerLine[] = WhitespaceTokenizer.INSTANCE.tokenize(line);
String[] tags = posTaggerME.tag(whitespaceTokenizerLine);
POSSample posSample = new POSSample(whitespaceTokenizerLine, tags);
LOGGER.info(posSample.toString());
}
lineStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void chunker() throws IOException {
InputStream is = new FileInputStream("OpenNLP/en-chunker.bin");
ChunkerModel cModel = new ChunkerModel(is);
ChunkerME chunkerME = new ChunkerME(cModel);
String[] taggedSentence = new String[] {"Out", "of", "the", "night", "that", "covers", "me"};
String pos[] = new String[] { "IN", "IN", "DT", "NN", "WDT", "VBZ", "PRP"};
String chunks[] = chunkerME.chunk(taggedSentence, pos);
for (String chunk : chunks) {
LOGGER.info(chunk);
}
}
}
@@ -0,0 +1,13 @@
package com.baeldung.quartz;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class JobA implements Job {
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("This is the job A");
}
}
@@ -0,0 +1,13 @@
package com.baeldung.quartz;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class JobB implements Job {
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("This is the job B");
}
}
@@ -21,6 +21,8 @@ public class QuartzExample {
JobDetail job = JobBuilder.newJob(SimpleJob.class)
.withIdentity("myJob", "group1")
.usingJobData("jobSays", "Hello World!")
.usingJobData("myFloatValue", 3.141f)
.build();
Trigger trigger = TriggerBuilder.newTrigger()
@@ -30,8 +32,36 @@ public class QuartzExample {
.withIntervalInSeconds(40)
.repeatForever())
.build();
JobDetail jobA = JobBuilder.newJob(JobA.class)
.withIdentity("jobA", "group2")
.build();
JobDetail jobB = JobBuilder.newJob(JobB.class)
.withIdentity("jobB", "group2")
.build();
Trigger triggerA = TriggerBuilder.newTrigger()
.withIdentity("triggerA", "group2")
.startNow()
.withPriority(15)
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(40)
.repeatForever())
.build();
Trigger triggerB = TriggerBuilder.newTrigger()
.withIdentity("triggerB", "group2")
.startNow()
.withPriority(10)
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(20)
.repeatForever())
.build();
sched.scheduleJob(job, trigger);
sched.scheduleJob(jobA, triggerA);
sched.scheduleJob(jobB, triggerB);
sched.start();
} catch (SchedulerException e) {
@@ -1,13 +1,21 @@
package com.baeldung.quartz;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class SimpleJob implements Job {
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("This is a quartz job!");
public void execute(JobExecutionContext context) throws JobExecutionException {
JobDataMap dataMap = context.getJobDetail()
.getJobDataMap();
String jobSays = dataMap.getString("jobSays");
float myFloatValue = dataMap.getFloat("myFloatValue");
System.out.println("Job says: " + jobSays + ", and val is: " + myFloatValue);
}
}
@@ -0,0 +1,38 @@
package com.baeldung.commons.beanutils;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public class CourseServiceTest {
@Test
public void givenCourse_whenSetValuesUsingPropertyUtil_thenReturnSetValues()
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Course course = new Course();
String name = "Computer Science";
List<String> codes = Arrays.asList("CS", "CS01");
CourseService.setValues(course, name, codes);
Assert.assertEquals(name, course.getName());
Assert.assertEquals(2, course.getCodes().size());
Assert.assertEquals("CS", course.getCodes().get(0));
CourseService.setIndexedValue(course, 1, "CS02");
Assert.assertEquals("CS02", course.getCodes().get(1));
Student student = new Student();
String studentName = "Joe";
student.setName(studentName);
CourseService.setMappedValue(course, "ST-1", student);
Assert.assertEquals(student, course.getEnrolledStudent("ST-1"));
String accessedStudentName = CourseService.getNestedValue(course, "ST-1", "name");
Assert.assertEquals(studentName, accessedStudentName);
}
}
@@ -0,0 +1,83 @@
package com.baeldung.commons.collections;
import org.apache.commons.collections4.SetUtils;
import org.apache.commons.collections4.set.TransformedSet;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by smatt on 21/06/2017.
*/
public class SetUtilsUnitTest {
@Test(expected = IllegalArgumentException.class)
public void givenSetAndPredicate_whenPredicatedSet_thenValidateSet_and_throw_IllegalArgumentException() {
Set<String> sourceSet = new HashSet<>();
sourceSet.addAll(Arrays.asList("London", "Lagos", "Err Source1"));
Set<String> validatingSet
= SetUtils.predicatedSet(sourceSet, (s) -> s.startsWith("L"));
validatingSet.add("Err Source2");
}
@Test
public void givenTwoSets_whenDifference_thenSetView() {
Set<Integer> a = new HashSet<>(Arrays.asList(1,2,5));
Set<Integer> b = new HashSet<>(Arrays.asList(1,2));
SetUtils.SetView<Integer> result = SetUtils.difference(a, b);
assertTrue(result.size() == 1 && result.contains(5));
}
@Test
public void givenTwoSets_whenUnion_thenUnionResult() {
Set<Integer> a = new HashSet<>(Arrays.asList(1,2,5));
Set<Integer> b = new HashSet<>(Arrays.asList(1,2));
Set<Integer> expected = new HashSet<>(Arrays.asList(1,2,5));
SetUtils.SetView<Integer> union = SetUtils.union(a, b);
assertTrue(SetUtils.isEqualSet(expected, union));
}
@Test
public void givenTwoSets_whenIntersection_thenIntersectionResult() {
Set<Integer> a = new HashSet<>(Arrays.asList(1,2,5));
Set<Integer> b = new HashSet<>(Arrays.asList(1,2));
Set<Integer> expected = new HashSet<>(Arrays.asList(1,2));
SetUtils.SetView<Integer> intersect = SetUtils.intersection(a, b);
assertTrue(SetUtils.isEqualSet(expected, intersect));
}
@Test
public void givenSet_whenTransformedSet_thenTransformedResult() {
Set<Integer> a = SetUtils.transformedSet(new HashSet<>(), (e) -> e * 2 );
a.add(2);
assertEquals(a.toArray()[0], 4);
Set<Integer> source = new HashSet<>(Arrays.asList(1));
Set<Integer> newSet = TransformedSet.transformedSet(source, (e) -> e * 2);
assertEquals(newSet.toArray()[0], 2);
assertEquals(source.toArray()[0], 2);
}
@Test
public void givenTwoSet_whenDisjunction_thenDisjunctionSet() {
Set<Integer> a = new HashSet<>(Arrays.asList(1,2,5));
Set<Integer> b = new HashSet<>(Arrays.asList(1,2,3));
SetUtils.SetView<Integer> result = SetUtils.disjunction(a, b);
assertTrue(result.toSet().contains(5) && result.toSet().contains(3));
}
@Test
public void givenSet_when_OrderedSet_thenMaintainElementOrder() {
Set<Integer> set = new HashSet<>(Arrays.asList(10,1,5));
System.out.println("unordered set: " + set);
Set<Integer> orderedSet = SetUtils.orderedSet(new HashSet<>());
orderedSet.addAll(Arrays.asList(10,1,5));
System.out.println("ordered set = " + orderedSet);
}
}
@@ -0,0 +1,211 @@
package com.baeldung.commons.collections.orderedmap;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.OrderedMap;
import org.apache.commons.collections4.OrderedMapIterator;
import org.apache.commons.collections4.map.LinkedMap;
import org.apache.commons.collections4.map.ListOrderedMap;
import org.junit.Before;
import org.junit.Test;
public class OrderedMapUnitTest {
private String[] names = {"Emily", "Mathew", "Rose", "John", "Anna"};
private Integer[] ages = {37, 28, 40, 36, 21};
private int RUNNERS_COUNT = names.length;
private OrderedMap<String, Integer> runnersLinkedMap;
private OrderedMap<String, Integer> runnersListOrderedMap;
@Before
public void createRunners() {
// First implementation: ListOrderedMap
this.runnersListOrderedMap = new ListOrderedMap<>();
this.loadOrderedMapOfRunners(this.runnersListOrderedMap);
// Second implementation: LinkedMap
this.runnersLinkedMap = new LinkedMap<>();
this.loadOrderedMapOfRunners(this.runnersLinkedMap);
}
private void loadOrderedMapOfRunners(OrderedMap<String, Integer> runners) {
for (int i = 0; i < RUNNERS_COUNT; i++) {
runners.put(this.names[i], this.ages[i]);
}
}
@Test
public void givenALinkedMap_whenIteratedWithMapIterator_thenPreservesOrder() {
// Tests that the order in map iterator is the same
// as defined in the constant arrays of names and ages:
OrderedMapIterator<String, Integer> runnersIterator = this.runnersLinkedMap.mapIterator();
int i = 0;
while (runnersIterator.hasNext()) {
runnersIterator.next();
assertEquals(runnersIterator.getKey(), this.names[i]);
assertEquals(runnersIterator.getValue(), this.ages[i]);
i++;
}
}
@Test
public void givenAListOrderedMap_whenIteratedWithMapIterator_thenPreservesOrder() {
// Tests that the order in map iterator is the same
// as defined in the constant arrays of names and ages:
OrderedMapIterator<String, Integer> runnersIterator = this.runnersListOrderedMap.mapIterator();
int i = 0;
while (runnersIterator.hasNext()) {
runnersIterator.next();
assertEquals(runnersIterator.getKey(), this.names[i]);
assertEquals(runnersIterator.getValue(), this.ages[i]);
i++;
}
}
@Test
public void givenALinkedMap_whenIteratedForwards_thenPreservesOrder() {
// Tests that the order in the forward iteration is the same
// as defined in the constant arrays of names and ages
String name = this.runnersLinkedMap.firstKey();
int i = 0;
while (name != null) {
assertEquals(name, this.names[i]);
name = this.runnersLinkedMap.nextKey(name);
i++;
}
}
@Test
public void givenAListOrderedMap_whenIteratedForwards_thenPreservesOrder() {
// Tests that the order in the forward iteration is the same
// as defined in the constant arrays of names and ages
String name = this.runnersListOrderedMap.firstKey();
int i = 0;
while (name != null) {
assertEquals(name, this.names[i]);
name = this.runnersListOrderedMap.nextKey(name);
i++;
}
}
@Test
public void givenALinkedMap_whenIteratedBackwards_thenPreservesOrder() {
// Tests that the order in the backwards iteration is the same
// as defined in the constant arrays of names and ages
String name = this.runnersLinkedMap.lastKey();
int i = RUNNERS_COUNT - 1;
while (name != null) {
assertEquals(name, this.names[i]);
name = this.runnersLinkedMap.previousKey(name);
i--;
}
}
@Test
public void givenAListOrderedMap_whenIteratedBackwards_thenPreservesOrder() {
// Tests that the order in the backwards iteration is the same
// as defined in the constant arrays of names and ages
String name = this.runnersListOrderedMap.lastKey();
int i = RUNNERS_COUNT - 1;
while (name != null) {
assertEquals(name, this.names[i]);
name = this.runnersListOrderedMap.previousKey(name);
i--;
}
}
@Test
public void givenALinkedMap_whenObjectIsSearched_thenMatchesConstantArray() {
assertEquals(ages[4], this.runnersLinkedMap.get("Anna"));
}
@Test
public void givenALinkedMap_whenConvertedToList_thenMatchesKeySet() {
// Casting the OrderedMap to a LinkedMap we can use asList() method
LinkedMap<String, Integer> lmap = (LinkedMap<String, Integer>) this.runnersLinkedMap;
List<String> listKeys = new ArrayList<>();
listKeys.addAll(this.runnersLinkedMap.keySet());
List<String> linkedMap = lmap.asList();
assertEquals(listKeys, linkedMap);
}
@Test
public void givenALinkedMap_whenSearchByIndexIsUsed_thenMatchesConstantArray() {
LinkedMap<String, Integer> lmap = (LinkedMap<String, Integer>) this.runnersLinkedMap;
for (int i = 0; i < RUNNERS_COUNT; i++) {
// accessed by index:
String name = lmap.get(i);
assertEquals(name, this.names[i]);
// index of key concides with position in array
assertEquals(lmap.indexOf(this.names[i]), i);
}
}
@Test
public void givenALinkedMap_whenElementRemoved_thenSizeDecrease() {
LinkedMap<String, Integer> lmap = (LinkedMap<String, Integer>) this.runnersLinkedMap;
Integer johnAge = lmap.remove("John");// by object
assertEquals(johnAge, new Integer(36));
assertEquals(lmap.size(), RUNNERS_COUNT - 1);
Integer emilyAge = lmap.remove(0);// by index
assertEquals(emilyAge, new Integer(37));
assertEquals(lmap.size(), RUNNERS_COUNT - 2);
}
@Test
public void givenAListOrderedMap_whenObjectIsSearched_thenMatchesConstantArray() {
assertEquals(ages[4], this.runnersListOrderedMap.get("Anna"));
}
@Test
public void givenAListOrderedMap_whenConvertedToList_thenMatchesKeySet() {
ListOrderedMap<String, Integer> lomap = (ListOrderedMap<String, Integer>) this.runnersListOrderedMap;
List<String> listKeys = new ArrayList<>();
listKeys.addAll(this.runnersListOrderedMap.keySet());
List<String> lomapList = lomap.asList();
assertEquals(listKeys, lomapList);
}
@Test
public void givenAListOrderedMap_whenSearchByIndexIsUsed_thenMatchesConstantArray() {
ListOrderedMap<String, Integer> lomap = (ListOrderedMap<String, Integer>) this.runnersListOrderedMap;
for (int i = 0; i < RUNNERS_COUNT; i++) {
// accessed by index:
String name = lomap.get(i);
assertEquals(name, this.names[i]);
// index of key concides with position in array
assertEquals(lomap.indexOf(this.names[i]), i);
}
}
@Test
public void givenAListOrderedMap_whenElementRemoved_thenSizeDecrease() {
ListOrderedMap<String, Integer> lomap = (ListOrderedMap<String, Integer>) this.runnersListOrderedMap;
Integer johnAge = lomap.remove("John");// by object
assertEquals(johnAge, new Integer(36));
assertEquals(lomap.size(), RUNNERS_COUNT - 1);
Integer emilyAge = lomap.remove(0);// by index
assertEquals(emilyAge, new Integer(37));
assertEquals(lomap.size(), RUNNERS_COUNT - 2);
}
}
@@ -2,77 +2,78 @@ package com.baeldung.commons.lang3;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class ArrayUtilsUnitTest {
@Test
public void givenArray_whenAddingElementAtSpecifiedPosition_thenCorrect() {
int[] oldArray = { 2, 3, 4, 5 };
int[] oldArray = {2, 3, 4, 5};
int[] newArray = ArrayUtils.add(oldArray, 0, 1);
int[] expectedArray = { 1, 2, 3, 4, 5 };
int[] expectedArray = {1, 2, 3, 4, 5};
assertArrayEquals(expectedArray, newArray);
}
@Test
public void givenArray_whenAddingElementAtTheEnd_thenCorrect() {
int[] oldArray = { 2, 3, 4, 5 };
int[] oldArray = {2, 3, 4, 5};
int[] newArray = ArrayUtils.add(oldArray, 1);
int[] expectedArray = { 2, 3, 4, 5, 1 };
int[] expectedArray = {2, 3, 4, 5, 1};
assertArrayEquals(expectedArray, newArray);
}
@Test
public void givenArray_whenAddingAllElementsAtTheEnd_thenCorrect() {
int[] oldArray = { 0, 1, 2 };
int[] oldArray = {0, 1, 2};
int[] newArray = ArrayUtils.addAll(oldArray, 3, 4, 5);
int[] expectedArray = { 0, 1, 2, 3, 4, 5 };
int[] expectedArray = {0, 1, 2, 3, 4, 5};
assertArrayEquals(expectedArray, newArray);
}
@Test
public void givenArray_whenRemovingElementAtSpecifiedPosition_thenCorrect() {
int[] oldArray = { 1, 2, 3, 4, 5 };
int[] oldArray = {1, 2, 3, 4, 5};
int[] newArray = ArrayUtils.remove(oldArray, 1);
int[] expectedArray = { 1, 3, 4, 5 };
int[] expectedArray = {1, 3, 4, 5};
assertArrayEquals(expectedArray, newArray);
}
@Test
public void givenArray_whenRemovingAllElementsAtSpecifiedPositions_thenCorrect() {
int[] oldArray = { 1, 2, 3, 4, 5 };
int[] oldArray = {1, 2, 3, 4, 5};
int[] newArray = ArrayUtils.removeAll(oldArray, 1, 3);
int[] expectedArray = { 1, 3, 5 };
int[] expectedArray = {1, 3, 5};
assertArrayEquals(expectedArray, newArray);
}
@Test
public void givenArray_whenRemovingAnElement_thenCorrect() {
int[] oldArray = { 1, 2, 3, 3, 4 };
int[] oldArray = {1, 2, 3, 3, 4};
int[] newArray = ArrayUtils.removeElement(oldArray, 3);
int[] expectedArray = { 1, 2, 3, 4 };
int[] expectedArray = {1, 2, 3, 4};
assertArrayEquals(expectedArray, newArray);
}
@Test
public void givenArray_whenRemovingElements_thenCorrect() {
int[] oldArray = { 1, 2, 3, 3, 4 };
int[] oldArray = {1, 2, 3, 3, 4};
int[] newArray = ArrayUtils.removeElements(oldArray, 2, 3, 5);
int[] expectedArray = { 1, 3, 4 };
int[] expectedArray = {1, 3, 4};
assertArrayEquals(expectedArray, newArray);
}
@Test
public void givenArray_whenRemovingAllElementOccurences_thenCorrect() {
int[] oldArray = { 1, 2, 2, 2, 3 };
int[] oldArray = {1, 2, 2, 2, 3};
int[] newArray = ArrayUtils.removeAllOccurences(oldArray, 2);
int[] expectedArray = { 1, 3 };
int[] expectedArray = {1, 3};
assertArrayEquals(expectedArray, newArray);
}
@Test
public void givenArray_whenCheckingExistingElement_thenCorrect() {
int[] array = { 1, 3, 5, 7, 9 };
int[] array = {1, 3, 5, 7, 9};
boolean evenContained = ArrayUtils.contains(array, 2);
boolean oddContained = ArrayUtils.contains(array, 7);
assertEquals(false, evenContained);
@@ -81,57 +82,57 @@ public class ArrayUtilsUnitTest {
@Test
public void givenArray_whenReversingElementsWithinARange_thenCorrect() {
int[] originalArray = { 1, 2, 3, 4, 5 };
int[] originalArray = {1, 2, 3, 4, 5};
ArrayUtils.reverse(originalArray, 1, 4);
int[] expectedArray = { 1, 4, 3, 2, 5 };
int[] expectedArray = {1, 4, 3, 2, 5};
assertArrayEquals(expectedArray, originalArray);
}
@Test
public void givenArray_whenReversingAllElements_thenCorrect() {
int[] originalArray = { 1, 2, 3, 4, 5 };
int[] originalArray = {1, 2, 3, 4, 5};
ArrayUtils.reverse(originalArray);
int[] expectedArray = { 5, 4, 3, 2, 1 };
int[] expectedArray = {5, 4, 3, 2, 1};
assertArrayEquals(expectedArray, originalArray);
}
@Test
public void givenArray_whenShiftingElementsWithinARange_thenCorrect() {
int[] originalArray = { 1, 2, 3, 4, 5 };
int[] originalArray = {1, 2, 3, 4, 5};
ArrayUtils.shift(originalArray, 1, 4, 1);
int[] expectedArray = { 1, 4, 2, 3, 5 };
int[] expectedArray = {1, 4, 2, 3, 5};
assertArrayEquals(expectedArray, originalArray);
}
@Test
public void givenArray_whenShiftingAllElements_thenCorrect() {
int[] originalArray = { 1, 2, 3, 4, 5 };
int[] originalArray = {1, 2, 3, 4, 5};
ArrayUtils.shift(originalArray, 1);
int[] expectedArray = { 5, 1, 2, 3, 4 };
int[] expectedArray = {5, 1, 2, 3, 4};
assertArrayEquals(expectedArray, originalArray);
}
@Test
public void givenArray_whenExtractingElements_thenCorrect() {
int[] oldArray = { 1, 2, 3, 4, 5 };
int[] oldArray = {1, 2, 3, 4, 5};
int[] newArray = ArrayUtils.subarray(oldArray, 2, 7);
int[] expectedArray = { 3, 4, 5 };
int[] expectedArray = {3, 4, 5};
assertArrayEquals(expectedArray, newArray);
}
@Test
public void givenArray_whenSwapingElementsWithinARange_thenCorrect() {
int[] originalArray = { 1, 2, 3, 4, 5 };
int[] originalArray = {1, 2, 3, 4, 5};
ArrayUtils.swap(originalArray, 0, 3, 2);
int[] expectedArray = { 4, 5, 3, 1, 2 };
int[] expectedArray = {4, 5, 3, 1, 2};
assertArrayEquals(expectedArray, originalArray);
}
@Test
public void givenArray_whenSwapingElementsAtSpecifiedPositions_thenCorrect() {
int[] originalArray = { 1, 2, 3, 4, 5 };
int[] originalArray = {1, 2, 3, 4, 5};
ArrayUtils.swap(originalArray, 0, 3);
int[] expectedArray = { 4, 2, 3, 1, 5 };
int[] expectedArray = {4, 2, 3, 1, 5};
assertArrayEquals(expectedArray, originalArray);
}
}
@@ -8,7 +8,7 @@ public class ComplexUnitTest {
@Test
public void whenComplexPow_thenCorrect() {
Complex first = new Complex(1.0, 3.0);
Complex first = new Complex(1.0, 3.0);
Complex second = new Complex(2.0, 5.0);
Complex power = first.pow(second);
@@ -35,9 +35,9 @@ public class WordCountIntegrationTest {
//then
List<Tuple2<String, Integer>> collect = result.collect();
assertThat(collect).containsExactlyInAnyOrder(
new Tuple2<>("a", 3), new Tuple2<>("sentence", 2), new Tuple2<>("word", 1),
new Tuple2<>("is", 2), new Tuple2<>("this", 2), new Tuple2<>("second", 1),
new Tuple2<>("first", 1), new Tuple2<>("with", 1), new Tuple2<>("one", 1));
new Tuple2<>("a", 3), new Tuple2<>("sentence", 2), new Tuple2<>("word", 1),
new Tuple2<>("is", 2), new Tuple2<>("this", 2), new Tuple2<>("second", 1),
new Tuple2<>("first", 1), new Tuple2<>("with", 1), new Tuple2<>("one", 1));
}
@Test
@@ -48,9 +48,9 @@ public class WordCountIntegrationTest {
//when
List<Integer> collect = amounts
.filter(a -> a > threshold)
.reduce((integer, t1) -> integer + t1)
.collect();
.filter(a -> a > threshold)
.reduce((integer, t1) -> integer + t1)
.collect();
//then
assertThat(collect.get(0)).isEqualTo(90);
@@ -78,13 +78,13 @@ public class WordCountIntegrationTest {
Tuple2<Integer, String> fourthPerson = new Tuple2<>(200, "Michael");
Tuple2<Integer, String> firstPerson = new Tuple2<>(1, "Jack");
DataSet<Tuple2<Integer, String>> transactions = env.fromElements(fourthPerson, secondPerson,
thirdPerson, firstPerson);
thirdPerson, firstPerson);
//when
List<Tuple2<Integer, String>> sorted = transactions
.sortPartition(new IdKeySelectorTransaction(), Order.ASCENDING)
.collect();
.sortPartition(new IdKeySelectorTransaction(), Order.ASCENDING)
.collect();
//then
assertThat(sorted).containsExactly(firstPerson, secondPerson, thirdPerson, fourthPerson);
@@ -99,15 +99,15 @@ public class WordCountIntegrationTest {
Tuple2<Integer, String> firstTransaction = new Tuple2<>(1, "Transaction_1");
DataSet<Tuple2<Integer, String>> transactions =
env.fromElements(firstTransaction, new Tuple2<>(12, "Transaction_2"));
env.fromElements(firstTransaction, new Tuple2<>(12, "Transaction_2"));
//when
List<Tuple2<Tuple2<Integer, String>, Tuple3<Integer, String, String>>> joined =
transactions.join(addresses)
.where(new IdKeySelectorTransaction())
.equalTo(new IdKeySelectorAddress())
.collect();
transactions.join(addresses)
.where(new IdKeySelectorTransaction())
.equalTo(new IdKeySelectorAddress())
.collect();
//then
assertThat(joined).hasSize(1);
@@ -121,7 +121,7 @@ public class WordCountIntegrationTest {
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStream<String> text
= env.fromElements("This is a first sentence", "This is a second sentence with a one word");
= env.fromElements("This is a first sentence", "This is a second sentence with a one word");
SingleOutputStreamOperator<String> upperCase = text.map(String::toUpperCase);
@@ -139,8 +139,8 @@ public class WordCountIntegrationTest {
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
SingleOutputStreamOperator<Tuple2<Integer, Long>> windowed = env.fromElements(
new Tuple2<>(16, ZonedDateTime.now().plusMinutes(25).toInstant().getEpochSecond()),
new Tuple2<>(15, ZonedDateTime.now().plusMinutes(2).toInstant().getEpochSecond())
new Tuple2<>(16, ZonedDateTime.now().plusMinutes(25).toInstant().getEpochSecond()),
new Tuple2<>(15, ZonedDateTime.now().plusMinutes(2).toInstant().getEpochSecond())
).assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<Tuple2<Integer, Long>>(Time.seconds(20)) {
@Override
public long extractTimestamp(Tuple2<Integer, Long> element) {
@@ -149,8 +149,8 @@ public class WordCountIntegrationTest {
});
SingleOutputStreamOperator<Tuple2<Integer, Long>> reduced = windowed
.windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
.maxBy(0, true);
.windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
.maxBy(0, true);
reduced.print();
@@ -1,9 +1,9 @@
package com.baeldung.hikaricp;
import java.util.List;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class HikariCPUnitTest {
@@ -4,7 +4,15 @@ package com.baeldung.javassist;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.NotFoundException;
import javassist.bytecode.*;
import javassist.bytecode.AccessFlag;
import javassist.bytecode.BadBytecode;
import javassist.bytecode.Bytecode;
import javassist.bytecode.ClassFile;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.CodeIterator;
import javassist.bytecode.FieldInfo;
import javassist.bytecode.MethodInfo;
import javassist.bytecode.Mnemonic;
import org.junit.Test;
import java.io.DataOutputStream;
@@ -66,7 +74,7 @@ public class JavasisstUnitTest {
//then
assertEquals(operations,
Arrays.asList("aload_0", "iload_1", "putfield", "aload_0", "iload_2", "putfield", "return"));
Arrays.asList("aload_0", "iload_1", "putfield", "aload_0", "iload_2", "putfield", "return"));
}
@@ -112,7 +120,7 @@ public class JavasisstUnitTest {
}
assertEquals(operations,
Arrays.asList("aload_0", "invokespecial", "return"));
Arrays.asList("aload_0", "invokespecial", "return"));
}
@@ -1,10 +1,5 @@
package com.baeldung.javatuples;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.List;
import org.javatuples.KeyValue;
import org.javatuples.LabelValue;
import org.javatuples.Pair;
@@ -13,6 +8,11 @@ import org.javatuples.Triplet;
import org.javatuples.Unit;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class JavaTuplesUnitTest {
@SuppressWarnings("unused")
@@ -26,7 +26,7 @@ public class JavaTuplesUnitTest {
Pair<String, String> pairFromList = Pair.fromIterable(collectionOfNames, 2);
String[] names = new String[] { "john", "doe", "anne" };
String[] names = new String[]{"john", "doe", "anne"};
Triplet<String, String, String> triplet2 = Triplet.fromArray(names);
}
@@ -74,11 +74,11 @@ public class JaversUnitTest {
Javers javers = JaversBuilder.javers().build();
PersonWithAddress person =
new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England")));
new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England")));
PersonWithAddress personWithNewAddress =
new PersonWithAddress(1, "Tom",
Arrays.asList(new Address("England"), new Address("USA")));
new PersonWithAddress(1, "Tom",
Arrays.asList(new Address("England"), new Address("USA")));
//when
@@ -96,10 +96,10 @@ public class JaversUnitTest {
Javers javers = JaversBuilder.javers().build();
PersonWithAddress person =
new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England")));
new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England")));
PersonWithAddress personWithNewAddress =
new PersonWithAddress(1, "Tom", Collections.emptyList());
new PersonWithAddress(1, "Tom", Collections.emptyList());
//when
@@ -24,14 +24,14 @@ public class GuideToJDOIntegrationTest {
pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:h2:mem:mypersistence");
pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa");
pumd.addProperty("javax.jdo.option.ConnectionPassword", "");
pumd.addProperty("datanucleus.autoCreateSchema", "true");
pumd.addProperty("datanucleus.autoCreateSchema", "true");
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction();
try {
tx.begin();
for (int i = 0; i < 100; i++){
for (int i = 0; i < 100; i++) {
String nam = "Product-" + i;
Product productx = new Product(nam, (double) i);
pm.makePersistent(productx);
@@ -58,7 +58,7 @@ public class GuideToJDOIntegrationTest {
pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:h2:mem:mypersistence");
pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa");
pumd.addProperty("javax.jdo.option.ConnectionPassword", "");
pumd.addProperty("datanucleus.autoCreateSchema", "true");
pumd.addProperty("datanucleus.autoCreateSchema", "true");
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
PersistenceManager pm = pmf.getPersistenceManager();
@@ -93,9 +93,7 @@ public class GuideToJDOIntegrationTest {
Query q = pm2.newQuery("SELECT FROM " + Product.class.getName() + " WHERE price == 200");
@SuppressWarnings("unchecked")
List<Product> products = (List<Product>) q.execute();
Iterator<Product> iter = products.iterator();
while (iter.hasNext()) {
Product p = iter.next();
for (Product p : products) {
assertEquals("Laptop", p.name);
}
@@ -1,8 +1,6 @@
package com.baeldung.jsonassert;
import static org.assertj.core.api.Assertions.assertThat;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
@@ -13,6 +11,8 @@ import org.skyscreamer.jsonassert.RegularExpressionValueMatcher;
import org.skyscreamer.jsonassert.comparator.ArraySizeComparator;
import org.skyscreamer.jsonassert.comparator.CustomComparator;
import static org.assertj.core.api.Assertions.assertThat;
public class JsonAssertUnitTest {
@Test
@@ -44,7 +44,7 @@ public class JsonAssertUnitTest {
@Test
public void givenDifferentOrderForJsonObject_whenAssertEquals_thenPass() throws JSONException {
String result = "{id:1,name:\"John\"}";
JSONAssert.assertEquals("{name:\"John\",id:1}", result, JSONCompareMode.STRICT);
JSONAssert.assertEquals("{name:\"John\",id:1}", result, JSONCompareMode.LENIENT);
}
@@ -55,7 +55,7 @@ public class JsonAssertUnitTest {
JSONObject actual = new JSONObject();
expected.put("id", Integer.valueOf(12345));
actual.put("id", Double.valueOf(12345));
JSONAssert.assertEquals(expected, actual, false);
JSONAssert.assertEquals(expected, actual, JSONCompareMode.LENIENT);
}
@@ -63,11 +63,11 @@ public class JsonAssertUnitTest {
@Test
public void givenNestedObjects_whenAssertEquals_thenPass() throws JSONException {
String result = "{id:1,name:\"Juergen\", address:{city:\"Hollywood\", "
+ "state:\"LA\", zip:91601}}";
+ "state:\"LA\", zip:91601}}";
JSONAssert.assertEquals("{id:1,name:\"Juergen\", address:{city:\"Hollywood\", "
+ "state:\"LA\", zip:91601}}", result, false);
+ "state:\"LA\", zip:91601}}", result, false);
}
@Test
public void whenMessageUsedInAssertion_thenDisplayMessageOnFailure() throws JSONException {
String actual = "{id:123,name:\"John\"}";
@@ -94,36 +94,36 @@ public class JsonAssertUnitTest {
JSONAssert.assertNotEquals("[1,2,3]", result, JSONCompareMode.LENIENT);
JSONAssert.assertNotEquals("[1,2,3,4,5,6]", result, JSONCompareMode.LENIENT);
}
@Test
public void whenComparingSizeOfArray_thenPass() throws JSONException {
String names = "{names:[Alex, Barbera, Charlie, Xavier]}";
JSONAssert.assertEquals(
"{names:[4]}",
names,
new ArraySizeComparator(JSONCompareMode.LENIENT));
"{names:[4]}",
names,
new ArraySizeComparator(JSONCompareMode.LENIENT));
}
@Test
public void whenComparingContentsOfArray_thenPass() throws JSONException {
String ratings = "{ratings:[3.2,3.5,4.1,5,1]}";
JSONAssert.assertEquals(
"{ratings:[1,5]}",
ratings,
new ArraySizeComparator(JSONCompareMode.LENIENT));
"{ratings:[1,5]}",
ratings,
new ArraySizeComparator(JSONCompareMode.LENIENT));
}
@Test
public void givenValueMatcher_whenComparingUsingRegex_thenPass() throws IllegalArgumentException, JSONException {
JSONAssert.assertEquals("{entry:{id:x}}", "{entry:{id:1, id:2}}",
new CustomComparator(
JSONCompareMode.STRICT,
new Customization("entry.id",
new RegularExpressionValueMatcher<Object>("\\d"))));
JSONAssert.assertNotEquals("{entry:{id:x}}", "{entry:{id:1, id:as}}",
new CustomComparator(JSONCompareMode.STRICT,
new Customization("entry.id",
new RegularExpressionValueMatcher<Object>("\\d"))));
JSONAssert.assertEquals("{entry:{id:x}}", "{entry:{id:1, id:2}}",
new CustomComparator(
JSONCompareMode.STRICT,
new Customization("entry.id",
new RegularExpressionValueMatcher<Object>("\\d"))));
JSONAssert.assertNotEquals("{entry:{id:x}}", "{entry:{id:1, id:as}}",
new CustomComparator(JSONCompareMode.STRICT,
new Customization("entry.id",
new RegularExpressionValueMatcher<Object>("\\d"))));
}
}
@@ -1,13 +1,12 @@
package com.baeldung.junitparams;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import junitparams.FileParameters;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
@RunWith(JUnitParamsRunner.class)
public class SafeAdditionUtilTest {
@@ -15,7 +14,7 @@ public class SafeAdditionUtilTest {
private SafeAdditionUtil serviceUnderTest = new SafeAdditionUtil();
@Test
@Parameters({ "1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15" })
@Parameters({"1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15"})
public void whenCalledWithAnnotationProvidedParams_thenSafeAddAndReturn(int a, int b, int expectedValue) {
assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b));
}
@@ -27,7 +26,7 @@ public class SafeAdditionUtilTest {
}
private Object[] parametersToTestAdd() {
return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } };
return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}};
}
@Test
@@ -37,7 +36,7 @@ public class SafeAdditionUtilTest {
}
private Object[] parametersForWhenCalledWithnoParam_thenLoadByNameSafeAddAndReturn() {
return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } };
return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}};
}
@Test
@@ -3,11 +3,11 @@ package com.baeldung.junitparams;
public class TestDataProvider {
public static Object[] provideBasicData() {
return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { 15, -5, 10 }, new Object[] { -5, -10, -15 } };
return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{15, -5, 10}, new Object[]{-5, -10, -15}};
}
public static Object[] provideEdgeCaseData() {
return new Object[] { new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -2, Integer.MIN_VALUE }, };
return new Object[]{new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -2, Integer.MIN_VALUE},};
}
}
@@ -0,0 +1,48 @@
package com.baeldung.lsh;
import info.debatty.java.lsh.LSHMinHash;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
public class LocalSensitiveHashingUnitTest {
@Ignore("for simplicity of the example number of input vectors is very low, that's why LSH may yield non deterministic results")
@Test()
public void givenNVectors_whenPerformLSH_thenShouldCalculateSameHashForSimilarVectors() {
//given
boolean[] vector1 = new boolean[]{true, true, true, true, true};
boolean[] vector2 = new boolean[]{false, false, false, true, false};
boolean[] vector3 = new boolean[]{false, false, true, true, false};
int sizeOfVectors = 5;
int numberOfBuckets = 10;
int stages = 4;
LSHMinHash lsh = new LSHMinHash(stages, numberOfBuckets, sizeOfVectors);
//when
int[] firstHash = lsh.hash(vector1);
int[] secondHash = lsh.hash(vector2);
int[] thirdHash = lsh.hash(vector3);
System.out.println(Arrays.toString(firstHash));
System.out.println(Arrays.toString(secondHash));
System.out.println(Arrays.toString(thirdHash));
//then
int lastIndexOfResult = stages - 1;
assertThat(firstHash[lastIndexOfResult]).isNotEqualTo(secondHash[lastIndexOfResult]);
assertThat(firstHash[lastIndexOfResult]).isNotEqualTo(thirdHash[lastIndexOfResult]);
assertThat(isCloseOrEqual(secondHash[lastIndexOfResult], thirdHash[lastIndexOfResult], numberOfBuckets)).isTrue();
}
private boolean isCloseOrEqual(int secondHash, int thirdHash, int numberOfBuckets) {
return Math.abs(secondHash - thirdHash) < numberOfBuckets / 2;
}
}
@@ -0,0 +1,151 @@
package com.baeldung.opennlp;
import opennlp.tools.chunker.ChunkerME;
import opennlp.tools.chunker.ChunkerModel;
import opennlp.tools.cmdline.postag.POSModelLoader;
import opennlp.tools.doccat.DoccatFactory;
import opennlp.tools.doccat.DoccatModel;
import opennlp.tools.doccat.DocumentCategorizerME;
import opennlp.tools.doccat.DocumentSample;
import opennlp.tools.doccat.DocumentSampleStream;
import opennlp.tools.namefind.NameFinderME;
import opennlp.tools.namefind.TokenNameFinderModel;
import opennlp.tools.postag.POSModel;
import opennlp.tools.postag.POSSample;
import opennlp.tools.postag.POSTaggerME;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
import opennlp.tools.tokenize.WhitespaceTokenizer;
import opennlp.tools.util.InputStreamFactory;
import opennlp.tools.util.ObjectStream;
import opennlp.tools.util.PlainTextByLineStream;
import opennlp.tools.util.Span;
import opennlp.tools.util.TrainingParameters;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import static org.junit.Assert.assertEquals;
public class OpenNLPTests {
private final static String text = "To get to the south: Go to the store. Buy a compass. Use the compass. Then walk to the south.";
private final static String sentence[] = new String[]{"James", "Jordan", "live", "in", "Oklahoma", "city", "."};
@Test
public void givenText_WhenDetectSentences_ThenCountSentences() {
InputStream is;
SentenceModel model;
try {
is = new FileInputStream("OpenNLP/en-sent.bin");
model = new SentenceModel(is);
SentenceDetectorME sdetector = new SentenceDetectorME(model);
String sentences[] = sdetector.sentDetect(text);
assertEquals(4, sentences.length);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void givenText_WhenDetectTokens_ThenVerifyNames() {
InputStream is;
TokenNameFinderModel model;
try {
is = new FileInputStream("OpenNLP/en-ner-person.bin");
model = new TokenNameFinderModel(is);
is.close();
NameFinderME nameFinder = new NameFinderME(model);
Span nameSpans[] = nameFinder.find(sentence);
String[] names = Span.spansToStrings(nameSpans, sentence);
assertEquals(1, names.length);
assertEquals("James Jordan", names[0]);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void givenText_WhenDetectTokens_ThenVerifyLocations() {
InputStream is;
TokenNameFinderModel model;
try {
is = new FileInputStream("OpenNLP/en-ner-location.bin");
model = new TokenNameFinderModel(is);
is.close();
NameFinderME nameFinder = new NameFinderME(model);
Span locationSpans[] = nameFinder.find(sentence);
String[] locations = Span.spansToStrings(locationSpans, sentence);
assertEquals(1, locations.length);
assertEquals("Oklahoma", locations[0]);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void givenText_WhenCategorizeDocument_ThenVerifyDocumentContent() {
DoccatModel docCatModel;
try {
InputStreamFactory isf = new InputStreamFactory() {
public InputStream createInputStream() throws IOException {
return new FileInputStream("OpenNLP/doc-cat.train");
}
};
ObjectStream<String> lineStream = new PlainTextByLineStream(isf, "UTF-8");
ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);
DoccatFactory docCatFactory = new DoccatFactory();
docCatModel = DocumentCategorizerME.train("en", sampleStream, TrainingParameters.defaultParams(), docCatFactory);
DocumentCategorizerME myCategorizer = new DocumentCategorizerME(docCatModel);
double[] outcomes = myCategorizer.categorize(sentence);
String category = myCategorizer.getBestCategory(outcomes);
assertEquals("GOOD", category);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void givenText_WhenTagDocument_ThenVerifyTaggedString() {
try {
POSModel posModel = new POSModelLoader().load(new File("OpenNLP/en-pos-maxent.bin"));
POSTaggerME posTaggerME = new POSTaggerME(posModel);
InputStreamFactory isf = new InputStreamFactory() {
public InputStream createInputStream() throws IOException {
return new FileInputStream("OpenNLP/PartOfSpeechTag.txt");
}
};
ObjectStream<String> lineStream = new PlainTextByLineStream(isf, "UTF-8");
String line;
while ((line = lineStream.read()) != null) {
String whitespaceTokenizerLine[] = WhitespaceTokenizer.INSTANCE.tokenize(line);
String[] tags = posTaggerME.tag(whitespaceTokenizerLine);
POSSample posSample = new POSSample(whitespaceTokenizerLine, tags);
assertEquals("Out_IN of_IN the_DT night_NN that_WDT covers_VBZ me_PRP", posSample.toString());
}
lineStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void givenText_WhenChunked_ThenCountChunks() {
try {
InputStream is = new FileInputStream("OpenNLP/en-chunker.bin");
ChunkerModel cModel = new ChunkerModel(is);
ChunkerME chunkerME = new ChunkerME(cModel);
String pos[] = new String[]{"NNP", "NNP", "NNP", "POS", "NNP", "NN", "VBD"};
String chunks[] = chunkerME.chunk(sentence, pos);
assertEquals(7, chunks.length);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,82 @@
package com.baeldung.pact;
import au.com.dius.pact.consumer.Pact;
import au.com.dius.pact.consumer.PactProviderRuleMk2;
import au.com.dius.pact.consumer.PactVerification;
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.model.RequestResponsePact;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
public class PactConsumerDrivenContractUnitTest {
@Rule
public PactProviderRuleMk2 mockProvider
= new PactProviderRuleMk2("test_provider", "localhost", 8080, this);
@Pact(consumer = "test_consumer")
public RequestResponsePact createPact(PactDslWithProvider builder) {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return builder
.given("test GET ")
.uponReceiving("GET REQUEST")
.path("/")
.method("GET")
.willRespondWith()
.status(200)
.headers(headers)
.body("{\"condition\": true, \"name\": \"tom\"}")
.given("test POST")
.uponReceiving("POST REQUEST")
.method("POST")
.headers(headers)
.body("{\"name\": \"Michael\"}")
.path("/create")
.willRespondWith()
.status(201)
.headers(headers)
.body("")
.toPact();
}
@Test
@PactVerification()
public void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody() {
//when
ResponseEntity<String> response
= new RestTemplate().getForEntity(mockProvider.getUrl(), String.class);
//then
assertThat(response.getStatusCode().value()).isEqualTo(200);
assertThat(response.getHeaders().get("Content-Type").contains("application/json")).isTrue();
assertThat(response.getBody()).contains("condition", "true", "name", "tom");
//and
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
String jsonBody = "{\"name\": \"Michael\"}";
//when
ResponseEntity<String> postResponse = new RestTemplate().exchange(
mockProvider.getUrl() + "/create",
HttpMethod.POST,
new HttpEntity<>(jsonBody, httpHeaders),
String.class
);
//then
assertThat(postResponse.getStatusCode().value()).isEqualTo(201);
}
}
@@ -2,9 +2,6 @@ package com.baeldung.serenity;
import net.serenitybdd.jbehave.SerenityStory;
/**
* @author aiet
*/
public class GithubUserProfilePayloadIntegrationTest extends SerenityStory {
}
@@ -0,0 +1,37 @@
package com.baeldung.serenity;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.thucydides.core.annotations.Managed;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
@RunWith(SerenityRunner.class)
public class GoogleSearchLiveTest {
@Managed(driver = "chrome")
private WebDriver browser;
@Test
public void whenGoogleBaeldungThenShouldSeeEugen() {
browser.get("https://www.google.com/ncr");
browser
.findElement(By.name("q"))
.sendKeys("baeldung", Keys.ENTER);
new WebDriverWait(browser, 5).until(visibilityOfElementLocated(By.cssSelector("._ksh")));
assertThat(browser
.findElement(By.cssSelector("._ksh"))
.getText(), containsString("Eugen (Baeldung)"));
}
}
@@ -0,0 +1,27 @@
package com.baeldung.serenity;
import com.baeldung.serenity.pageobjects.GoogleSearchPageObject;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.thucydides.core.annotations.Managed;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
@RunWith(SerenityRunner.class)
public class GoogleSearchPageObjectLiveTest {
@Managed(driver = "chrome")
private WebDriver browser;
private GoogleSearchPageObject googleSearch;
@Test
public void whenGoogleBaeldungThenShouldSeeEugen() {
googleSearch.open();
googleSearch.searchFor("baeldung");
googleSearch.resultMatches("Eugen (Baeldung)");
}
}
@@ -0,0 +1,44 @@
package com.baeldung.serenity;
import com.baeldung.serenity.screenplay.GoogleSearchResults;
import com.baeldung.serenity.screenplay.SearchForKeyword;
import com.baeldung.serenity.screenplay.StartWith;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.abilities.BrowseTheWeb;
import net.thucydides.core.annotations.Managed;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import static net.serenitybdd.screenplay.GivenWhenThen.givenThat;
import static net.serenitybdd.screenplay.GivenWhenThen.seeThat;
import static net.serenitybdd.screenplay.GivenWhenThen.then;
import static net.serenitybdd.screenplay.GivenWhenThen.when;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.hasItem;
@RunWith(SerenityRunner.class)
public class GoogleSearchScreenplayLiveTest {
@Managed(driver = "chrome")
private WebDriver browser;
private Actor kitty = Actor.named("kitty");
@Before
public void setup() {
kitty.can(BrowseTheWeb.with(browser));
}
@Test
public void whenGoogleBaeldungThenShouldSeeEugen() {
givenThat(kitty).wasAbleTo(StartWith.googleSearchPage());
when(kitty).attemptsTo(SearchForKeyword.of("baeldung"));
then(kitty).should(seeThat(GoogleSearchResults.displayed(), hasItem(containsString("Eugen (Baeldung)"))));
}
}
@@ -16,7 +16,8 @@ import static com.baeldung.serenity.membership.MemberGrade.Silver;
@RunWith(SerenityRunner.class)
public class MemberStatusIntegrationTest {
@Steps MemberStatusSteps memberSteps;
@Steps
private MemberStatusSteps memberSteps;
@Test
public void membersShouldStartWithBronzeStatus() {
@@ -42,7 +43,7 @@ public class MemberStatusIntegrationTest {
@Test
@Title("Members with 50,000 points can exchange a MacBook Pro")
public void memberWith50000PointsCanExchangeAMacbookpro(){
public void memberWith50000PointsCanExchangeAMacbookpro() {
memberSteps.aMemberHasPointsOf(50_000);
memberSteps.aMemberExchangeA(MacBookPro);
memberSteps.memberShouldHavePointsLeft();
@@ -55,7 +56,7 @@ public class MemberStatusIntegrationTest {
@Test
@Ignore
@Title("Members with 500 points should have a Gold status when added 4,000 points ($40,000)")
public void memberWith500PointsEarnsGoldAfterSpends$40000(){
public void memberWith500PointsEarnsGoldAfterSpends$40000() {
memberSteps.aMemberHasPointsOf(500);
memberSteps.theMemberSpends(40_000);
memberSteps.theMemberShouldHaveAStatusOf(Gold);
@@ -64,7 +65,7 @@ public class MemberStatusIntegrationTest {
@Test
@Ignore
@Title("Members with 100 points would have a Gold status when added 10,000 points ($100,000)")
public void memberWith100EarnsGoldAfterSpends$100000(){
public void memberWith100EarnsGoldAfterSpends$100000() {
memberSteps.aMemberHasPointsOf(100);
memberSteps.theMemberSpends(100_000);
memberSteps.theMemberShouldHaveAStatusOf(Gold);
@@ -8,25 +8,22 @@ import java.io.IOException;
import static net.serenitybdd.rest.SerenityRest.rest;
import static net.serenitybdd.rest.SerenityRest.then;
/**
* @author aiet
*/
public class GithubRestAssuredUserAPISteps {
class GithubRestAssuredUserAPISteps {
private String api;
@Step("Given the github REST API for user profile")
public void withUserProfileAPIEndpoint() {
void withUserProfileAPIEndpoint() {
api = "https://api.github.com/users/{username}";
}
@Step("When looking for {0} via the api")
public void getProfileOfUser(String username) throws IOException {
void getProfileOfUser(String username) throws IOException {
rest().get(api, username);
}
@Step("Then there should be a login field with value {0} in payload of user {0}")
public void profilePayloadShouldContainLoginValue(String username) {
void profilePayloadShouldContainLoginValue(String username) {
then().body("login", Matchers.equalTo(username));
}
@@ -14,9 +14,6 @@ import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* @author aiet
*/
public class GithubRestUserAPISteps {
private String api;
@@ -9,11 +9,8 @@ import java.io.IOException;
public class GithubUserProfilePayloadStepDefinitions {
// @Steps
// GithubRestUserAPISteps userAPISteps;
@Steps
GithubRestAssuredUserAPISteps userAPISteps;
private GithubRestAssuredUserAPISteps userAPISteps;
@Given("github user profile api")
public void givenGithubUserProfileApi() {
@@ -6,12 +6,9 @@ import net.thucydides.core.annotations.Step;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
/**
* @author aiet
*/
public class MemberStatusSteps {
Member member;
private Member member;
@Step("Given a member has {0} points")
public void aMemberHasPointsOf(int points) {
@@ -35,7 +32,7 @@ public class MemberStatusSteps {
@Pending
@Step("When the member exchange {}")
public void aMemberExchangeA(Commodity commodity){
public void aMemberExchangeA(Commodity commodity) {
//TODO
}
@@ -0,0 +1,33 @@
package com.baeldung.serenity.pageobjects;
import net.thucydides.core.annotations.DefaultUrl;
import net.thucydides.core.pages.PageObject;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
@DefaultUrl("https://www.google.com/ncr")
public class GoogleSearchPageObject extends PageObject {
@FindBy(name = "q")
private WebElement search;
@FindBy(css = "._ksh")
private WebElement result;
public void searchFor(String keyword) {
search.sendKeys(keyword, Keys.ENTER);
}
public void resultMatches(String expected) {
withTimeoutOf(5, SECONDS)
.waitFor(result)
.waitUntilVisible();
assertThat(result.getText(), containsString(expected));
}
}
@@ -0,0 +1,21 @@
package com.baeldung.serenity.screenplay;
import net.serenitybdd.core.pages.PageObject;
import net.serenitybdd.screenplay.targets.Target;
import net.thucydides.core.annotations.DefaultUrl;
/**
* @author baoqiang
*/
@DefaultUrl("https://www.google.com/ncr")
class GoogleSearchPage extends PageObject {
static final Target SEARCH_RESULT_TITLES = Target
.the("search results")
.locatedBy("._ksh");
static final Target SEARCH_INPUT_BOX = Target
.the("search input box")
.locatedBy("#lst-ib");
}
@@ -0,0 +1,21 @@
package com.baeldung.serenity.screenplay;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Question;
import net.serenitybdd.screenplay.questions.Text;
import java.util.List;
public class GoogleSearchResults implements Question<List<String>> {
public static Question<List<String>> displayed() {
return new GoogleSearchResults();
}
public List<String> answeredBy(Actor actor) {
return Text
.of(GoogleSearchPage.SEARCH_RESULT_TITLES)
.viewedBy(actor)
.asList();
}
}
@@ -0,0 +1,32 @@
package com.baeldung.serenity.screenplay;
import net.serenitybdd.core.steps.Instrumented;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Enter;
import net.thucydides.core.annotations.Step;
import org.openqa.selenium.Keys;
public class SearchForKeyword implements Task {
@Step("{0} searches for '#keyword'")
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(Enter
.theValue(keyword)
.into(GoogleSearchPage.SEARCH_INPUT_BOX)
.thenHit(Keys.RETURN));
}
private String keyword;
public SearchForKeyword(String keyword) {
this.keyword = keyword;
}
public static Task of(String keyword) {
return Instrumented
.instanceOf(SearchForKeyword.class)
.withProperties(keyword);
}
}
@@ -0,0 +1,25 @@
package com.baeldung.serenity.screenplay;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Open;
import net.thucydides.core.annotations.Step;
import static net.serenitybdd.screenplay.Tasks.instrumented;
public class StartWith implements Task {
public static StartWith googleSearchPage() {
return instrumented(StartWith.class);
}
private GoogleSearchPage googleSearchPage;
@Step("{0} starts a google search")
public <T extends Actor> void performAs(T t) {
t.attemptsTo(Open
.browserOn()
.the(googleSearchPage));
}
}
@@ -14,23 +14,21 @@ import org.springframework.test.context.ContextConfiguration;
import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS;
/**
* @author aiet
*/
@RunWith(Suite.class)
@Suite.SuiteClasses({
AdderClassDirtiesContextIntegrationTest.DirtiesContextTest.class, AdderClassDirtiesContextIntegrationTest.AnotherDirtiesContextTest.class
})
AdderClassDirtiesContextIntegrationTest.DirtiesContextTest.class, AdderClassDirtiesContextIntegrationTest.AnotherDirtiesContextTest.class
})
public class AdderClassDirtiesContextIntegrationTest {
@RunWith(SerenityRunner.class)
@ContextConfiguration(classes = AdderService.class)
public static abstract class Base {
@Steps AdderServiceSteps adderServiceSteps;
@Steps
AdderServiceSteps adderServiceSteps;
@ClassRule public static SpringIntegrationClassRule springIntegrationClassRule = new SpringIntegrationClassRule();
@ClassRule
public static SpringIntegrationClassRule springIntegrationClassRule = new SpringIntegrationClassRule();
void whenAccumulate_thenSummedUp() {
adderServiceSteps.whenAccumulate();
@@ -6,13 +6,11 @@ import org.jbehave.core.annotations.BeforeStory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
/**
* @author aiet
*/
@ContextConfiguration(classes = { AdderController.class, AdderService.class })
@ContextConfiguration(classes = {AdderController.class, AdderService.class})
public class AdderTest extends SerenityStory {
@Autowired private AdderService adderService;
@Autowired
private AdderService adderService;
@BeforeStory
public void init() {
@@ -1,9 +1,7 @@
package com.baeldung.stm;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
@@ -17,10 +17,10 @@ public class JoolMergeStreamsTest {
Stream<Integer> seq2 = Stream.of(2, 4, 6);
Stream<Integer> resultingSeq = Seq.ofType(seq1, Integer.class)
.append(seq2);
.append(seq2);
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6),
resultingSeq.collect(Collectors.toList()));
resultingSeq.collect(Collectors.toList()));
}
@Test
@@ -30,10 +30,10 @@ public class JoolMergeStreamsTest {
Stream<String> closingBracketSeq = Stream.of("]");
Stream<String> resultingStream = Seq.ofType(seq, String.class)
.append(closingBracketSeq)
.prepend(openingBracketSeq);
.append(closingBracketSeq)
.prepend(openingBracketSeq);
Assert.assertEquals(Arrays.asList("[", "foo", "bar", "]"),
resultingStream.collect(Collectors.toList()));
resultingStream.collect(Collectors.toList()));
}
}
@@ -17,10 +17,10 @@ public class MergeStreamsTest {
Stream<Integer> stream2 = Stream.of(2, 4, 6);
Stream<Integer> resultingStream = Stream.concat(stream1,
stream2);
stream2);
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6),
resultingStream.collect(Collectors.toList()));
resultingStream.collect(Collectors.toList()));
}
@Test
@@ -30,11 +30,11 @@ public class MergeStreamsTest {
Stream<Integer> stream3 = Stream.of(18, 15, 36);
Stream<Integer> resultingStream = Stream.concat(Stream.concat(stream1,
stream2),
stream3);
stream2),
stream3);
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36),
resultingStream.collect(Collectors.toList()));
resultingStream.collect(Collectors.toList()));
}
@Test
@@ -47,7 +47,7 @@ public class MergeStreamsTest {
Stream<Integer> resultingStream = Stream.of(stream1, stream2, stream3, stream4).flatMap(Function.identity());
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99),
resultingStream.collect(Collectors.toList()));
resultingStream.collect(Collectors.toList()));
}
}
@@ -19,7 +19,7 @@ public class StreamExMergeStreamsTest {
Stream<Integer> resultingStream = StreamEx.of(stream1).append(stream2);
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6),
resultingStream.collect(Collectors.toList()));
resultingStream.collect(Collectors.toList()));
}
@Test
@@ -30,12 +30,12 @@ public class StreamExMergeStreamsTest {
Stream<Integer> stream4 = Stream.of(99);
Stream<Integer> resultingStream = StreamEx.of(stream1)
.append(stream2)
.append(stream3)
.append(stream4);
.append(stream2)
.append(stream3)
.append(stream4);
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99),
resultingStream.collect(Collectors.toList()));
resultingStream.collect(Collectors.toList()));
}
@@ -46,10 +46,10 @@ public class StreamExMergeStreamsTest {
Stream<String> closingBracketStream = Stream.of("]");
Stream<String> resultingStream = StreamEx.of(stream1)
.append(closingBracketStream)
.prepend(openingBracketStream);
.append(closingBracketStream)
.prepend(openingBracketStream);
assertEquals(Arrays.asList("[", "foo", "bar", "]"),
resultingStream.collect(Collectors.toList()));
resultingStream.collect(Collectors.toList()));
}
}