diff --git a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationTests.java b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationTests.java index ddfe9325d3..cd563b6270 100644 --- a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationTests.java +++ b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationTests.java @@ -151,20 +151,20 @@ public class CayenneAdvancedOperationTests { @Test public void givenTwoAuthor_whenInObjS_thenWeGetAuthors() { - String [] args = {"Paul Xavier", "pAuL Smith", "Vicky Sarra"}; + List names = Arrays.asList("Paul Xavier", "pAuL Smith", "Vicky Sarra"); List authors = ObjectSelect.query(Author.class) - .where(Author.NAME.in(Arrays.asList(args))) - .select(context); + .where(Author.NAME.in(names)) + .select(context); assertEquals(authors.size(), 3); } @Test public void givenTwoAuthor_whenNinObjS_thenWeGetAuthors() { - String [] args = {"Paul Xavier", "pAuL Smith"}; + List names = Arrays.asList("Paul Xavier", "pAuL Smith"); List authors = ObjectSelect.query(Author.class) - .where(Author.NAME.nin(Arrays.asList(args))) - .select(context); + .where(Author.NAME.nin(names)) + .select(context); Author author = authors.get(0); assertEquals(authors.size(), 1); diff --git a/deeplearning4j/README.md b/deeplearning4j/README.md new file mode 100644 index 0000000000..729ab101fd --- /dev/null +++ b/deeplearning4j/README.md @@ -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/) diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml new file mode 100644 index 0000000000..a39fabc3d6 --- /dev/null +++ b/deeplearning4j/pom.xml @@ -0,0 +1,33 @@ + + 4.0.0 + com.baeldung.deeplearning4j + deeplearning4j + jar + 1.0-SNAPSHOT + deeplearning4j + + + UTF-8 + 1.8 + 1.8 + 0.9.1 + + + + + + org.nd4j + nd4j-native-platform + ${dl4j.version} + + + + org.deeplearning4j + deeplearning4j-core + ${dl4j.version} + + + + + \ No newline at end of file diff --git a/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/IrisClassifier.java b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/IrisClassifier.java new file mode 100644 index 0000000000..bf341209e1 --- /dev/null +++ b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/IrisClassifier.java @@ -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()); + + } + +} diff --git a/deeplearning4j/src/main/resources/iris.txt b/deeplearning4j/src/main/resources/iris.txt new file mode 100644 index 0000000000..8b4511f8be --- /dev/null +++ b/deeplearning4j/src/main/resources/iris.txt @@ -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.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 +7.2,3.2,6.0,1.8,2 +6.2,2.8,4.8,1.8,2 +6.1,3.0,4.9,1.8,2 +6.4,2.8,5.6,2.1,2 +7.2,3.0,5.8,1.6,2 +7.4,2.8,6.1,1.9,2 +7.9,3.8,6.4,2.0,2 +6.4,2.8,5.6,2.2,2 +6.3,2.8,5.1,1.5,2 +6.1,2.6,5.6,1.4,2 +7.7,3.0,6.1,2.3,2 +6.3,3.4,5.6,2.4,2 +6.4,3.1,5.5,1.8,2 +6.0,3.0,4.8,1.8,2 +6.9,3.1,5.4,2.1,2 +6.7,3.1,5.6,2.4,2 +6.9,3.1,5.1,2.3,2 +5.8,2.7,5.1,1.9,2 +6.8,3.2,5.9,2.3,2 +6.7,3.3,5.7,2.5,2 +6.7,3.0,5.2,2.3,2 +6.3,2.5,5.0,1.9,2 +6.5,3.0,5.2,2.0,2 +6.2,3.4,5.4,2.3,2 +5.9,3.0,5.1,1.8,2 diff --git a/libraries/pom.xml b/libraries/pom.xml index 15446975f3..c7c5da95a6 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -601,6 +601,16 @@ wurmloch-crdt ${crdt.version} + + org.docx4j + docx4j + 3.3.5 + + + javax.xml.bind + jaxb-api + 2.1 + diff --git a/libraries/src/main/java/com/baeldung/docx/Docx4jExample.java b/libraries/src/main/java/com/baeldung/docx/Docx4jExample.java new file mode 100644 index 0000000000..d9c87b3889 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/docx/Docx4jExample.java @@ -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 rows = tbl.getContent(); + for (Object row : rows) { + Tr tr = (Tr) row; + List 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 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; + } +} diff --git a/libraries/src/main/java/com/baeldung/jira/MyJiraClient.java b/libraries/src/main/java/com/baeldung/jira/MyJiraClient.java index 62cce56532..ea1d73f52a 100644 --- a/libraries/src/main/java/com/baeldung/jira/MyJiraClient.java +++ b/libraries/src/main/java/com/baeldung/jira/MyJiraClient.java @@ -52,7 +52,7 @@ public class MyJiraClient { myJiraClient.restClient.close(); } - public String createIssue(String projectKey, Long issueType, String issueSummary) { + private String createIssue(String projectKey, Long issueType, String issueSummary) { IssueRestClient issueClient = restClient.getIssueClient(); @@ -65,30 +65,30 @@ public class MyJiraClient { return restClient.getIssueClient().getIssue(issueKey).claim(); } - public void voteForAnIssue(Issue issue) { + private void voteForAnIssue(Issue issue) { restClient.getIssueClient().vote(issue.getVotesUri()).claim(); } - public int getTotalVotesCount(String issueKey) { + private int getTotalVotesCount(String issueKey) { BasicVotes votes = getIssue(issueKey).getVotes(); return votes == null ? 0 : votes.getVotes(); } - public void addComment(Issue issue, String commentBody) { + private void addComment(Issue issue, String commentBody) { restClient.getIssueClient().addComment(issue.getCommentsUri(), Comment.valueOf(commentBody)); } - public List getAllComments(String issueKey) { + private List getAllComments(String issueKey) { return StreamSupport.stream(getIssue(issueKey).getComments().spliterator(), false) .collect(Collectors.toList()); } - public void updateIssueDescription(String issueKey, String newDescription) { + private void updateIssueDescription(String issueKey, String newDescription) { IssueInput input = new IssueInputBuilder().setDescription(newDescription).build(); restClient.getIssueClient().updateIssue(issueKey, input).claim(); } - public void deleteIssue(String issueKey, boolean deleteSubtasks) { + private void deleteIssue(String issueKey, boolean deleteSubtasks) { restClient.getIssueClient().deleteIssue(issueKey, deleteSubtasks).claim(); } diff --git a/libraries/src/main/resources/image.jpg b/libraries/src/main/resources/image.jpg new file mode 100644 index 0000000000..e2554a0d9c Binary files /dev/null and b/libraries/src/main/resources/image.jpg differ diff --git a/libraries/src/test/java/com/baeldung/docx/Docx4jReadAndWriteTest.java b/libraries/src/test/java/com/baeldung/docx/Docx4jReadAndWriteTest.java new file mode 100644 index 0000000000..7c3f779931 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/docx/Docx4jReadAndWriteTest.java @@ -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")); + } +} diff --git a/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java b/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java index 151bcc78a2..28d4f57e77 100644 --- a/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java @@ -7,7 +7,9 @@ import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.junit.After; +import org.junit.AfterClass; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import java.nio.charset.StandardCharsets; @@ -15,17 +17,16 @@ import java.nio.charset.StandardCharsets; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; public class JettyIntegrationTest { - private JettyServer jettyServer; + private static JettyServer jettyServer; - @Before - public void setup() throws Exception { + @BeforeClass + public static void setup() throws Exception { jettyServer = new JettyServer(); jettyServer.start(); } - @After - public void cleanup() throws Exception { - Thread.sleep(2000); + @AfterClass + public static void cleanup() throws Exception { jettyServer.stop(); } diff --git a/pom.xml b/pom.xml index ff4b490c6b..c3915e4fce 100644 --- a/pom.xml +++ b/pom.xml @@ -248,6 +248,7 @@ mockserver undertow vertx-and-rxjava + deeplearning4j diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SchedulersTest.java b/rxjava/src/test/java/com/baeldung/rxjava/SchedulersTest.java index 35714566ca..05b86e52b9 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/SchedulersTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/SchedulersTest.java @@ -1,7 +1,6 @@ package com.baeldung.rxjava; import com.google.common.util.concurrent.ThreadFactoryBuilder; -import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import rx.Observable; @@ -16,9 +15,11 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; +import static com.jayway.awaitility.Awaitility.await; import static java.util.concurrent.Executors.newFixedThreadPool; import static org.hamcrest.Matchers.hasItems; import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; public class SchedulersTest { private String result = ""; @@ -31,7 +32,8 @@ public class SchedulersTest { Scheduler scheduler = Schedulers.immediate(); Scheduler.Worker worker = scheduler.createWorker(); worker.schedule(() -> result += "action"); - Assert.assertTrue(result.equals("action")); + + assertTrue(result.equals("action")); } @Test @@ -44,8 +46,9 @@ public class SchedulersTest { worker.unsubscribe(); }); worker.schedule(() -> result += "Second_Action"); - Thread.sleep(500); - Assert.assertTrue(result.equals("First_Action")); + + await() + .until(() -> assertTrue(result.equals("First_Action"))); } @Ignore //it's not safe, not every time is running correctly @@ -59,8 +62,9 @@ public class SchedulersTest { worker.schedule(() -> result += "_worker_"); result += "_End"; }); - Thread.sleep(2000); - Assert.assertTrue(result.equals("RxNewThreadScheduler-1_Start_End_worker_")); + + await() + .until(() -> assertTrue(result.equals("RxNewThreadScheduler-1_Start_End_worker_"))); } @Test @@ -75,9 +79,11 @@ public class SchedulersTest { .subscribe(s -> result1 += Thread.currentThread().getName() ); - Thread.sleep(500); - Assert.assertTrue(result1.equals("RxNewThreadScheduler-1")); - Assert.assertTrue(result2.equals("RxNewThreadScheduler-2")); + await() + .until(() -> { + assertTrue(result1.equals("RxNewThreadScheduler-1")); + assertTrue(result2.equals("RxNewThreadScheduler-2")); + }); } @Test @@ -90,8 +96,9 @@ public class SchedulersTest { worker.schedule(() -> result += "_worker_"); result += "_End"; }); - Thread.sleep(500); - Assert.assertTrue(result.equals("main_Start_worker__End")); + + await() + .until(() -> assertTrue(result.equals("main_Start_worker__End"))); } @Test @@ -102,8 +109,9 @@ public class SchedulersTest { .subscribe(s -> result += Thread.currentThread().getName() ); - Thread.sleep(500); - Assert.assertTrue(result.equals("main")); + + await() + .until(() -> assertTrue(result.equals("main"))); } @Test @@ -115,8 +123,9 @@ public class SchedulersTest { Observable.just(1, 3, 5, 7, 9) .subscribeOn(Schedulers.trampoline()) .subscribe(i -> result += "" + i); - Thread.sleep(500); - Assert.assertTrue(result.equals("246813579")); + + await() + .until(() -> assertTrue(result.equals("246813579"))); } @Test @@ -135,9 +144,9 @@ public class SchedulersTest { }); result += "_mainEnd"; }); - Thread.sleep(500); - Assert.assertTrue(result - .equals("mainStart_mainEnd_middleStart_middleEnd_worker_")); + + await() + .until(() -> assertTrue(result.equals("mainStart_mainEnd_middleStart_middleEnd_worker_"))); } private ThreadFactory threadFactory(String pattern) { @@ -159,7 +168,6 @@ public class SchedulersTest { subscriber.onNext("Beta"); subscriber.onCompleted(); }); - ; observable .subscribeOn(schedulerA) @@ -169,8 +177,9 @@ public class SchedulersTest { Throwable::printStackTrace, () -> result += "_Completed" ); - Thread.sleep(2000); - Assert.assertTrue(result.equals("Sched-A-0Alfa_Sched-A-0Beta__Completed")); + + await() + .until(() -> assertTrue(result.equals("Sched-A-0Alfa_Sched-A-0Beta__Completed"))); } @Test @@ -179,8 +188,9 @@ public class SchedulersTest { Observable.just("io") .subscribeOn(Schedulers.io()) .subscribe(i -> result += Thread.currentThread().getName()); - Thread.sleep(500); - Assert.assertTrue(result.equals("RxIoScheduler-2")); + + await() + .until(() -> assertTrue(result.equals("RxIoScheduler-2"))); } @Test @@ -189,8 +199,9 @@ public class SchedulersTest { Observable.just("computation") .subscribeOn(Schedulers.computation()) .subscribe(i -> result += Thread.currentThread().getName()); - Thread.sleep(500); - Assert.assertTrue(result.equals("RxComputationScheduler-1")); + + await() + .until(() -> assertTrue(result.equals("RxComputationScheduler-1"))); } @Test @@ -229,7 +240,7 @@ public class SchedulersTest { .delay(1, TimeUnit.SECONDS, schedulerA) .subscribe(i -> result += Thread.currentThread().getName() + i + " "); - Thread.sleep(2000); - Assert.assertTrue(result.equals("Sched1-A Sched1-B ")); + await() + .until(() -> assertTrue(result.equals("Sched1-A Sched1-B "))); } } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java index a4fc62aaf1..0b38f0387b 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java @@ -11,6 +11,7 @@ import rx.schedulers.Timestamped; import java.util.concurrent.TimeUnit; +import static com.jayway.awaitility.Awaitility.await; import static org.junit.Assert.assertTrue; public class UtilityOperatorsTest { @@ -40,9 +41,11 @@ public class UtilityOperatorsTest { + Thread.currentThread().getName()); }); - Thread.sleep(2000); - assertTrue(emittedTotal == 1500); - assertTrue(receivedTotal == 15000); + await().until(() -> { + assertTrue(emittedTotal == 1500); + assertTrue(receivedTotal == 15000); + } + ); } @Test @@ -63,9 +66,10 @@ public class UtilityOperatorsTest { + Thread.currentThread().getName()); }); - Thread.sleep(2000); - assertTrue(emittedTotal == 1500); - assertTrue(receivedTotal == 15000); + await().until(() -> { + assertTrue(emittedTotal == 1500); + assertTrue(receivedTotal == 15000); + }); } @Test @@ -86,9 +90,10 @@ public class UtilityOperatorsTest { + Thread.currentThread().getName()); }); - Thread.sleep(2000); - assertTrue(emittedTotal == 1500); - assertTrue(receivedTotal == 15000); + await().until(() -> { + assertTrue(emittedTotal == 1500); + assertTrue(receivedTotal == 15000); + }); } @Test @@ -210,7 +215,7 @@ public class UtilityOperatorsTest { value -> System.out.println("delay : " + value), t -> System.out.println("delay error"), () -> System.out.println("delay completed")); - Thread.sleep(8000); + //Thread.sleep(8000); } @Test