This commit is contained in:
Dassi Orleando 2017-10-09 17:29:50 +01:00
commit 9fc0aa96d3
24 changed files with 858 additions and 125 deletions

View File

@ -0,0 +1,26 @@
package com.baeldung.string;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class StringTest {
@Test
public void whenCallCodePointAt_thenDecimalUnicodeReturned() {
assertEquals(97, "abcd".codePointAt(0));
}
@Test
public void whenCallConcat_thenCorrect() {
assertEquals("elephant", "elep".concat("hant"));
}
@Test
public void whenGetBytes_thenCorrect() {
byte[] byteArray = "abcd".getBytes();
byte[] expected = new byte[] { 97, 98, 99, 100 };
assertArrayEquals(expected, byteArray);
}
}

5
deeplearning4j/README.md Normal file
View File

@ -0,0 +1,5 @@
### Sample deeplearning4j Project
This is a sample project for the [deeplearning4j](https://deeplearning4j.org) library.
### Relevant Articles:
- [A Guide to deeplearning4j](http://www.baeldung.com/a-guide-to-deeplearning4j/)

33
deeplearning4j/pom.xml Normal file
View File

@ -0,0 +1,33 @@
<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.deeplearning4j</groupId>
<artifactId>deeplearning4j</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>deeplearning4j</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<dl4j.version>0.9.1</dl4j.version>
</properties>
<dependencies>
<dependency>
<groupId>org.nd4j</groupId>
<artifactId>nd4j-native-platform</artifactId>
<version>${dl4j.version}</version>
</dependency>
<dependency>
<groupId>org.deeplearning4j</groupId>
<artifactId>deeplearning4j-core</artifactId>
<version>${dl4j.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,80 @@
package com.baeldung.deeplearning4j;
import org.datavec.api.records.reader.RecordReader;
import org.datavec.api.records.reader.impl.csv.CSVRecordReader;
import org.datavec.api.split.FileSplit;
import org.datavec.api.util.ClassPathResource;
import org.deeplearning4j.datasets.datavec.RecordReaderDataSetIterator;
import org.deeplearning4j.eval.Evaluation;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.layers.DenseLayer;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.dataset.SplitTestAndTrain;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import org.nd4j.linalg.dataset.api.preprocessor.DataNormalization;
import org.nd4j.linalg.dataset.api.preprocessor.NormalizerStandardize;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import java.io.IOException;
public class IrisClassifier {
private static final int CLASSES_COUNT = 3;
private static final int FEATURES_COUNT = 4;
public static void main(String[] args) throws IOException, InterruptedException {
DataSet allData;
try (RecordReader recordReader = new CSVRecordReader(0, ',')) {
recordReader.initialize(new FileSplit(new ClassPathResource("iris.txt").getFile()));
DataSetIterator iterator = new RecordReaderDataSetIterator(recordReader, 150, FEATURES_COUNT, CLASSES_COUNT);
allData = iterator.next();
}
allData.shuffle(42);
DataNormalization normalizer = new NormalizerStandardize();
normalizer.fit(allData);
normalizer.transform(allData);
SplitTestAndTrain testAndTrain = allData.splitTestAndTrain(0.65);
DataSet trainingData = testAndTrain.getTrain();
DataSet testData = testAndTrain.getTest();
MultiLayerConfiguration configuration = new NeuralNetConfiguration.Builder()
.iterations(1000)
.activation(Activation.TANH)
.weightInit(WeightInit.XAVIER)
.learningRate(0.1)
.regularization(true).l2(0.0001)
.list()
.layer(0, new DenseLayer.Builder().nIn(FEATURES_COUNT).nOut(3)
.build())
.layer(1, new DenseLayer.Builder().nIn(3).nOut(3)
.build())
.layer(2, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.activation(Activation.SOFTMAX)
.nIn(3).nOut(CLASSES_COUNT).build())
.backprop(true).pretrain(false)
.build();
MultiLayerNetwork model = new MultiLayerNetwork(configuration);
model.init();
model.fit(trainingData);
INDArray output = model.output(testData.getFeatureMatrix());
Evaluation eval = new Evaluation(CLASSES_COUNT);
eval.eval(testData.getLabels(), output);
System.out.println(eval.stats());
}
}

View File

@ -0,0 +1,150 @@
5.1,3.5,1.4,0.2,0
4.9,3.0,1.4,0.2,0
4.7,3.2,1.3,0.2,0
4.6,3.1,1.5,0.2,0
5.0,3.6,1.4,0.2,0
5.4,3.9,1.7,0.4,0
4.6,3.4,1.4,0.3,0
5.0,3.4,1.5,0.2,0
4.4,2.9,1.4,0.2,0
4.9,3.1,1.5,0.1,0
5.4,3.7,1.5,0.2,0
4.8,3.4,1.6,0.2,0
4.8,3.0,1.4,0.1,0
4.3,3.0,1.1,0.1,0
5.8,4.0,1.2,0.2,0
5.7,4.4,1.5,0.4,0
5.4,3.9,1.3,0.4,0
5.1,3.5,1.4,0.3,0
5.7,3.8,1.7,0.3,0
5.1,3.8,1.5,0.3,0
5.4,3.4,1.7,0.2,0
5.1,3.7,1.5,0.4,0
4.6,3.6,1.0,0.2,0
5.1,3.3,1.7,0.5,0
4.8,3.4,1.9,0.2,0
5.0,3.0,1.6,0.2,0
5.0,3.4,1.6,0.4,0
5.2,3.5,1.5,0.2,0
5.2,3.4,1.4,0.2,0
4.7,3.2,1.6,0.2,0
4.8,3.1,1.6,0.2,0
5.4,3.4,1.5,0.4,0
5.2,4.1,1.5,0.1,0
5.5,4.2,1.4,0.2,0
4.9,3.1,1.5,0.1,0
5.0,3.2,1.2,0.2,0
5.5,3.5,1.3,0.2,0
4.9,3.1,1.5,0.1,0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="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>
@ -487,7 +487,7 @@
<artifactId>vavr</artifactId>
<version>${vavr.version}</version>
</dependency>
<!-- Retrofit -->
<dependency>
<groupId>com.squareup.retrofit2</groupId>
@ -503,7 +503,7 @@
<groupId>com.squareup.retrofit2</groupId>
<artifactId>adapter-rxjava</artifactId>
<version>${retrofit.version}</version>
</dependency>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>logging-interceptor</artifactId>
@ -583,8 +583,34 @@
<dependency>
<groupId>com.atlassian.fugue</groupId>
<artifactId>fugue</artifactId>
<version>3.0.0-m007</version>
<version>2.6.1</version>
</dependency>
<!-- Uncomment this in order to use the jira-rest-java-client-core API -->
<!-- <dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency> -->
<dependency>
<groupId>org.jgrapht</groupId>
<artifactId>jgrapht-core</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>com.netopyr.wurmloch</groupId>
<artifactId>wurmloch-crdt</artifactId>
<version>${crdt.version}</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j</artifactId>
<version>3.3.5</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
</dependencies>
<repositories>
<repository>
@ -606,6 +632,7 @@
</repository>
</repositories>
<properties>
<crdt.version>0.1.0</crdt.version>
<multiverse.version>0.7.0</multiverse.version>
<cglib.version>3.2.4</cglib.version>
<commons-lang.version>3.6</commons-lang.version>
@ -658,6 +685,6 @@
<protonpack.version>1.14</protonpack.version>
<unit-ri.version>1.0.3</unit-ri.version>
<cache.version>1.0.0</cache.version>
<hazelcast.version>3.8.4</hazelcast.version>
<hazelcast.version>3.8.4</hazelcast.version>
</properties>
</project>

View File

@ -0,0 +1,109 @@
package com.baeldung.docx;
import org.docx4j.dml.wordprocessingDrawing.Inline;
import org.docx4j.jaxb.Context;
import org.docx4j.model.table.TblFactory;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.BooleanDefaultTrue;
import org.docx4j.wml.Color;
import org.docx4j.wml.Drawing;
import org.docx4j.wml.ObjectFactory;
import org.docx4j.wml.P;
import org.docx4j.wml.R;
import org.docx4j.wml.RPr;
import org.docx4j.wml.Tbl;
import org.docx4j.wml.Tc;
import org.docx4j.wml.Text;
import org.docx4j.wml.Tr;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.nio.file.Files;
import java.util.List;
class Docx4jExample {
void createDocumentPackage(String outputPath, String imagePath) throws Exception {
WordprocessingMLPackage wordPackage = WordprocessingMLPackage.createPackage();
MainDocumentPart mainDocumentPart = wordPackage.getMainDocumentPart();
mainDocumentPart.addStyledParagraphOfText("Title", "Hello World!");
mainDocumentPart.addParagraphOfText("Welcome To Baeldung!");
ObjectFactory factory = Context.getWmlObjectFactory();
P p = factory.createP();
R r = factory.createR();
Text t = factory.createText();
t.setValue("Welcome To Baeldung");
r.getContent().add(t);
p.getContent().add(r);
RPr rpr = factory.createRPr();
BooleanDefaultTrue b = new BooleanDefaultTrue();
rpr.setB(b);
rpr.setI(b);
rpr.setCaps(b);
Color red = factory.createColor();
red.setVal("green");
rpr.setColor(red);
r.setRPr(rpr);
mainDocumentPart.getContent().add(p);
File image = new File(imagePath);
byte[] fileContent = Files.readAllBytes(image.toPath());
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage
.createImagePart(wordPackage, fileContent);
Inline inline = imagePart.createImageInline(
"Baeldung Image", "Alt Text", 1, 2, false);
P Imageparagraph = addImageToParagraph(inline);
mainDocumentPart.getContent().add(Imageparagraph);
int writableWidthTwips = wordPackage.getDocumentModel()
.getSections().get(0).getPageDimensions()
.getWritableWidthTwips();
int columnNumber = 3;
Tbl tbl = TblFactory.createTable(3, 3, writableWidthTwips / columnNumber);
List<Object> rows = tbl.getContent();
for (Object row : rows) {
Tr tr = (Tr) row;
List<Object> cells = tr.getContent();
for (Object cell : cells) {
Tc td = (Tc) cell;
td.getContent().add(p);
}
}
mainDocumentPart.getContent().add(tbl);
File exportFile = new File(outputPath);
wordPackage.save(exportFile);
}
boolean isTextExist(String testText) throws Docx4JException, JAXBException {
File doc = new File("helloWorld.docx");
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(doc);
MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart();
String textNodesXPath = "//w:t";
List<Object> paragraphs = mainDocumentPart.getJAXBNodesViaXPath(textNodesXPath, true);
for (Object obj : paragraphs) {
Text text = (Text) ((JAXBElement) obj).getValue();
String textValue = text.getValue();
if (textValue != null && textValue.contains(testText)) {
return true;
}
}
return false;
}
private static P addImageToParagraph(Inline inline) {
ObjectFactory factory = new ObjectFactory();
P p = factory.createP();
R r = factory.createR();
p.getContent().add(r);
Drawing drawing = factory.createDrawing();
r.getContent().add(drawing);
drawing.getAnchorOrInline().add(inline);
return p;
}
}

View File

@ -1,57 +0,0 @@
package com.baeldung.jira;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.JiraRestClientFactory;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class JiraClient {
private static final String USERNAME = "jira.user";
private static final String PASSWORD = "secret";
private static final String JIRA_URL = "http://jira.company.com";
public static void main(String[] args) {
final Issue issue = new JiraClient().getIssue("MYKEY-1234");
System.out.println(issue.getDescription());
}
private Issue getIssue(String issueKey) {
JiraRestClient restClient = getJiraRestClient();
Issue issue = restClient.getIssueClient().getIssue(issueKey).claim();
closeRestClient(restClient);
return issue;
}
private JiraRestClient getJiraRestClient() {
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
URI jiraServerUri = getJiraUri();
return factory
.createWithBasicHttpAuthentication(jiraServerUri, USERNAME, PASSWORD);
}
private URI getJiraUri() {
URI jiraServerUri = null;
try {
jiraServerUri = new URI(JIRA_URL);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return jiraServerUri;
}
private void closeRestClient(JiraRestClient restClient) {
try {
restClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,103 @@
package com.baeldung.jira;
import com.atlassian.jira.rest.client.api.IssueRestClient;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.domain.BasicVotes;
import com.atlassian.jira.rest.client.api.domain.Comment;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.api.domain.input.IssueInput;
import com.atlassian.jira.rest.client.api.domain.input.IssueInputBuilder;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
public class MyJiraClient {
private String username;
private String password;
private String jiraUrl;
private JiraRestClient restClient;
private MyJiraClient(String username, String password, String jiraUrl) {
this.username = username;
this.password = password;
this.jiraUrl = jiraUrl;
this.restClient = getJiraRestClient();
}
public static void main(String[] args) throws IOException {
MyJiraClient myJiraClient = new MyJiraClient("user.name", "pass", "http://jira.company.com");
final String issueKey = myJiraClient.createIssue("ABCD", 1L, "Issue created from JRJC");
myJiraClient.updateIssueDescription(issueKey, "This is description from my Jira Client");
Issue issue = myJiraClient.getIssue(issueKey);
System.out.println(issue.getDescription());
myJiraClient.voteForAnIssue(issue);
System.out.println(myJiraClient.getTotalVotesCount(issueKey));
myJiraClient.addComment(issue, "This is comment from my Jira Client");
List<Comment> comments = myJiraClient.getAllComments(issueKey);
comments.forEach(c -> System.out.println(c.getBody()));
myJiraClient.deleteIssue(issueKey, true);
myJiraClient.restClient.close();
}
private String createIssue(String projectKey, Long issueType, String issueSummary) {
IssueRestClient issueClient = restClient.getIssueClient();
IssueInput newIssue = new IssueInputBuilder(projectKey, issueType, issueSummary).build();
return issueClient.createIssue(newIssue).claim().getKey();
}
private Issue getIssue(String issueKey) {
return restClient.getIssueClient().getIssue(issueKey).claim();
}
private void voteForAnIssue(Issue issue) {
restClient.getIssueClient().vote(issue.getVotesUri()).claim();
}
private int getTotalVotesCount(String issueKey) {
BasicVotes votes = getIssue(issueKey).getVotes();
return votes == null ? 0 : votes.getVotes();
}
private void addComment(Issue issue, String commentBody) {
restClient.getIssueClient().addComment(issue.getCommentsUri(), Comment.valueOf(commentBody));
}
private List<Comment> getAllComments(String issueKey) {
return StreamSupport.stream(getIssue(issueKey).getComments().spliterator(), false)
.collect(Collectors.toList());
}
private void updateIssueDescription(String issueKey, String newDescription) {
IssueInput input = new IssueInputBuilder().setDescription(newDescription).build();
restClient.getIssueClient().updateIssue(issueKey, input).claim();
}
private void deleteIssue(String issueKey, boolean deleteSubtasks) {
restClient.getIssueClient().deleteIssue(issueKey, deleteSubtasks).claim();
}
private JiraRestClient getJiraRestClient() {
return new AsynchronousJiraRestClientFactory()
.createWithBasicHttpAuthentication(getJiraUri(), this.username, this.password);
}
private URI getJiraUri() {
return URI.create(this.jiraUrl);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

View File

@ -0,0 +1,153 @@
package com.baeldung.crdt;
import com.netopyr.wurmloch.crdt.GCounter;
import com.netopyr.wurmloch.crdt.GSet;
import com.netopyr.wurmloch.crdt.LWWRegister;
import com.netopyr.wurmloch.crdt.PNCounter;
import com.netopyr.wurmloch.store.LocalCrdtStore;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class CRDTTest {
@Test
public void givenGrowOnlySet_whenTwoReplicasDiverge_thenShouldMergeItWithoutAConflict() {
//given
final LocalCrdtStore crdtStore1 = new LocalCrdtStore();
final LocalCrdtStore crdtStore2 = new LocalCrdtStore();
crdtStore1.connect(crdtStore2);
final GSet<String> replica1 = crdtStore1.createGSet("ID_1");
final GSet<String> replica2 = crdtStore2.<String>findGSet("ID_1").get();
//when
replica1.add("apple");
replica2.add("banana");
//then
assertThat(replica1).contains("apple", "banana");
assertThat(replica2).contains("apple", "banana");
//when
crdtStore1.disconnect(crdtStore2);
replica1.add("strawberry");
replica2.add("pear");
assertThat(replica1).contains("apple", "banana", "strawberry");
assertThat(replica2).contains("apple", "banana", "pear");
crdtStore1.connect(crdtStore2);
//then
assertThat(replica1).contains("apple", "banana", "strawberry", "pear");
assertThat(replica2).contains("apple", "banana", "strawberry", "pear");
}
@Test
public void givenIncrementOnlyCounter_whenTwoReplicasDiverge_thenShouldMergeIt() {
//given
final LocalCrdtStore crdtStore1 = new LocalCrdtStore();
final LocalCrdtStore crdtStore2 = new LocalCrdtStore();
crdtStore1.connect(crdtStore2);
final GCounter replica1 = crdtStore1.createGCounter("ID_1");
final GCounter replica2 = crdtStore2.findGCounter("ID_1").get();
//when
replica1.increment();
replica2.increment(2L);
//then
assertThat(replica1.get()).isEqualTo(3L);
assertThat(replica2.get()).isEqualTo(3L);
//when
crdtStore1.disconnect(crdtStore2);
replica1.increment(3L);
replica2.increment(5L);
assertThat(replica1.get()).isEqualTo(6L);
assertThat(replica2.get()).isEqualTo(8L);
crdtStore1.connect(crdtStore2);
// then
assertThat(replica1.get()).isEqualTo(11L);
assertThat(replica2.get()).isEqualTo(11L);
}
@Test
public void givenPNCounter_whenReplicasDiverge_thenShouldMergeWithoutAConflict() {
// given
final LocalCrdtStore crdtStore1 = new LocalCrdtStore();
final LocalCrdtStore crdtStore2 = new LocalCrdtStore();
crdtStore1.connect(crdtStore2);
final PNCounter replica1 = crdtStore1.createPNCounter("ID_1");
final PNCounter replica2 = crdtStore2.findPNCounter("ID_1").get();
//when
replica1.increment();
replica2.decrement(2L);
//then
assertThat(replica1.get()).isEqualTo(-1L);
assertThat(replica2.get()).isEqualTo(-1L);
//when
crdtStore1.disconnect(crdtStore2);
replica1.decrement(3L);
replica2.increment(5L);
assertThat(replica1.get()).isEqualTo(-4L);
assertThat(replica2.get()).isEqualTo(4L);
crdtStore1.connect(crdtStore2);
//then
assertThat(replica1.get()).isEqualTo(1L);
assertThat(replica2.get()).isEqualTo(1L);
}
@Test
public void givenLastWriteWinsStrategy_whenReplicasDiverge_thenAfterMergeShouldKeepOnlyLastValue() {
//given
final LocalCrdtStore crdtStore1 = new LocalCrdtStore("N_1");
final LocalCrdtStore crdtStore2 = new LocalCrdtStore("N_2");
crdtStore1.connect(crdtStore2);
final LWWRegister<String> replica1 = crdtStore1.createLWWRegister("ID_1");
final LWWRegister<String> replica2 = crdtStore2.<String>findLWWRegister("ID_1").get();
//when
replica1.set("apple");
replica2.set("banana");
// then
assertThat(replica1.get()).isEqualTo("banana");
assertThat(replica2.get()).isEqualTo("banana");
// when
crdtStore1.disconnect(crdtStore2);
replica1.set("strawberry");
replica2.set("pear");
assertThat(replica1.get()).isEqualTo("strawberry");
assertThat(replica2.get()).isEqualTo("pear");
crdtStore1.connect(crdtStore2);
//then
assertThat(replica1.get()).isEqualTo("pear");
assertThat(replica2.get()).isEqualTo("pear");
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.docx;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class Docx4jReadAndWriteTest {
private static final String imagePath = "src/main/resources/image.jpg";
private static final String outputPath = "helloWorld.docx";
@Test
public void givenWordPackage_whenTextExist_thenReturnTrue() throws Exception {
Docx4jExample docx4j = new Docx4jExample();
docx4j.createDocumentPackage(outputPath, imagePath);
assertTrue(docx4j.isTextExist("Hello World!"));
assertTrue(!docx4j.isTextExist("InexistantText"));
}
}

View File

@ -0,0 +1,57 @@
package org.baeldung.mockito;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.mockito.Mockito;
public class MockitoExceptionIntegrationTest {
@Test(expected = NullPointerException.class)
public void whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class);
dictMock.getMeaning("word");
}
@Test(expected = IllegalStateException.class)
public void whenConfigVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
doThrow(IllegalStateException.class).when(dictMock)
.add(anyString(), anyString());
dictMock.add("word", "meaning");
}
@Test(expected = NullPointerException.class)
public void whenConfigNonVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred"));
dictMock.getMeaning("word");
}
@Test(expected = IllegalStateException.class)
public void whenConfigVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
doThrow(new IllegalStateException("Error occurred")).when(dictMock)
.add(anyString(), anyString());
dictMock.add("word", "meaning");
}
// =====
@Test(expected = NullPointerException.class)
public void givenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dict = new MyDictionary();
MyDictionary spy = Mockito.spy(dict);
when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class);
spy.getMeaning("word");
}
}

View File

@ -248,6 +248,7 @@
<module>mockserver</module>
<module>undertow</module>
<module>vertx-and-rxjava</module>
<module>deeplearning4j</module>
</modules>
<dependencies>

View File

@ -8,13 +8,15 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.github.davidmoten.rx.jdbc.ConnectionProvider;
import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class AutomapClassIntegrationTest {
private Database db = Database.from(Connector.connectionProvider);
private ConnectionProvider connectionProvider = Connector.connectionProvider;
private Database db = Database.from(connectionProvider);
private Observable<Integer> create = null;
private Observable<Integer> insert1, insert2 = null;
@ -56,6 +58,6 @@ public class AutomapClassIntegrationTest {
public void close() {
db.update("DROP TABLE MANAGER")
.dependsOn(create);
Connector.connectionProvider.close();
connectionProvider.close();
}
}

View File

@ -8,13 +8,15 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.github.davidmoten.rx.jdbc.ConnectionProvider;
import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class AutomapInterfaceIntegrationTest {
private Database db = Database.from(Connector.connectionProvider);
private ConnectionProvider connectionProvider = Connector.connectionProvider;
private Database db = Database.from(connectionProvider);
private Observable<Integer> create = null;
private Observable<Integer> insert1, insert2 = null;
@ -55,8 +57,7 @@ public class AutomapInterfaceIntegrationTest {
@After
public void close() {
db.update("DROP TABLE EMPLOYEE")
.dependsOn(create);
Connector.connectionProvider.close();
.dependsOn(create);
connectionProvider.close();
}
}

View File

@ -1,38 +1,42 @@
package com.baeldung.rxjava.jdbc;
import com.github.davidmoten.rx.jdbc.Database;
import org.junit.After;
import org.junit.Test;
import rx.Observable;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Test;
import com.github.davidmoten.rx.jdbc.ConnectionProvider;
import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class BasicQueryTypesIntegrationTest {
private Database db = Database.from(Connector.connectionProvider);
private ConnectionProvider connectionProvider = Connector.connectionProvider;
private Database db = Database.from(connectionProvider);
private Observable<Integer> create;
private Observable<Integer> create, insert1, insert2, insert3, update, delete = null;
@Test
public void whenCreateTableAndInsertRecords_thenCorrect() {
create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))")
.count();
Observable<Integer> insert1 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'John')")
insert1 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'John')")
.dependsOn(create)
.count();
Observable<Integer> update = db.update("UPDATE EMPLOYEE SET name = 'Alan' WHERE id = 1")
update = db.update("UPDATE EMPLOYEE SET name = 'Alan' WHERE id = 1")
.dependsOn(create)
.count();
Observable<Integer> insert2 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(2, 'Sarah')")
insert2 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(2, 'Sarah')")
.dependsOn(create)
.count();
Observable<Integer> insert3 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(3, 'Mike')")
insert3 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(3, 'Mike')")
.dependsOn(create)
.count();
Observable<Integer> delete = db.update("DELETE FROM EMPLOYEE WHERE id = 2")
delete = db.update("DELETE FROM EMPLOYEE WHERE id = 2")
.dependsOn(create)
.count();
List<String> names = db.select("select name from EMPLOYEE where id < ?")
@ -55,6 +59,6 @@ public class BasicQueryTypesIntegrationTest {
public void close() {
db.update("DROP TABLE EMPLOYEE")
.dependsOn(create);
Connector.connectionProvider.close();
connectionProvider.close();
}
}

View File

@ -1,21 +1,25 @@
package com.baeldung.rxjava.jdbc;
import com.github.davidmoten.rx.jdbc.Database;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import rx.Observable;
import static org.junit.Assert.assertEquals;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.github.davidmoten.rx.jdbc.ConnectionProvider;
import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class InsertBlobIntegrationTest {
private Database db = Database.from(Connector.connectionProvider);
private ConnectionProvider connectionProvider = Connector.connectionProvider;
private Database db = Database.from(connectionProvider);
private String expectedDocument = null;
private String actualDocument = null;
@ -56,6 +60,6 @@ public class InsertBlobIntegrationTest {
public void close() {
db.update("DROP TABLE SERVERLOG")
.dependsOn(create);
Connector.connectionProvider.close();
connectionProvider.close();
}
}
}

View File

@ -1,20 +1,24 @@
package com.baeldung.rxjava.jdbc;
import com.github.davidmoten.rx.jdbc.Database;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import rx.Observable;
import static org.junit.Assert.assertEquals;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.github.davidmoten.rx.jdbc.ConnectionProvider;
import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class InsertClobIntegrationTest {
private Database db = Database.from(Connector.connectionProvider);
private ConnectionProvider connectionProvider = Connector.connectionProvider;
private Database db = Database.from(connectionProvider);
private String expectedDocument = null;
private String actualDocument = null;
@ -54,6 +58,6 @@ public class InsertClobIntegrationTest {
public void close() {
db.update("DROP TABLE SERVERLOG")
.dependsOn(create);
Connector.connectionProvider.close();
connectionProvider.close();
}
}

View File

@ -1,24 +1,28 @@
package com.baeldung.rxjava.jdbc;
import com.github.davidmoten.rx.jdbc.Database;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import rx.Observable;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.github.davidmoten.rx.jdbc.ConnectionProvider;
import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class ReturnKeysIntegrationTest {
private Observable<Integer> createStatement;
private Observable<Boolean> begin = null;
private Observable<Integer> createStatement = null;
private Database db = Database.from(Connector.connectionProvider);
private ConnectionProvider connectionProvider = Connector.connectionProvider;
private Database db = Database.from(connectionProvider);
@Before
public void setup() {
Observable<Boolean> begin = db.beginTransaction();
createStatement = db
.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int auto_increment primary key, name varchar(255))")
begin = db.beginTransaction();
createStatement = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int auto_increment primary key, name varchar(255))")
.dependsOn(begin)
.count();
}
@ -37,7 +41,8 @@ public class ReturnKeysIntegrationTest {
@After
public void close() {
db.update("DROP TABLE EMPLOYEE");
Connector.connectionProvider.close();
db.update("DROP TABLE EMPLOYEE")
.dependsOn(createStatement);
connectionProvider.close();
}
}

View File

@ -1,15 +1,21 @@
package com.baeldung.rxjava.jdbc;
import com.github.davidmoten.rx.jdbc.Database;
import org.junit.After;
import org.junit.Test;
import rx.Observable;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Test;
import com.github.davidmoten.rx.jdbc.ConnectionProvider;
import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class TransactionIntegrationTest {
private Database db = Database.from(Connector.connectionProvider);
private Observable<Integer> createStatement = null;
private ConnectionProvider connectionProvider = Connector.connectionProvider;
private Database db = Database.from(connectionProvider);
@Test
public void whenCommitTransaction_thenRecordUpdated() {
@ -36,7 +42,8 @@ public class TransactionIntegrationTest {
@After
public void close() {
db.update("DROP TABLE EMPLOYEE");
Connector.connectionProvider.close();
db.update("DROP TABLE EMPLOYEE")
.dependsOn(createStatement);
connectionProvider.close();
}
}

View File

@ -8,4 +8,3 @@
- [Spring YAML Configuration](http://www.baeldung.com/spring-yaml)
- [Introduction to Springs StreamUtils](http://www.baeldung.com/spring-stream-utils)
- [Using Spring @Value with Defaults](http://www.baeldung.com/spring-value-defaults)

View File

@ -5,12 +5,13 @@
<artifactId>vavr</artifactId>
<version>1.0</version>
<name>vavr</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
<relativePath />
<version>1.5.6.RELEASE</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<dependencies>
@ -35,10 +36,11 @@
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>

View File

@ -43,5 +43,4 @@ public class VavrRepositoryIntegrationTest {
Seq<User> users = userRepository.findByName("John");
assertEquals(2, users.size());
}
}