This commit is contained in:
Jonathan Cook
2019-10-23 15:01:44 +02:00
parent db85c8f275
commit 684ec0d2e3
20486 changed files with 1642483 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
## Libraries
This module contains articles about various Java libraries.
These are small libraries that are relatively easy to use and do not require any separate module of their own.
The code examples related to different libraries are each in their own module.
Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-modules) we already have separate modules. Please make sure to have a look at the existing modules in such cases.
### Relevant articles
- [A Guide to jBPM with Java](https://www.baeldung.com/jbpm-java)
- [Guide to Classgraph Library](https://www.baeldung.com/classgraph)
- [Create a Java Command Line Program with Picocli](https://www.baeldung.com/java-picocli-create-command-line-program)
- [Guide to Java Parallel Collectors Library](https://www.baeldung.com/java-parallel-collectors)
- [Templating with Handlebars](https://www.baeldung.com/handlebars)
- [A Guide to Crawler4j](https://www.baeldung.com/crawler4j)
- [Decode an OkHttp JSON Response](https://www.baeldung.com/okhttp-json-response)
- [Key Value Store with Chronicle Map](https://www.baeldung.com/java-chronicle-map)
- [Guide to MapDB](https://www.baeldung.com/mapdb)
- [A Guide to Apache Mesos](https://www.baeldung.com/apache-mesos)
- [JasperReports with Spring](https://www.baeldung.com/spring-jasper)
- More articles [[<-- prev]](/libraries)
+162
View File
@@ -0,0 +1,162 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>libraries-2</artifactId>
<name>libraries-2</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<repositories>
<repository>
<id>jboss-public-repository-group</id>
<name>JBoss Public Repository Group</name>
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.mapdb</groupId>
<artifactId>mapdb</artifactId>
<version>${mapdb.version}</version>
</dependency>
<dependency>
<groupId>com.pivovarit</groupId>
<artifactId>parallel-collectors</artifactId>
<version>${parallel-collectors.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
</dependency>
<dependency>
<groupId>io.github.classgraph</groupId>
<artifactId>classgraph</artifactId>
<version>${classgraph.version}</version>
</dependency>
<dependency>
<groupId>org.jbpm</groupId>
<artifactId>jbpm-test</artifactId>
<version>${jbpm.version}</version>
</dependency>
<dependency>
<groupId>info.picocli</groupId>
<artifactId>picocli</artifactId>
<version>${picocli.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${spring-boot-starter.version}</version>
</dependency>
<dependency>
<groupId>net.openhft</groupId>
<artifactId>chronicle-map</artifactId>
<version>${chronicle.map.version}</version>
<exclusions>
<exclusion>
<groupId>com.sun.java</groupId>
<artifactId>tools</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Dependencies for response decoder with okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${okhttp.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>mockwebserver</artifactId>
<version>${mockwebserver.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>edu.uci.ics</groupId>
<artifactId>crawler4j</artifactId>
<version>${crawler4j.version}</version>
</dependency>
<dependency>
<groupId>com.github.jknack</groupId>
<artifactId>handlebars</artifactId>
<version>${handlebars.version}</version>
</dependency>
<dependency>
<groupId>org.apache.mesos</groupId>
<artifactId>mesos</artifactId>
<version>${mesos.library.version}</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>${jasperreports.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
<properties>
<mapdb.version>3.0.7</mapdb.version>
<assertj.version>3.6.2</assertj.version>
<classgraph.version>4.8.28</classgraph.version>
<jbpm.version>6.0.0.Final</jbpm.version>
<picocli.version>3.9.6</picocli.version>
<chronicle.map.version>3.17.2</chronicle.map.version>
<crawler4j.version>4.4.0</crawler4j.version>
<spring-boot-starter.version>2.1.4.RELEASE</spring-boot-starter.version>
<mesos.library.version>0.28.3</mesos.library.version>
<parallel-collectors.version>1.1.0</parallel-collectors.version>
<okhttp.version>3.14.2</okhttp.version>
<gson.version>2.8.5</gson.version>
<mockwebserver.version>3.14.2</mockwebserver.version>
<handlebars.version>4.1.2</handlebars.version>
<jasperreports.version>6.6.0</jasperreports.version>
<spring.version>5.1.9.RELEASE</spring.version>
<hsqldb.version>2.5.0</hsqldb.version>
</properties>
</project>
@@ -0,0 +1,22 @@
package com.baeldung.crawler4j;
public class CrawlerStatistics {
private int processedPageCount = 0;
private int totalLinksCount = 0;
public void incrementProcessedPageCount() {
processedPageCount++;
}
public void incrementTotalLinksCount(int linksCount) {
totalLinksCount += linksCount;
}
public int getProcessedPageCount() {
return processedPageCount;
}
public int getTotalLinksCount() {
return totalLinksCount;
}
}
@@ -0,0 +1,48 @@
package com.baeldung.crawler4j;
import java.util.Set;
import java.util.regex.Pattern;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;
public class HtmlCrawler extends WebCrawler {
private final static Pattern EXCLUSIONS = Pattern.compile(".*(\\.(css|js|xml|gif|jpg|png|mp3|mp4|zip|gz|pdf))$");
private CrawlerStatistics stats;
public HtmlCrawler(CrawlerStatistics stats) {
this.stats = stats;
}
@Override
public boolean shouldVisit(Page referringPage, WebURL url) {
String urlString = url.getURL().toLowerCase();
return !EXCLUSIONS.matcher(urlString).matches()
&& urlString.startsWith("https://www.baeldung.com/");
}
@Override
public void visit(Page page) {
String url = page.getWebURL().getURL();
stats.incrementProcessedPageCount();
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String title = htmlParseData.getTitle();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
Set<WebURL> links = htmlParseData.getOutgoingUrls();
stats.incrementTotalLinksCount(links.size());
System.out.printf("Page with title '%s' %n", title);
System.out.printf(" Text length: %d %n", text.length());
System.out.printf(" HTML length: %d %n", html.length());
System.out.printf(" %d outbound links %n", links.size());
}
}
}
@@ -0,0 +1,36 @@
package com.baeldung.crawler4j;
import java.io.File;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
public class HtmlCrawlerController {
public static void main(String[] args) throws Exception {
File crawlStorage = new File("src/test/resources/crawler4j");
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorage.getAbsolutePath());
config.setMaxDepthOfCrawling(2);
int numCrawlers = 12;
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
controller.addSeed("https://www.baeldung.com/");
CrawlerStatistics stats = new CrawlerStatistics();
CrawlController.WebCrawlerFactory<HtmlCrawler> factory = () -> new HtmlCrawler(stats);
controller.start(factory, numCrawlers);
System.out.printf("Crawled %d pages %n", stats.getProcessedPageCount());
System.out.printf("Total Number of outbound links = %d %n", stats.getTotalLinksCount());
}
}
@@ -0,0 +1,49 @@
package com.baeldung.crawler4j;
import java.io.File;
import java.util.regex.Pattern;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.BinaryParseData;
import edu.uci.ics.crawler4j.url.WebURL;
public class ImageCrawler extends WebCrawler {
private final static Pattern EXCLUSIONS = Pattern.compile(".*(\\.(css|js|xml|gif|png|mp3|mp4|zip|gz|pdf))$");
private static final Pattern IMG_PATTERNS = Pattern.compile(".*(\\.(jpg|jpeg))$");
private File saveDir;
public ImageCrawler(File saveDir) {
this.saveDir = saveDir;
}
@Override
public boolean shouldVisit(Page referringPage, WebURL url) {
String urlString = url.getURL().toLowerCase();
if (EXCLUSIONS.matcher(urlString).matches()) {
return false;
}
if (IMG_PATTERNS.matcher(urlString).matches()
|| urlString.startsWith("https://www.baeldung.com/")) {
return true;
}
return false;
}
@Override
public void visit(Page page) {
String url = page.getWebURL().getURL();
if (IMG_PATTERNS.matcher(url).matches()
&& page.getParseData() instanceof BinaryParseData) {
String extension = url.substring(url.lastIndexOf("."));
int contentLength = page.getContentData().length;
System.out.printf("Extension is '%s' with content length %d %n", extension, contentLength);
}
}
}
@@ -0,0 +1,36 @@
package com.baeldung.crawler4j;
import java.io.File;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
public class ImageCrawlerController {
public static void main(String[] args) throws Exception {
File crawlStorage = new File("src/test/resources/crawler4j");
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorage.getAbsolutePath());
config.setIncludeBinaryContentInCrawling(true);
config.setMaxPagesToFetch(500);
File saveDir = new File("src/test/resources/crawler4j");
int numCrawlers = 12;
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
controller.addSeed("https://www.baeldung.com/");
CrawlController.WebCrawlerFactory<ImageCrawler> factory = () -> new ImageCrawler(saveDir);
controller.start(factory, numCrawlers);
}
}
@@ -0,0 +1,54 @@
package com.baeldung.crawler4j;
import java.io.File;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
public class MultipleCrawlerController {
public static void main(String[] args) throws Exception {
File crawlStorageBase = new File("src/test/resources/crawler4j");
CrawlConfig htmlConfig = new CrawlConfig();
CrawlConfig imageConfig = new CrawlConfig();
htmlConfig.setCrawlStorageFolder(new File(crawlStorageBase, "html").getAbsolutePath());
imageConfig.setCrawlStorageFolder(new File(crawlStorageBase, "image").getAbsolutePath());
imageConfig.setIncludeBinaryContentInCrawling(true);
htmlConfig.setMaxPagesToFetch(500);
imageConfig.setMaxPagesToFetch(1000);
PageFetcher pageFetcherHtml = new PageFetcher(htmlConfig);
PageFetcher pageFetcherImage = new PageFetcher(imageConfig);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcherHtml);
CrawlController htmlController = new CrawlController(htmlConfig, pageFetcherHtml, robotstxtServer);
CrawlController imageController = new CrawlController(imageConfig, pageFetcherImage, robotstxtServer);
htmlController.addSeed("https://www.baeldung.com/");
imageController.addSeed("https://www.baeldung.com/");
CrawlerStatistics stats = new CrawlerStatistics();
CrawlController.WebCrawlerFactory<HtmlCrawler> htmlFactory = () -> new HtmlCrawler(stats);
File saveDir = new File("src/test/resources/crawler4j");
CrawlController.WebCrawlerFactory<ImageCrawler> imageFactory = () -> new ImageCrawler(saveDir);
imageController.startNonBlocking(imageFactory, 7);
htmlController.startNonBlocking(htmlFactory, 10);
htmlController.waitUntilFinish();
System.out.printf("Crawled %d pages %n", stats.getProcessedPageCount());
System.out.printf("Total Number of outbound links = %d %n", stats.getTotalLinksCount());
imageController.waitUntilFinish();
System.out.printf("Image Crawler is finished.");
}
}
@@ -0,0 +1,40 @@
package com.baeldung.jasperreports;
import com.baeldung.jasperreports.config.JasperRerportsSimpleConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(JasperRerportsSimpleConfig.class);
ctx.refresh();
SimpleReportFiller simpleReportFiller = ctx.getBean(SimpleReportFiller.class);
simpleReportFiller.setReportFileName("employeeEmailReport.jrxml");
simpleReportFiller.compileReport();
simpleReportFiller.setReportFileName("employeeReport.jrxml");
simpleReportFiller.compileReport();
Map<String, Object> parameters = new HashMap<>();
parameters.put("title", "Employee Report Example");
parameters.put("minSalary", 15000.0);
parameters.put("condition", " LAST_NAME ='Smith' ORDER BY FIRST_NAME");
simpleReportFiller.setParameters(parameters);
simpleReportFiller.fillReport();
SimpleReportExporter simpleExporter = ctx.getBean(SimpleReportExporter.class);
simpleExporter.setJasperPrint(simpleReportFiller.getJasperPrint());
simpleExporter.exportToPdf("employeeReport.pdf", "baeldung");
simpleExporter.exportToXlsx("employeeReport.xlsx", "Employee Data");
simpleExporter.exportToCsv("employeeReport.csv");
simpleExporter.exportToHtml("employeeReport.html");
}
}
@@ -0,0 +1,104 @@
package com.baeldung.jasperreports;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.HtmlExporter;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.export.*;
import org.springframework.stereotype.Component;
import java.util.logging.Level;
import java.util.logging.Logger;
@Component
public class SimpleReportExporter {
private JasperPrint jasperPrint;
public SimpleReportExporter() {
}
public SimpleReportExporter(JasperPrint jasperPrint) {
this.jasperPrint = jasperPrint;
}
public JasperPrint getJasperPrint() {
return jasperPrint;
}
public void setJasperPrint(JasperPrint jasperPrint) {
this.jasperPrint = jasperPrint;
}
public void exportToPdf(String fileName, String author) {
// print report to file
JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(fileName));
SimplePdfReportConfiguration reportConfig = new SimplePdfReportConfiguration();
reportConfig.setSizePageToContent(true);
reportConfig.setForceLineBreakPolicy(false);
SimplePdfExporterConfiguration exportConfig = new SimplePdfExporterConfiguration();
exportConfig.setMetadataAuthor(author);
exportConfig.setEncrypted(true);
exportConfig.setAllowedPermissionsHint("PRINTING");
exporter.setConfiguration(reportConfig);
exporter.setConfiguration(exportConfig);
try {
exporter.exportReport();
} catch (JRException ex) {
Logger.getLogger(SimpleReportFiller.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void exportToXlsx(String fileName, String sheetName) {
JRXlsxExporter exporter = new JRXlsxExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(fileName));
SimpleXlsxReportConfiguration reportConfig = new SimpleXlsxReportConfiguration();
reportConfig.setSheetNames(new String[] { sheetName });
exporter.setConfiguration(reportConfig);
try {
exporter.exportReport();
} catch (JRException ex) {
Logger.getLogger(SimpleReportFiller.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void exportToCsv(String fileName) {
JRCsvExporter exporter = new JRCsvExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleWriterExporterOutput(fileName));
try {
exporter.exportReport();
} catch (JRException ex) {
Logger.getLogger(SimpleReportFiller.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void exportToHtml(String fileName) {
HtmlExporter exporter = new HtmlExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleHtmlExporterOutput(fileName));
try {
exporter.exportReport();
} catch (JRException ex) {
Logger.getLogger(SimpleReportFiller.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
@@ -0,0 +1,85 @@
package com.baeldung.jasperreports;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.util.JRSaver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
@Component
public class SimpleReportFiller {
private String reportFileName;
private JasperReport jasperReport;
private JasperPrint jasperPrint;
@Autowired
private DataSource dataSource;
private Map<String, Object> parameters;
public SimpleReportFiller() {
parameters = new HashMap<>();
}
public void prepareReport() {
compileReport();
fillReport();
}
public void compileReport() {
try {
InputStream reportStream = getClass().getResourceAsStream("/".concat(reportFileName));
jasperReport = JasperCompileManager.compileReport(reportStream);
JRSaver.saveObject(jasperReport, reportFileName.replace(".jrxml", ".jasper"));
} catch (JRException ex) {
Logger.getLogger(SimpleReportFiller.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void fillReport() {
try {
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource.getConnection());
} catch (JRException | SQLException ex) {
Logger.getLogger(SimpleReportFiller.class.getName()).log(Level.SEVERE, null, ex);
}
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Map<String, Object> getParameters() {
return parameters;
}
public void setParameters(Map<String, Object> parameters) {
this.parameters = parameters;
}
public String getReportFileName() {
return reportFileName;
}
public void setReportFileName(String reportFileName) {
this.reportFileName = reportFileName;
}
public JasperPrint getJasperPrint() {
return jasperPrint;
}
}
@@ -0,0 +1,30 @@
package com.baeldung.jasperreports.config;
import com.baeldung.jasperreports.SimpleReportExporter;
import com.baeldung.jasperreports.SimpleReportFiller;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import javax.sql.DataSource;
@Configuration
public class JasperRerportsSimpleConfig {
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL).addScript("classpath:employee-schema.sql").build();
}
@Bean
public SimpleReportFiller reportFiller() {
return new SimpleReportFiller();
}
@Bean
public SimpleReportExporter reportExporter() {
return new SimpleReportExporter();
}
}
@@ -0,0 +1,19 @@
package com.baeldung.jbpm;
import org.kie.api.runtime.manager.Context;
import org.kie.internal.runtime.manager.context.EmptyContext;
import com.baeldung.jbpm.engine.WorkflowEngine;
import com.baeldung.jbpm.engine.WorkflowEngineImpl;
public class WorkflowProcessMain {
public static void main(String[] args) {
WorkflowEngine workflowEngine = new WorkflowEngineImpl();
String processId = "com.baeldung.bpmn.helloworld";
String kbaseId = "kbase";
String persistenceUnit = "org.jbpm.persistence.jpa";
Context<String> initialContext = EmptyContext.get();
workflowEngine.runjBPMEngineForProcess(processId, initialContext, kbaseId, persistenceUnit);
}
}
@@ -0,0 +1,10 @@
package com.baeldung.jbpm.engine;
import org.kie.api.runtime.manager.Context;
import org.kie.api.runtime.process.ProcessInstance;
public interface WorkflowEngine {
public ProcessInstance runjBPMEngineForProcess(String processId, Context<String> initialContext, String kbaseId, String persistenceUnit);
}
@@ -0,0 +1,66 @@
package com.baeldung.jbpm.engine;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.jbpm.test.JBPMHelper;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.manager.Context;
import org.kie.api.runtime.manager.RuntimeEngine;
import org.kie.api.runtime.manager.RuntimeEnvironment;
import org.kie.api.runtime.manager.RuntimeEnvironmentBuilder;
import org.kie.api.runtime.manager.RuntimeManager;
import org.kie.api.runtime.manager.RuntimeManagerFactory;
import org.kie.api.runtime.process.ProcessInstance;
public class WorkflowEngineImpl implements WorkflowEngine {
@Override
public ProcessInstance runjBPMEngineForProcess(String processId, Context<String> initialContext, String kbaseId, String persistenceUnit) {
RuntimeManager manager = null;
RuntimeEngine engine = null;
ProcessInstance pInstance = null;
try {
KieBase kbase = getKieBase(kbaseId);
manager = createJBPMRuntimeManager(kbase, persistenceUnit);
engine = manager.getRuntimeEngine(initialContext);
pInstance = executeProcessInstance(processId, manager, initialContext, engine);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (manager != null && engine != null)
manager.disposeRuntimeEngine(engine);
System.exit(0);
}
return pInstance;
}
private ProcessInstance executeProcessInstance(String processId, RuntimeManager manager, Context<String> initialContext, RuntimeEngine engine) {
KieSession ksession = engine.getKieSession();
ProcessInstance pInstance = ksession.startProcess(processId);
return pInstance;
}
private KieBase getKieBase(String kbaseId) {
KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieBase kbase = kContainer.getKieBase(kbaseId);
return kbase;
}
private RuntimeManager createJBPMRuntimeManager(KieBase kbase, String persistenceUnit) {
JBPMHelper.startH2Server();
JBPMHelper.setupDataSource();
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);
RuntimeEnvironmentBuilder runtimeEnvironmentBuilder = RuntimeEnvironmentBuilder.Factory.get()
.newDefaultBuilder();
RuntimeEnvironment runtimeEnvironment = runtimeEnvironmentBuilder.entityManagerFactory(emf)
.knowledgeBase(kbase)
.get();
return RuntimeManagerFactory.Factory.get()
.newSingletonRuntimeManager(runtimeEnvironment);
}
}
@@ -0,0 +1,42 @@
package com.baeldung.mesos;
import com.baeldung.mesos.schedulers.HelloWorldScheduler;
import org.apache.mesos.MesosSchedulerDriver;
import org.apache.mesos.Protos;
import org.apache.mesos.Protos.CommandInfo;
import org.apache.mesos.Protos.ExecutorInfo;
import org.apache.mesos.Protos.FrameworkInfo;
public class HelloWorldMain {
public static void main(String[] args) {
String path = System.getProperty("user.dir")
+ "/target/libraries2-1.0.0-SNAPSHOT.jar";
CommandInfo.URI uri = CommandInfo.URI.newBuilder().setValue(path).setExtract(false).build();
String helloWorldCommand = "java -cp libraries2-1.0.0-SNAPSHOT.jar com.baeldung.mesos.executors.HelloWorldExecutor";
CommandInfo commandInfoHelloWorld = CommandInfo.newBuilder().setValue(helloWorldCommand).addUris(uri)
.build();
ExecutorInfo executorHelloWorld = ExecutorInfo.newBuilder()
.setExecutorId(Protos.ExecutorID.newBuilder().setValue("HelloWorldExecutor"))
.setCommand(commandInfoHelloWorld).setName("Hello World (Java)").setSource("java").build();
FrameworkInfo.Builder frameworkBuilder = FrameworkInfo.newBuilder().setFailoverTimeout(120000)
.setUser("")
.setName("Hello World Framework (Java)");
frameworkBuilder.setPrincipal("test-framework-java");
MesosSchedulerDriver driver = new MesosSchedulerDriver(new HelloWorldScheduler(executorHelloWorld), frameworkBuilder.build(), args[0]);
int status = driver.run() == Protos.Status.DRIVER_STOPPED ? 0 : 1;
// Ensure that the driver process terminates.
driver.stop();
System.exit(status);
}
}
@@ -0,0 +1,59 @@
package com.baeldung.mesos.executors;
import org.apache.mesos.Executor;
import org.apache.mesos.ExecutorDriver;
import org.apache.mesos.MesosExecutorDriver;
import org.apache.mesos.Protos;
import org.apache.mesos.Protos.TaskInfo;
public class HelloWorldExecutor implements Executor {
@Override
public void registered(ExecutorDriver driver, Protos.ExecutorInfo executorInfo, Protos.FrameworkInfo frameworkInfo, Protos.SlaveInfo slaveInfo) {
}
@Override
public void reregistered(ExecutorDriver driver, Protos.SlaveInfo slaveInfo) {
}
@Override
public void disconnected(ExecutorDriver driver) {
}
@Override
public void launchTask(ExecutorDriver driver, TaskInfo task) {
Protos.TaskStatus status = Protos.TaskStatus.newBuilder().setTaskId(task.getTaskId())
.setState(Protos.TaskState.TASK_RUNNING).build();
driver.sendStatusUpdate(status);
String myStatus = "Hello Framework";
driver.sendFrameworkMessage(myStatus.getBytes());
System.out.println("Hello World!!!");
status = Protos.TaskStatus.newBuilder().setTaskId(task.getTaskId())
.setState(Protos.TaskState.TASK_FINISHED).build();
driver.sendStatusUpdate(status);
}
@Override
public void killTask(ExecutorDriver driver, Protos.TaskID taskId) {
}
@Override
public void frameworkMessage(ExecutorDriver driver, byte[] data) {
}
@Override
public void shutdown(ExecutorDriver driver) {
}
@Override
public void error(ExecutorDriver driver, String message) {
}
public static void main(String[] args) {
MesosExecutorDriver driver = new MesosExecutorDriver(new HelloWorldExecutor());
System.exit(driver.run() == Protos.Status.DRIVER_STOPPED ? 0 : 1);
}
}
@@ -0,0 +1,100 @@
package com.baeldung.mesos.schedulers;
import com.google.protobuf.ByteString;
import org.apache.mesos.Protos;
import org.apache.mesos.Protos.ExecutorInfo;
import org.apache.mesos.Protos.Offer;
import org.apache.mesos.Protos.OfferID;
import org.apache.mesos.Protos.TaskInfo;
import org.apache.mesos.Scheduler;
import org.apache.mesos.SchedulerDriver;
import java.util.ArrayList;
import java.util.List;
public class HelloWorldScheduler implements Scheduler {
private int launchedTasks = 0;
private final ExecutorInfo helloWorldExecutor;
public HelloWorldScheduler(ExecutorInfo helloWorldExecutor) {
this.helloWorldExecutor = helloWorldExecutor;
}
@Override
public void registered(SchedulerDriver schedulerDriver, Protos.FrameworkID frameworkID, Protos.MasterInfo masterInfo) {
}
@Override
public void reregistered(SchedulerDriver schedulerDriver, Protos.MasterInfo masterInfo) {
}
@Override
public void resourceOffers(SchedulerDriver schedulerDriver, List<Offer> list) {
for (Offer offer : list) {
List<TaskInfo> tasks = new ArrayList<TaskInfo>();
Protos.TaskID taskId = Protos.TaskID.newBuilder().setValue(Integer.toString(launchedTasks++)).build();
System.out.println("Launching printHelloWorld " + taskId.getValue() + " Hello World Java");
TaskInfo printHelloWorld = TaskInfo
.newBuilder()
.setName("printHelloWorld " + taskId.getValue())
.setTaskId(taskId)
.setSlaveId(offer.getSlaveId())
.addResources(
Protos.Resource.newBuilder().setName("cpus").setType(Protos.Value.Type.SCALAR)
.setScalar(Protos.Value.Scalar.newBuilder().setValue(1)))
.addResources(
Protos.Resource.newBuilder().setName("mem").setType(Protos.Value.Type.SCALAR)
.setScalar(Protos.Value.Scalar.newBuilder().setValue(128)))
.setExecutor(ExecutorInfo.newBuilder(helloWorldExecutor)).build();
List<OfferID> offerIDS = new ArrayList<>();
offerIDS.add(offer.getId());
tasks.add(printHelloWorld);
schedulerDriver.declineOffer(offer.getId());
schedulerDriver.launchTasks(offerIDS, tasks);
}
}
@Override
public void offerRescinded(SchedulerDriver schedulerDriver, OfferID offerID) {
}
@Override
public void statusUpdate(SchedulerDriver schedulerDriver, Protos.TaskStatus taskStatus) {
}
@Override
public void frameworkMessage(SchedulerDriver schedulerDriver, Protos.ExecutorID executorID, Protos.SlaveID slaveID, byte[] bytes) {
}
@Override
public void disconnected(SchedulerDriver schedulerDriver) {
}
@Override
public void slaveLost(SchedulerDriver schedulerDriver, Protos.SlaveID slaveID) {
}
@Override
public void executorLost(SchedulerDriver schedulerDriver, Protos.ExecutorID executorID, Protos.SlaveID slaveID, int i) {
}
@Override
public void error(SchedulerDriver schedulerDriver, String s) {
}
}
@@ -0,0 +1,41 @@
package com.baeldung.picocli.git;
import com.baeldung.picocli.git.commands.programmative.GitCommand;
import com.baeldung.picocli.git.commands.subcommands.GitAddCommand;
import com.baeldung.picocli.git.commands.subcommands.GitCommitCommand;
import com.baeldung.picocli.git.commands.subcommands.GitConfigCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import picocli.CommandLine;
@SpringBootApplication
public class Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
private GitCommand gitCommand;
private GitAddCommand addCommand;
private GitCommitCommand commitCommand;
private GitConfigCommand configCommand;
@Autowired
public Application(GitCommand gitCommand, GitAddCommand addCommand, GitCommitCommand commitCommand, GitConfigCommand configCommand) {
this.gitCommand = gitCommand;
this.addCommand = addCommand;
this.commitCommand = commitCommand;
this.configCommand = configCommand;
}
@Override
public void run(String... args) {
CommandLine commandLine = new CommandLine(gitCommand);
commandLine.addSubcommand("add", addCommand);
commandLine.addSubcommand("commit", commitCommand);
commandLine.addSubcommand("config", configCommand);
commandLine.parseWithHandler(new CommandLine.RunLast(), args);
}
}
@@ -0,0 +1,32 @@
package com.baeldung.picocli.git.commands.declarative;
import com.baeldung.picocli.git.model.ConfigElement;
import com.baeldung.picocli.git.commands.subcommands.GitAddCommand;
import com.baeldung.picocli.git.commands.subcommands.GitCommitCommand;
import com.baeldung.picocli.git.commands.subcommands.GitConfigCommand;
import picocli.CommandLine;
import static picocli.CommandLine.*;
import static picocli.CommandLine.Command;
@Command(
name = "git",
subcommands = {
GitAddCommand.class,
GitCommitCommand.class,
GitConfigCommand.class
}
)
public class GitCommand implements Runnable {
public static void main(String[] args) {
CommandLine commandLine = new CommandLine(new GitCommand());
commandLine.registerConverter(ConfigElement.class, ConfigElement::from);
commandLine.parseWithHandler(new RunLast(), args);
}
@Override
public void run() {
System.out.println("The popular git command");
}
}
@@ -0,0 +1,27 @@
package com.baeldung.picocli.git.commands.methods;
import picocli.CommandLine;
import static picocli.CommandLine.Command;
@Command(name = "git")
public class GitCommand implements Runnable {
public static void main(String[] args) {
CommandLine.run(new GitCommand(), args);
}
@Override
public void run() {
System.out.println("The popular git command");
}
@Command(name = "add")
public void addCommand() {
System.out.println("Adding some files to the staging area");
}
@Command(name = "commit")
public void commitCommand() {
System.out.println("Committing files in the staging area, how wonderful?");
}
}
@@ -0,0 +1,26 @@
package com.baeldung.picocli.git.commands.programmative;
import com.baeldung.picocli.git.commands.subcommands.GitAddCommand;
import com.baeldung.picocli.git.commands.subcommands.GitCommitCommand;
import org.springframework.stereotype.Component;
import picocli.CommandLine;
import static picocli.CommandLine.Command;
import static picocli.CommandLine.RunLast;
@Command(name = "git")
@Component
public class GitCommand implements Runnable {
public static void main(String[] args) {
CommandLine commandLine = new CommandLine(new GitCommand());
commandLine.addSubcommand("add", new GitAddCommand());
commandLine.addSubcommand("commit", new GitCommitCommand());
commandLine.parseWithHandler(new RunLast(), args);
}
@Override
public void run() {
System.out.println("The popular git command");
}
}
@@ -0,0 +1,31 @@
package com.baeldung.picocli.git.commands.subcommands;
import org.springframework.stereotype.Component;
import java.nio.file.Path;
import java.util.List;
import static picocli.CommandLine.*;
@Command(
name = "add"
)
@Component
public class GitAddCommand implements Runnable {
@Option(names = "-A")
private boolean allFiles;
@Parameters(index = "0..*")
private List<Path> files;
@Override
public void run() {
if (allFiles) {
System.out.println("Adding all files to the staging area");
}
if (files != null) {
files.forEach(path -> System.out.println("Adding " + path + " to the staging area"));
}
}
}
@@ -0,0 +1,26 @@
package com.baeldung.picocli.git.commands.subcommands;
import org.springframework.stereotype.Component;
import static picocli.CommandLine.Command;
import static picocli.CommandLine.Option;
@Command(
name = "commit"
)
@Component
public class GitCommitCommand implements Runnable {
@Option(names = {"-m", "--message"}, required = true)
private String[] messages;
@Override
public void run() {
System.out.println("Committing files in the staging area, how wonderful?");
if (messages != null) {
System.out.println("The commit message is");
for (String message : messages) {
System.out.println(message);
}
}
}
}
@@ -0,0 +1,24 @@
package com.baeldung.picocli.git.commands.subcommands;
import com.baeldung.picocli.git.model.ConfigElement;
import org.springframework.stereotype.Component;
import static picocli.CommandLine.Command;
import static picocli.CommandLine.Parameters;
@Command(
name = "config"
)
@Component
public class GitConfigCommand implements Runnable {
@Parameters(index = "0")
private ConfigElement element;
@Parameters(index = "1")
private String value;
@Override
public void run() {
System.out.println("Setting " + element.value() + " to " + value);
}
}
@@ -0,0 +1,25 @@
package com.baeldung.picocli.git.model;
import java.util.Arrays;
public enum ConfigElement {
USERNAME("user.name"),
EMAIL("user.email");
private final String value;
ConfigElement(String value) {
this.value = value;
}
public String value() {
return value;
}
public static ConfigElement from(String value) {
return Arrays.stream(values())
.filter(element -> element.value.equals(value))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("The argument " + value + " doesn't match any ConfigElement"));
}
}
@@ -0,0 +1,20 @@
package com.baeldung.picocli.helloworld;
import picocli.CommandLine;
import static picocli.CommandLine.Command;
@Command(
name = "hello",
description = "Says hello"
)
public class HelloWorldCommand implements Runnable {
public static void main(String[] args) {
CommandLine.run(new HelloWorldCommand(), args);
}
@Override
public void run() {
System.out.println("Hello World!");
}
}
@@ -0,0 +1,3 @@
<kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule">
<kbase name="kbase" packages="com.baeldung.process"/>
</kmodule>
@@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="Definition"
targetNamespace="http://www.jboss.org/drools"
typeLanguage="http://www.java.com/javaTypes"
expressionLanguage="http://www.mvel.org/2.0"
xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd"
xmlns:g="http://www.jboss.org/drools/flow/gpd"
xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI"
xmlns:dc="http://www.omg.org/spec/DD/20100524/DC"
xmlns:di="http://www.omg.org/spec/DD/20100524/DI"
xmlns:tns="http://www.jboss.org/drools">
<process processType="Private" isExecutable="true" id="com.baeldung.bpmn.helloworld" name="HelloWorld Process" tns:packageName="com.baeldung.bpmn.process" >
<!-- nodes -->
<scriptTask id="_jbpm-unique-1" name="HelloWorld" scriptFormat="http://www.java.com/java" >
<script>System.out.println("Hello World");</script>
</scriptTask>
<endEvent id="_jbpm-unique-2" name="End" >
<terminateEventDefinition />
</endEvent>
<startEvent id="_jbpm-unique-0" name="Start" isInterrupting="false"/>
<!-- connections -->
<sequenceFlow id="_jbpm-unique-0-_jbpm-unique-1" sourceRef="_jbpm-unique-0" targetRef="_jbpm-unique-1" />
<sequenceFlow id="_jbpm-unique-1-_jbpm-unique-2" sourceRef="_jbpm-unique-1" targetRef="_jbpm-unique-2" />
</process>
<bpmndi:BPMNDiagram>
<bpmndi:BPMNPlane bpmnElement="com.baeldung.bpmn.helloworld" >
<bpmndi:BPMNShape bpmnElement="_jbpm-unique-1" >
<dc:Bounds x="119" y="44" width="111" height="48" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="_jbpm-unique-2" >
<dc:Bounds x="272" y="43" width="48" height="48" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="_jbpm-unique-0" >
<dc:Bounds x="28" y="44" width="48" height="48" />
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge bpmnElement="_jbpm-unique-0-_jbpm-unique-1" >
<di:waypoint x="52" y="68" />
<di:waypoint x="174" y="68" />
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="_jbpm-unique-1-_jbpm-unique-2" >
<di:waypoint x="174" y="68" />
<di:waypoint x="296" y="67" />
</bpmndi:BPMNEdge>
</bpmndi:BPMNPlane>
</bpmndi:BPMNDiagram>
</definitions>
@@ -0,0 +1,27 @@
CREATE TABLE EMPLOYEE(
ID INT NOT NULL PRIMARY KEY,
FIRST_NAME VARCHAR(255),
LAST_NAME VARCHAR(255),
SALARY DOUBLE,
);
CREATE TABLE EMAIL(
ID INT NOT NULL PRIMARY KEY,
ID_EMPLOYEE VARCHAR(255),
ADDRESS VARCHAR(255)
);
INSERT INTO EMPLOYEE VALUES (1, 'John', 'Doe', 10000.10);
INSERT INTO EMPLOYEE VALUES (2, 'Kevin', 'Smith', 20000.20);
INSERT INTO EMPLOYEE VALUES (3, 'Kim', 'Smith', 30000.30);
INSERT INTO EMPLOYEE VALUES (4, 'Stephen', 'Torvalds', 40000.40);
INSERT INTO EMPLOYEE VALUES (5, 'Christian', 'Reynolds', 50000.50);
INSERT INTO EMAIL VALUES (1, 1, 'john@baeldung.com');
INSERT INTO EMAIL VALUES (2, 1, 'john@gmail.com');
INSERT INTO EMAIL VALUES (3, 2, 'kevin@baeldung.com');
INSERT INTO EMAIL VALUES (4, 3, 'kim@baeldung.com');
INSERT INTO EMAIL VALUES (5, 3, 'kim@gmail.com');
INSERT INTO EMAIL VALUES (6, 3, 'kim@outlook.com');
INSERT INTO EMAIL VALUES (7, 4, 'stephen@baeldung.com');
INSERT INTO EMAIL VALUES (8, 5, 'christian@gmail.com');
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
name="employeeReport" pageWidth="612" pageHeight="792" columnWidth="555" leftMargin="20" rightMargin="20"
topMargin="20" bottomMargin="20">
<parameter name="idEmployee" class="java.lang.Integer" isForPrompting="false"/>
<queryString>
<![CDATA[SELECT * FROM EMAIL WHERE ID_EMPLOYEE = $P{idEmployee}]]>
</queryString>
<field name="ADDRESS" class="java.lang.String"/>
<detail>
<band height="20" splitType="Stretch">
<textField>
<reportElement x="0" y="0" width="156" height="20"/>
<textElement/>
<textFieldExpression class="java.lang.String"><![CDATA[$F{ADDRESS}]]></textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>
@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
name="employeeReport" pageWidth="612" pageHeight="792" columnWidth="555" leftMargin="20" rightMargin="20"
topMargin="20" bottomMargin="20">
<parameter name="title" class="java.lang.String" isForPrompting="false"/>
<parameter name="condition" class="java.lang.String" isForPrompting="false">
<defaultValueExpression><![CDATA[" 1 = 1"]]></defaultValueExpression>
</parameter>
<parameter name="minSalary" class="java.lang.Double" isForPrompting="false"/>
<queryString>
<![CDATA[SELECT * FROM EMPLOYEE WHERE SALARY >= $P{minSalary} AND $P!{condition}]]>
</queryString>
<field name="FIRST_NAME" class="java.lang.String"/>
<field name="LAST_NAME" class="java.lang.String"/>
<field name="SALARY" class="java.lang.Double"/>
<field name="ID" class="java.lang.Integer"/>
<title>
<band height="20" splitType="Stretch">
<textField>
<reportElement x="238" y="0" width="100" height="20"/>
<textElement/>
<textFieldExpression class="java.lang.String"><![CDATA[$P{title}]]></textFieldExpression>
</textField>
</band>
</title>
<detail>
<band height="47" splitType="Stretch">
<textField>
<reportElement x="0" y="0" width="100" height="20"/>
<textElement/>
<textFieldExpression class="java.lang.String"><![CDATA[$F{FIRST_NAME}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="100" y="0" width="100" height="20"/>
<textElement/>
<textFieldExpression class="java.lang.String"><![CDATA[$F{LAST_NAME}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="200" y="0" width="100" height="20"/>
<textElement/>
<textFieldExpression class="java.lang.String"><![CDATA[$F{SALARY}]]></textFieldExpression>
</textField>
<subreport>
<reportElement x="0" y="20" width="300" height="27"/>
<subreportParameter name="idEmployee">
<subreportParameterExpression><![CDATA[$F{ID}]]></subreportParameterExpression>
</subreportParameter>
<connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
<subreportExpression class="java.lang.String">
<![CDATA["employeeEmailReport.jasper"]]></subreportExpression>
</subreport>
</band>
</detail>
</jasperReport>
@@ -0,0 +1,132 @@
package com.baeldung.chroniclemap;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import net.openhft.chronicle.core.values.LongValue;
import net.openhft.chronicle.map.ChronicleMap;
import net.openhft.chronicle.map.ExternalMapQueryContext;
import net.openhft.chronicle.map.MapEntry;
import net.openhft.chronicle.values.Values;
public class ChronicleMapUnitTest {
static ChronicleMap<LongValue, CharSequence> persistedCountryMap = null;
static ChronicleMap<LongValue, CharSequence> inMemoryCountryMap = null;
static ChronicleMap<Integer, Set<Integer>> multiMap = null;
@SuppressWarnings({ "unchecked", "rawtypes" })
@BeforeClass
public static void init() {
try {
inMemoryCountryMap = ChronicleMap.of(LongValue.class, CharSequence.class)
.name("country-map")
.entries(50)
.averageValue("America")
.create();
persistedCountryMap = ChronicleMap.of(LongValue.class, CharSequence.class)
.name("country-map")
.entries(50)
.averageValue("America")
.createPersistedTo(new File(System.getProperty("user.home") + "/country-details.dat"));
Set<Integer> averageValue = IntStream.of(1, 2)
.boxed()
.collect(Collectors.toSet());
multiMap = ChronicleMap.of(Integer.class, (Class<Set<Integer>>) (Class) Set.class)
.name("multi-map")
.entries(50)
.averageValue(averageValue)
.create();
LongValue qatarKey = Values.newHeapInstance(LongValue.class);
qatarKey.setValue(1);
inMemoryCountryMap.put(qatarKey, "Qatar");
LongValue key = Values.newHeapInstance(LongValue.class);
key.setValue(1);
persistedCountryMap.put(key, "Romania");
key.setValue(2);
persistedCountryMap.put(key, "India");
Set<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
multiMap.put(1, set1);
Set<Integer> set2 = new HashSet<>();
set2.add(3);
multiMap.put(2, set2);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void givenGetQuery_whenCalled_shouldReturnResult() {
LongValue key = Values.newHeapInstance(LongValue.class);
key.setValue(1);
CharSequence country = inMemoryCountryMap.get(key);
assertThat(country.toString(), is(equalTo("Qatar")));
}
@Test
public void givenGetUsingQuery_whenCalled_shouldReturnResult() {
LongValue key = Values.newHeapInstance(LongValue.class);
StringBuilder country = new StringBuilder();
key.setValue(1);
persistedCountryMap.getUsing(key, country);
assertThat(country.toString(), is(equalTo("Romania")));
key.setValue(2);
persistedCountryMap.getUsing(key, country);
assertThat(country.toString(), is(equalTo("India")));
}
@Test
public void givenMultipleKeyQuery_whenProcessed_shouldChangeTheValue() {
try (ExternalMapQueryContext<Integer, Set<Integer>, ?> fistContext = multiMap.queryContext(1)) {
try (ExternalMapQueryContext<Integer, Set<Integer>, ?> secondContext = multiMap.queryContext(2)) {
fistContext.updateLock()
.lock();
secondContext.updateLock()
.lock();
MapEntry<Integer, Set<Integer>> firstEntry = fistContext.entry();
Set<Integer> firstSet = firstEntry.value()
.get();
firstSet.remove(2);
MapEntry<Integer, Set<Integer>> secondEntry = secondContext.entry();
Set<Integer> secondSet = secondEntry.value()
.get();
secondSet.add(4);
firstEntry.doReplaceValue(fistContext.wrapValueAsData(firstSet));
secondEntry.doReplaceValue(secondContext.wrapValueAsData(secondSet));
}
} finally {
assertThat(multiMap.get(1)
.size(), is(equalTo(1)));
assertThat(multiMap.get(2)
.size(), is(equalTo(2)));
}
}
@AfterClass
public static void finish() {
persistedCountryMap.close();
inMemoryCountryMap.close();
multiMap.close();
}
}
@@ -0,0 +1,74 @@
package com.baeldung.classgraph;
import io.github.classgraph.*;
import org.junit.Test;
import java.io.IOException;
import java.util.function.Consumer;
import static org.assertj.core.api.Assertions.assertThat;
public class ClassGraphUnitTest {
@Test
public void whenClassAnnotationFilterIsDefined_thenTargetClassesCanBeFound() {
doTest(result -> {
ClassInfoList classInfos = result.getClassesWithAnnotation(TestAnnotation.class.getName());
assertThat(classInfos).extracting(ClassInfo::getName).contains(ClassWithAnnotation.class.getName());
});
}
@Test
public void whenMethodAnnotationFilterIsDefined_thenTargetClassesCanBeFound() {
doTest(result -> {
ClassInfoList classInfos = result.getClassesWithMethodAnnotation(TestAnnotation.class.getName());
assertThat(classInfos).extracting(ClassInfo::getName).contains(MethodWithAnnotation.class.getName());
});
}
@Test
public void whenMethodAnnotationValueFilterIsDefined_thenTargetClassesCanBeFound() {
doTest(result -> {
ClassInfoList classInfos = result.getClassesWithMethodAnnotation(TestAnnotation.class.getName());
ClassInfoList filteredClassInfos = classInfos.filter(classInfo -> {
return classInfo.getMethodInfo().stream().anyMatch(methodInfo -> {
AnnotationInfo annotationInfo = methodInfo.getAnnotationInfo(TestAnnotation.class.getName());
if (annotationInfo == null) {
return false;
}
return "web".equals(annotationInfo.getParameterValues().getValue("value"));
});
});
assertThat(filteredClassInfos)
.extracting(ClassInfo::getName)
.contains(MethodWithAnnotationParameterWeb.class.getName());
});
}
@Test
public void whenFieldAnnotationFilterIsDefined_thenTargetClassesCanBeFound() {
doTest(result -> {
ClassInfoList classInfos = result.getClassesWithFieldAnnotation(TestAnnotation.class.getName());
assertThat(classInfos).extracting(ClassInfo::getName).contains(FieldWithAnnotation.class.getName());
});
}
@Test
public void whenResourceIsUsed_thenItCanBeFoundAndLoaded() throws IOException {
try (ScanResult result = new ClassGraph().whitelistPaths("classgraph").scan()) {
ResourceList resources = result.getResourcesWithExtension("config");
assertThat(resources).extracting(Resource::getPath).containsOnly("classgraph/my.config");
assertThat(resources.get(0).getContentAsString()).isEqualTo("my data");
}
}
private void doTest(Consumer<ScanResult> checker) {
try (ScanResult result = new ClassGraph().enableAllInfo()
.whitelistPackages(getClass().getPackage().getName())
.scan())
{
checker.accept(result);
}
}
}
@@ -0,0 +1,5 @@
package com.baeldung.classgraph;
@TestAnnotation
public class ClassWithAnnotation {
}
@@ -0,0 +1,7 @@
package com.baeldung.classgraph;
public class FieldWithAnnotation {
@TestAnnotation
private String s;
}
@@ -0,0 +1,8 @@
package com.baeldung.classgraph;
public class MethodWithAnnotation {
@TestAnnotation
public void service() {
}
}
@@ -0,0 +1,8 @@
package com.baeldung.classgraph;
public class MethodWithAnnotationParameterDao {
@TestAnnotation("dao")
public void service() {
}
}
@@ -0,0 +1,8 @@
package com.baeldung.classgraph;
public class MethodWithAnnotationParameterWeb {
@TestAnnotation("web")
public void service() {
}
}
@@ -0,0 +1,14 @@
package com.baeldung.classgraph;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
@Target({TYPE, METHOD, FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
String value() default "";
}
@@ -0,0 +1,109 @@
package com.baeldung.handlebars;
import static org.assertj.core.api.Assertions.assertThat;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Template;
import com.github.jknack.handlebars.io.ClassPathTemplateLoader;
import com.github.jknack.handlebars.io.TemplateLoader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
/**
* Showcases the tag usage and different template loading mechanisms.
*
* @author isaolmez
*/
public class BasicUsageUnitTest {
@Test
public void whenThereIsNoTemplateFile_ThenCompilesInline() throws IOException {
Handlebars handlebars = new Handlebars();
Template template = handlebars.compileInline("Hi {{this}}!");
String templateString = template.apply("Baeldung");
assertThat(templateString).isEqualTo("Hi Baeldung!");
}
@Test
public void whenParameterMapIsSupplied_thenDisplays() throws IOException {
Handlebars handlebars = new Handlebars();
Template template = handlebars.compileInline("Hi {{name}}!");
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("name", "Baeldung");
String templateString = template.apply(parameterMap);
assertThat(templateString).isEqualTo("Hi Baeldung!");
}
@Test
public void whenParameterObjectIsSupplied_ThenDisplays() throws IOException {
Handlebars handlebars = new Handlebars();
Template template = handlebars.compileInline("Hi {{name}}!");
Person person = new Person();
person.setName("Baeldung");
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("Hi Baeldung!");
}
@Test
public void whenMultipleParametersAreSupplied_ThenDisplays() throws IOException {
Handlebars handlebars = new Handlebars();
Template template = handlebars.compileInline("Hi {{name}}! This is {{topic}}.");
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("name", "Baeldung");
parameterMap.put("topic", "Handlebars");
String templateString = template.apply(parameterMap);
assertThat(templateString).isEqualTo("Hi Baeldung! This is Handlebars.");
}
@Test
public void whenNoLoaderIsGiven_ThenSearchesClasspath() throws IOException {
Handlebars handlebars = new Handlebars();
Template template = handlebars.compile("greeting");
Person person = getPerson("Baeldung");
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("Hi Baeldung!");
}
@Test
public void whenClasspathTemplateLoaderIsGiven_ThenSearchesClasspathWithPrefixSuffix() throws IOException {
TemplateLoader loader = new ClassPathTemplateLoader("/handlebars", ".html");
Handlebars handlebars = new Handlebars(loader);
Template template = handlebars.compile("greeting");
Person person = getPerson("Baeldung");
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("Hi Baeldung!");
}
@Test
public void whenMultipleLoadersAreGiven_ThenSearchesSequentially() throws IOException {
TemplateLoader firstLoader = new ClassPathTemplateLoader("/handlebars", ".html");
TemplateLoader secondLoader = new ClassPathTemplateLoader("/templates", ".html");
Handlebars handlebars = new Handlebars().with(firstLoader, secondLoader);
Template template = handlebars.compile("greeting");
Person person = getPerson("Baeldung");
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("Hi Baeldung!");
}
private Person getPerson(String name) {
Person person = new Person();
person.setName(name);
return person;
}
}
@@ -0,0 +1,106 @@
package com.baeldung.handlebars;
import static org.assertj.core.api.Assertions.assertThat;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Template;
import com.github.jknack.handlebars.io.ClassPathTemplateLoader;
import com.github.jknack.handlebars.io.TemplateLoader;
import java.io.IOException;
import org.junit.Test;
/**
* Showcases the built-in template helpers.
*
* @author isaolmez
*/
public class BuiltinHelperUnitTest {
private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html");
@Test
public void whenUsedWith_ThenContextChanges() throws IOException {
Handlebars handlebars = new Handlebars(templateLoader);
Template template = handlebars.compile("with");
Person person = getPerson("Baeldung");
person.getAddress().setStreet("World");
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("\n<h4>I live in World</h4>\n");
}
@Test
public void whenUsedWithMustacheStyle_ThenContextChanges() throws IOException {
Handlebars handlebars = new Handlebars(templateLoader);
Template template = handlebars.compile("with_mustache");
Person person = getPerson("Baeldung");
person.getAddress().setStreet("World");
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("\n<h4>I live in World</h4>\n");
}
@Test
public void whenUsedEach_ThenIterates() throws IOException {
Handlebars handlebars = new Handlebars(templateLoader);
Template template = handlebars.compile("each");
Person person = getPerson("Baeldung");
Person friend1 = getPerson("Java");
Person friend2 = getPerson("Spring");
person.getFriends().add(friend1);
person.getFriends().add(friend2);
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("\n<span>Java is my friend.</span>\n"
+ "\n<span>Spring is my friend.</span>\n");
}
@Test
public void whenUsedEachMustacheStyle_ThenIterates() throws IOException {
Handlebars handlebars = new Handlebars(templateLoader);
Template template = handlebars.compile("each_mustache");
Person person = getPerson("Baeldung");
Person friend1 = getPerson("Java");
Person friend2 = getPerson("Spring");
person.getFriends().add(friend1);
person.getFriends().add(friend2);
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("\n<span>Java is my friend.</span>\n"
+ "\n<span>Spring is my friend.</span>\n");
}
@Test
public void whenUsedIf_ThenPutsCondition() throws IOException {
Handlebars handlebars = new Handlebars(templateLoader);
Template template = handlebars.compile("if");
Person person = getPerson("Baeldung");
person.setBusy(true);
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("\n<h4>Baeldung is busy.</h4>\n");
}
@Test
public void whenUsedIfMustacheStyle_ThenPutsCondition() throws IOException {
Handlebars handlebars = new Handlebars(templateLoader);
Template template = handlebars.compile("if_mustache");
Person person = getPerson("Baeldung");
person.setBusy(true);
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("\n<h4>Baeldung is busy.</h4>\n");
}
private Person getPerson(String name) {
Person person = new Person();
person.setName(name);
return person;
}
}
@@ -0,0 +1,59 @@
package com.baeldung.handlebars;
import static org.assertj.core.api.Assertions.assertThat;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Helper;
import com.github.jknack.handlebars.Options;
import com.github.jknack.handlebars.Template;
import com.github.jknack.handlebars.io.ClassPathTemplateLoader;
import com.github.jknack.handlebars.io.TemplateLoader;
import java.io.IOException;
import org.junit.Test;
/**
* Showcases implementing a custom template helper.
*
* @author isaolmez
*/
public class CustomHelperUnitTest {
private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html");
@Test
public void whenHelperIsCreated_ThenCanRegister() throws IOException {
Handlebars handlebars = new Handlebars(templateLoader);
handlebars.registerHelper("isBusy", new Helper<Person>() {
@Override
public Object apply(Person context, Options options) throws IOException {
String busyString = context.isBusy() ? "busy" : "available";
return context.getName() + " - " + busyString;
}
});
Template template = handlebars.compile("person");
Person person = getPerson("Baeldung");
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("Baeldung - busy");
}
@Test
public void whenHelperSourceIsCreated_ThenCanRegister() throws IOException {
Handlebars handlebars = new Handlebars(templateLoader);
handlebars.registerHelpers(new HelperSource());
Template template = handlebars.compile("person");
Person person = getPerson("Baeldung");
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("Baeldung - busy");
}
private Person getPerson(String name) {
Person person = new Person();
person.setName(name);
person.setBusy(true);
return person;
}
}
@@ -0,0 +1,9 @@
package com.baeldung.handlebars;
public class HelperSource {
public String isBusy(Person context) {
String busyString = context.isBusy() ? "busy" : "available";
return context.getName() + " - " + busyString;
}
}
@@ -0,0 +1,58 @@
package com.baeldung.handlebars;
import java.util.ArrayList;
import java.util.List;
public class Person {
private String name;
private boolean busy;
private Address address = new Address();
private List<Person> friends = new ArrayList<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isBusy() {
return busy;
}
public void setBusy(boolean busy) {
this.busy = busy;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<Person> getFriends() {
return friends;
}
public void setFriends(List<Person> friends) {
this.friends = friends;
}
public static class Address {
private String street;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}
}
@@ -0,0 +1,49 @@
package com.baeldung.handlebars;
import static org.assertj.core.api.Assertions.assertThat;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Template;
import com.github.jknack.handlebars.io.ClassPathTemplateLoader;
import com.github.jknack.handlebars.io.TemplateLoader;
import java.io.IOException;
import org.junit.Test;
/**
* Showcases reusing the existing templates.
*
* @author isaolmez
*/
public class ReusingTemplatesUnitTest {
private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html");
@Test
public void whenOtherTemplateIsReferenced_ThenCanReuse() throws IOException {
Handlebars handlebars = new Handlebars(templateLoader);
Template template = handlebars.compile("page");
Person person = new Person();
person.setName("Baeldung");
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("<h4>Hi Baeldung!</h4>\n<p>This is the page Baeldung</p>");
}
@Test
public void whenBlockIsDefined_ThenCanOverrideWithPartial() throws IOException {
Handlebars handlebars = new Handlebars(templateLoader);
Template template = handlebars.compile("simplemessage");
Person person = new Person();
person.setName("Baeldung");
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("\n<html>\n"
+ "<body>\n"
+ "\n This is the intro\n\n"
+ "\n Hi there!\n\n"
+ "</body>\n"
+ "</html>");
}
}
@@ -0,0 +1,52 @@
package com.baeldung.jbpm;
import org.jbpm.test.JbpmJUnitBaseTestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.manager.RuntimeEngine;
import org.kie.api.runtime.manager.RuntimeManager;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.internal.runtime.manager.context.ProcessInstanceIdContext;
public class WorkflowEngineIntegrationTest extends JbpmJUnitBaseTestCase {
private String[] triggeredNodesArray = { "Start", "HelloWorld", "End" };
private RuntimeManager manager = null;
private RuntimeEngine runtimeEngine = null;
private KieSession ksession = null;
private ProcessInstance processInstance = null;
@Before
public void setup() {
manager = createRuntimeManager(Strategy.SINGLETON, "manager", "com/baeldung/process/helloworld.bpmn");
runtimeEngine = getRuntimeEngine(ProcessInstanceIdContext.get());
ksession = runtimeEngine.getKieSession();
processInstance = ksession.startProcess("com.baeldung.bpmn.helloworld");
}
@After
public void cleanup() {
manager.disposeRuntimeEngine(runtimeEngine);
}
@Test
public void givenProcessInstance_whenExecutionCompleted_thenVerifyNodesExecutionOrder() {
assertNodeTriggered(processInstance.getId(), triggeredNodesArray);
}
@Test
public void givenProcessInstance_whenExecutionCompleted_thenVerifyKnowledgeSessionId() {
int ksessionID = ksession.getId();
runtimeEngine = getRuntimeEngine(ProcessInstanceIdContext.get(processInstance.getId()));
ksession = runtimeEngine.getKieSession();
assertEquals(ksessionID, ksession.getId());
}
@Test
public void givenProcessInstance_whenExecutionCompleted_thenVerifyProcessInstanceStatus() {
assertProcessInstanceCompleted(processInstance.getId(), ksession);
assertTrue("ProcessInstance completed with status 2", processInstance.getState() == 2);
}
}
@@ -0,0 +1,33 @@
package com.baeldung.mapdb;
import org.junit.Test;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.Serializer;
import java.util.NavigableSet;
import static junit.framework.Assert.assertEquals;
public class CollectionsUnitTest {
@Test
public void givenSetCreatedInDB_whenMultipleElementsAdded_checkOnlyOneExists() {
DB db = DBMaker.memoryDB().make();
NavigableSet<String> set = db.
treeSet("mySet")
.serializer(Serializer.STRING)
.createOrOpen();
String myString = "Baeldung!";
set.add(myString);
set.add(myString);
assertEquals(1, set.size());
db.close();
}
}
@@ -0,0 +1,38 @@
package com.baeldung.mapdb;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import org.mapdb.*;
import java.io.IOException;
import static junit.framework.Assert.assertEquals;
public class HTreeMapUnitTest {
@Test
public void givenValidDB_whenHTreeMapAddedToAndRetrieved_CheckedRetrievalCorrect() {
DB db = DBMaker.memoryDB().make();
HTreeMap<String, String> hTreeMap = db
.hashMap("myTreMap")
.keySerializer(Serializer.STRING)
.valueSerializer(Serializer.STRING)
.create();
hTreeMap.put("key1", "value1");
hTreeMap.put("key2", "value2");
assertEquals(2, hTreeMap.size());
//add another value with the same key
hTreeMap.put("key1", "value3");
assertEquals(2, hTreeMap.size());
assertEquals("value3", hTreeMap.get("key1"));
}
}
@@ -0,0 +1,49 @@
package com.baeldung.mapdb;
import org.junit.Test;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.HTreeMap;
import java.util.concurrent.ConcurrentMap;
import static junit.framework.Assert.assertEquals;
public class HelloBaeldungUnitTest {
@Test
public void givenInMemoryDBInstantiateCorrectly_whenDataSavedAndRetrieved_checkRetrievalCorrect() {
DB db = DBMaker.memoryDB().make();
String welcomeMessageKey = "Welcome Message";
String welcomeMessageString = "Hello Baeldung!";
HTreeMap myMap = db.hashMap("myMap").createOrOpen();
myMap.put(welcomeMessageKey, welcomeMessageString);
String welcomeMessageFromDB = (String) myMap.get(welcomeMessageKey);
db.close();
assertEquals(welcomeMessageString, welcomeMessageFromDB);
}
@Test
public void givenInFileDBInstantiateCorrectly_whenDataSavedAndRetrieved_checkRetrievalCorrect() {
DB db = DBMaker.fileDB("file.db").make();
String welcomeMessageKey = "Welcome Message";
String welcomeMessageString = "Hello Baeldung!";
HTreeMap myMap = db.hashMap("myMap").createOrOpen();
myMap.put(welcomeMessageKey, welcomeMessageString);
String welcomeMessageFromDB = (String) myMap.get(welcomeMessageKey);
db.close();
assertEquals(welcomeMessageString, welcomeMessageFromDB);
}
}
@@ -0,0 +1,62 @@
package com.baeldung.mapdb;
import org.junit.Test;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.HTreeMap;
import org.mapdb.Serializer;
import static junit.framework.Assert.assertEquals;
public class InMemoryModesUnitTest {
@Test
public void givenDBCreatedOnHeap_whenUsed_checkUsageCorrect() {
DB heapDB = DBMaker.heapDB().make();
HTreeMap<Integer, String> map = heapDB
.hashMap("myMap")
.keySerializer(Serializer.INTEGER)
.valueSerializer(Serializer.STRING)
.createOrOpen();
map.put(1, "ONE");
assertEquals("ONE", map.get(1));
}
@Test
public void givenDBCreatedBaseOnByteArray_whenUsed_checkUsageCorrect() {
DB heapDB = DBMaker.memoryDB().make();
HTreeMap<Integer, String> map = heapDB
.hashMap("myMap")
.keySerializer(Serializer.INTEGER)
.valueSerializer(Serializer.STRING)
.createOrOpen();
map.put(1, "ONE");
assertEquals("ONE", map.get(1));
}
@Test
public void givenDBCreatedBaseOnDirectByteBuffer_whenUsed_checkUsageCorrect() {
DB heapDB = DBMaker.memoryDirectDB().make();
HTreeMap<Integer, String> map = heapDB
.hashMap("myMap")
.keySerializer(Serializer.INTEGER)
.valueSerializer(Serializer.STRING)
.createOrOpen();
map.put(1, "ONE");
assertEquals("ONE", map.get(1));
}
}
@@ -0,0 +1,47 @@
package com.baeldung.mapdb;
import org.junit.Test;
import org.mapdb.Serializer;
import org.mapdb.SortedTableMap;
import org.mapdb.volume.MappedFileVol;
import org.mapdb.volume.Volume;
import static junit.framework.Assert.assertEquals;
public class SortedTableMapUnitTest {
private static final String VOLUME_LOCATION = "sortedTableMapVol.db";
@Test
public void givenValidSortedTableMapSetup_whenQueried_checkValuesCorrect() {
//create memory mapped volume, readonly false
Volume vol = MappedFileVol.FACTORY.makeVolume(VOLUME_LOCATION, false);
//create sink to feed the map with data
SortedTableMap.Sink<Integer, String> sink =
SortedTableMap.create(
vol,
Serializer.INTEGER,
Serializer.STRING
).createFromSink();
//add content
for(int i = 0; i < 100; i++){
sink.put(i, "Value " + Integer.toString(i));
}
sink.create();
//now open in read-only mode
Volume openVol = MappedFileVol.FACTORY.makeVolume(VOLUME_LOCATION, true);
SortedTableMap<Integer, String> sortedTableMap = SortedTableMap.open(
openVol,
Serializer.INTEGER,
Serializer.STRING
);
assertEquals(100, sortedTableMap.size());
}
}
@@ -0,0 +1,41 @@
package com.baeldung.mapdb;
import org.junit.Test;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.Serializer;
import java.util.NavigableSet;
import static junit.framework.Assert.assertEquals;
public class TransactionsUnitTest {
@Test
public void givenValidDBSetup_whenTransactionCommittedAndRolledBack_checkPreviousStateAchieved() {
DB db = DBMaker.memoryDB().transactionEnable().make();
NavigableSet<String> set = db
.treeSet("mySet")
.serializer(Serializer.STRING)
.createOrOpen();
set.add("One");
set.add("Two");
db.commit();
assertEquals(2, set.size());
set.add("Three");
assertEquals(3, set.size());
db.rollback();
assertEquals(2, set.size());
db.close();
}
}
@@ -0,0 +1,102 @@
package com.baeldung.okhttp;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.InputStreamReader;
public class ResponseDecoderUnitTest {
@Rule public ExpectedException exceptionRule = ExpectedException.none();
@Rule public MockWebServer server = new MockWebServer();
SimpleEntity sampleResponse;
MockResponse mockResponse;
OkHttpClient client;
@Before
public void setUp() {
sampleResponse = new SimpleEntity("Baeldung");
client = new OkHttpClient.Builder().build();
mockResponse = new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "application/json")
.setBody(new Gson().toJson(sampleResponse));
}
@Test
public void givenJacksonDecoder_whenGetStringOfResponse_thenExpectSimpleEntity() throws Exception {
server.enqueue(mockResponse);
Request request = new Request.Builder()
.url(server.url(""))
.build();
ResponseBody responseBody = client
.newCall(request)
.execute()
.body();
Assert.assertNotNull(responseBody);
Assert.assertNotEquals(0, responseBody.contentLength());
ObjectMapper objectMapper = new ObjectMapper();
SimpleEntity entity = objectMapper.readValue(responseBody.string(), SimpleEntity.class);
Assert.assertNotNull(entity);
Assert.assertEquals(sampleResponse.getName(), entity.getName());
}
@Test
public void givenGsonDecoder_whenGetByteStreamOfResponse_thenExpectSimpleEntity() throws Exception {
server.enqueue(mockResponse);
Request request = new Request.Builder()
.url(server.url(""))
.build();
ResponseBody responseBody = client
.newCall(request)
.execute()
.body();
Assert.assertNotNull(responseBody);
Assert.assertNotEquals(0, responseBody.contentLength());
Gson gson = new Gson();
SimpleEntity entity = gson.fromJson(new InputStreamReader(responseBody.byteStream()), SimpleEntity.class);
Assert.assertNotNull(entity);
Assert.assertEquals(sampleResponse.getName(), entity.getName());
}
@Test
public void givenGsonDecoder_whenGetStringOfResponse_thenExpectSimpleEntity() throws Exception {
server.enqueue(mockResponse);
Request request = new Request.Builder()
.url(server.url(""))
.build();
ResponseBody responseBody = client
.newCall(request)
.execute()
.body();
Assert.assertNotNull(responseBody);
Gson gson = new Gson();
SimpleEntity entity = gson.fromJson(responseBody.string(), SimpleEntity.class);
Assert.assertNotNull(entity);
Assert.assertEquals(sampleResponse.getName(), entity.getName());
}
}
@@ -0,0 +1,22 @@
package com.baeldung.okhttp;
public class SimpleEntity {
protected String name;
public SimpleEntity(String name) {
this.name = name;
}
//no-arg constructor, getters and setters here
public SimpleEntity() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,168 @@
package com.baeldung.parallel_collectors;
import org.junit.Test;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import static com.pivovarit.collectors.ParallelCollectors.parallel;
import static com.pivovarit.collectors.ParallelCollectors.parallelOrdered;
import static com.pivovarit.collectors.ParallelCollectors.parallelToCollection;
import static com.pivovarit.collectors.ParallelCollectors.parallelToList;
import static com.pivovarit.collectors.ParallelCollectors.parallelToMap;
import static com.pivovarit.collectors.ParallelCollectors.parallelToStream;
public class ParallelCollectorsUnitTest {
@Test
public void shouldProcessInParallelWithStreams() {
List<Integer> ids = Arrays.asList(1, 2, 3);
List<String> results = ids.parallelStream()
.map(i -> fetchById(i))
.collect(Collectors.toList());
System.out.println(results);
}
@Test
public void shouldProcessInParallelWithParallelCollectors() {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> ids = Arrays.asList(1, 2, 3);
CompletableFuture<List<String>> results = ids.stream()
.collect(parallelToList(i -> fetchById(i), executor, 4));
System.out.println(results.join());
}
@Test
public void shouldCollectToList() {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> ids = Arrays.asList(1, 2, 3);
List<String> results = ids.stream()
.collect(parallelToList(i -> fetchById(i), executor, 4))
.join();
System.out.println(results); // [user-1, user-2, user-3]
}
@Test
public void shouldCollectToCollection() {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> ids = Arrays.asList(1, 2, 3);
List<String> results = ids.stream()
.collect(parallelToCollection(i -> fetchById(i), LinkedList::new, executor, 4))
.join();
System.out.println(results); // [user-1, user-2, user-3]
}
@Test
public void shouldCollectToStream() {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> ids = Arrays.asList(1, 2, 3);
Map<Integer, List<String>> results = ids.stream()
.collect(parallelToStream(i -> fetchById(i), executor, 4))
.thenApply(stream -> stream.collect(Collectors.groupingBy(i -> i.length())))
.join();
System.out.println(results); // [user-1, user-2, user-3]
}
@Test
public void shouldStreamInCompletionOrder() {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> ids = Arrays.asList(1, 2, 3);
ids.stream()
.collect(parallel(i -> fetchByIdWithRandomDelay(i), executor, 4))
.forEach(System.out::println);
}
@Test
public void shouldStreamInOriginalOrder() {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> ids = Arrays.asList(1, 2, 3);
ids.stream()
.collect(parallelOrdered(i -> fetchByIdWithRandomDelay(i), executor, 4))
.forEach(System.out::println);
}
@Test
public void shouldCollectToMap() {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> ids = Arrays.asList(1, 2, 3);
Map<Integer, String> results = ids.stream()
.collect(parallelToMap(i -> i, i -> fetchById(i), executor, 4))
.join();
System.out.println(results); // {1=user-1, 2=user-2, 3=user-3}
}
@Test
public void shouldCollectToTreeMap() {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> ids = Arrays.asList(1, 2, 3);
Map<Integer, String> results = ids.stream()
.collect(parallelToMap(i -> i, i -> fetchById(i), TreeMap::new, executor, 4))
.join();
System.out.println(results); // {1=user-1, 2=user-2, 3=user-3}
}
@Test
public void shouldCollectToTreeMapAndResolveClashes() {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> ids = Arrays.asList(1, 2, 3);
Map<Integer, String> results = ids.stream()
.collect(parallelToMap(i -> i, i -> fetchById(i), TreeMap::new, (s1, s2) -> s1, executor, 4))
.join();
System.out.println(results); // {1=user-1, 2=user-2, 3=user-3}
}
private static String fetchById(int id) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// ignore shamelessly
}
return "user-" + id;
}
private static String fetchByIdWithRandomDelay(int id) {
try {
Thread.sleep(ThreadLocalRandom.current().nextInt(1000));
} catch (InterruptedException e) {
// ignore shamelessly
}
return "user-" + id;
}
}
@@ -0,0 +1 @@
my data
@@ -0,0 +1 @@
Hi {{name}}!
@@ -0,0 +1,3 @@
{{#each friends}}
<span>{{name}} is my friend.</span>
{{/each}}
@@ -0,0 +1,3 @@
{{#each friends}}
<span>{{name}} is my friend.</span>
{{/each}}
@@ -0,0 +1 @@
Hi {{name}}!
@@ -0,0 +1 @@
<h4>Hi {{name}}!</h4>
@@ -0,0 +1,5 @@
{{#if busy}}
<h4>{{name}} is busy.</h4>
{{else}}
<h4>{{name}} is not busy.</h4>
{{/if}}
@@ -0,0 +1,5 @@
{{#if busy}}
<h4>{{name}} is busy.</h4>
{{^}}
<h4>{{name}} is not busy.</h4>
{{/if}}
@@ -0,0 +1,9 @@
<html>
<body>
{{#block "intro"}}
This is the intro
{{/block}}
{{#block "message"}}
{{/block}}
</body>
</html>
@@ -0,0 +1,2 @@
{{>header}}
<p>This is the page {{name}}</p>
@@ -0,0 +1 @@
{{#isBusy this}}{{/isBusy}}
@@ -0,0 +1,4 @@
{{#partial "message" }}
Hi there!
{{/partial}}
{{> messagebase}}
@@ -0,0 +1,3 @@
{{#with address}}
<h4>I live in {{street}}</h4>
{{/with}}
@@ -0,0 +1,3 @@
{{#address}}
<h4>I live in {{street}}</h4>
{{/address}}