Merge upstream/master
Conflicts: libraries/pom.xml
This commit is contained in:
+21
-3
@@ -8,9 +8,9 @@
|
||||
- [Embedded Jetty Server in Java](http://www.baeldung.com/jetty-embedded)
|
||||
- [Introduction to Apache Flink with Java](http://www.baeldung.com/apache-flink)
|
||||
- [Introduction to JSONassert](http://www.baeldung.com/jsonassert)
|
||||
- [Intro to JaVer](http://www.baeldung.com/javers)
|
||||
- [Intro to JaVers](http://www.baeldung.com/javers)
|
||||
- [Introduction to Apache Commons Math](http://www.baeldung.com/apache-commons-math)
|
||||
- [Intro to JaVer](http://www.baeldung.com/serenity-bdd)
|
||||
- [Intro to Serenity BDD](http://www.baeldung.com/serenity-bdd)
|
||||
- [Introduction to Netty](http://www.baeldung.com/netty)
|
||||
- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)
|
||||
- [Serenity BDD and Screenplay](http://www.baeldung.com/serenity-screenplay)
|
||||
@@ -39,8 +39,26 @@
|
||||
- [Introduction to Apache Commons CSV](http://www.baeldung.com/apache-commons-csv)
|
||||
- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference)
|
||||
- [Introduction to NoException](http://www.baeldung.com/no-exception)
|
||||
- [Introduction to FunctionalJava](http://www.baeldung.com/functional-java)
|
||||
- [Apache Commons IO](http://www.baeldung.com/apache-commons-io)
|
||||
- [Introduction to Conflict-Free Replicated Data Types](http://www.baeldung.com/java-conflict-free-replicated-data-types)
|
||||
- [Introduction to javax.measure](http://www.baeldung.com/javax-measure)
|
||||
- [Spring Yarg Integration](http://www.baeldung.com/spring-yarg)
|
||||
- [Delete a Directory Recursively in Java](http://www.baeldung.com/java-delete-directory)
|
||||
- [Guide to JDeferred](http://www.baeldung.com/jdeferred)
|
||||
- [Integrating Retrofit with RxJava](http://www.baeldung.com/retrofit-rxjava)
|
||||
- [Introduction to MBassador](http://www.baeldung.com/mbassador)
|
||||
- [Introduction to JCache](http://www.baeldung.com/jcache)
|
||||
- [Introduction to Retrofit](http://www.baeldung.com/retrofit)
|
||||
- [Using Pairs in Java](http://www.baeldung.com/java-pairs)
|
||||
- [Apache Commons Collections Bag](http://www.baeldung.com/apache-commons-bag)
|
||||
- [Introduction to Caffeine](http://www.baeldung.com/java-caching-caffeine)
|
||||
- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue)
|
||||
- [Introduction To Docx4J](http://www.baeldung.com/docx4j)
|
||||
- [Introduction to StreamEx](http://www.baeldung.com/streamex)
|
||||
- [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle)
|
||||
- [Intro to JDO Queries 2/2](http://www.baeldung.com/jdo-queries)
|
||||
- [Guide to google-http-client](http://www.baeldung.com/google-http-client)
|
||||
|
||||
|
||||
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.
|
||||
|
||||
|
||||
+82
-32
@@ -105,6 +105,13 @@
|
||||
</executions>
|
||||
</plugin>
|
||||
<!-- /Neuroph -->
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
@@ -326,6 +333,11 @@
|
||||
<artifactId>datanucleus-xml</artifactId>
|
||||
<version>5.0.0-release</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.datanucleus</groupId>
|
||||
<artifactId>datanucleus-jdo-query</artifactId>
|
||||
<version>5.0.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.openhft</groupId>
|
||||
<artifactId>chronicle</artifactId>
|
||||
@@ -487,7 +499,7 @@
|
||||
<artifactId>vavr</artifactId>
|
||||
<version>${vavr.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- Retrofit -->
|
||||
<dependency>
|
||||
<groupId>com.squareup.retrofit2</groupId>
|
||||
@@ -503,7 +515,7 @@
|
||||
<groupId>com.squareup.retrofit2</groupId>
|
||||
<artifactId>adapter-rxjava</artifactId>
|
||||
<version>${retrofit.version}</version>
|
||||
</dependency>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>logging-interceptor</artifactId>
|
||||
@@ -546,29 +558,29 @@
|
||||
<version>${protonpack.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.functionaljava</groupId>
|
||||
<artifactId>functionaljava</artifactId>
|
||||
<version>4.7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.functionaljava</groupId>
|
||||
<artifactId>functionaljava-java8</artifactId>
|
||||
<version>4.7</version>
|
||||
<groupId>org.functionaljava</groupId>
|
||||
<artifactId>functionaljava</artifactId>
|
||||
<version>4.7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.functionaljava</groupId>
|
||||
<artifactId>functionaljava-quickcheck</artifactId>
|
||||
<version>4.7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.functionaljava</groupId>
|
||||
<artifactId>functionaljava-java-core</artifactId>
|
||||
<version>4.7</version>
|
||||
<groupId>org.functionaljava</groupId>
|
||||
<artifactId>functionaljava-java8</artifactId>
|
||||
<version>4.7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.cache</groupId>
|
||||
<artifactId>cache-api</artifactId>
|
||||
<version>${cache.version}</version>
|
||||
<groupId>org.functionaljava</groupId>
|
||||
<artifactId>functionaljava-quickcheck</artifactId>
|
||||
<version>4.7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.functionaljava</groupId>
|
||||
<artifactId>functionaljava-java-core</artifactId>
|
||||
<version>4.7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.cache</groupId>
|
||||
<artifactId>cache-api</artifactId>
|
||||
<version>${cache.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.hazelcast</groupId>
|
||||
@@ -576,20 +588,59 @@
|
||||
<version>${hazelcast.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.atlassian.jira</groupId>
|
||||
<artifactId>jira-rest-java-client-core</artifactId>
|
||||
<version>4.0.0</version>
|
||||
<groupId>org.jgrapht</groupId>
|
||||
<artifactId>jgrapht-core</artifactId>
|
||||
<version>1.0.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.atlassian.fugue</groupId>
|
||||
<artifactId>fugue</artifactId>
|
||||
<version>3.0.0-m007</version>
|
||||
<groupId>com.netopyr.wurmloch</groupId>
|
||||
<artifactId>wurmloch-crdt</artifactId>
|
||||
<version>${crdt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jgrapht</groupId>
|
||||
<artifactId>jgrapht-core</artifactId>
|
||||
<version>1.0.1</version>
|
||||
</dependency>
|
||||
<groupId>org.docx4j</groupId>
|
||||
<artifactId>docx4j</artifactId>
|
||||
<version>3.3.5</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.xml.bind</groupId>
|
||||
<artifactId>jaxb-api</artifactId>
|
||||
<version>2.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.ben-manes.caffeine</groupId>
|
||||
<artifactId>caffeine</artifactId>
|
||||
<version>${caffeine.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk15on</artifactId>
|
||||
<version>1.58</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcpkix-jdk15on</artifactId>
|
||||
<version>1.58</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.http-client</groupId>
|
||||
<artifactId>google-http-client</artifactId>
|
||||
<version>${googleclient.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.http-client</groupId>
|
||||
<artifactId>google-http-client-jackson2</artifactId>
|
||||
<version>${googleclient.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.http-client</groupId>
|
||||
<artifactId>google-http-client-gson</artifactId>
|
||||
<version>${googleclient.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<repositories>
|
||||
<repository>
|
||||
@@ -605,12 +656,10 @@
|
||||
<name>bintray</name>
|
||||
<url>http://dl.bintray.com/cuba-platform/main</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>atlassian-public</id>
|
||||
<url>https://packages.atlassian.com/maven/repository/public</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
<properties>
|
||||
<googleclient.version>1.23.0</googleclient.version>
|
||||
<crdt.version>0.1.0</crdt.version>
|
||||
<multiverse.version>0.7.0</multiverse.version>
|
||||
<cglib.version>3.2.4</cglib.version>
|
||||
<commons-lang.version>3.6</commons-lang.version>
|
||||
@@ -663,6 +712,7 @@
|
||||
<protonpack.version>1.14</protonpack.version>
|
||||
<unit-ri.version>1.0.3</unit-ri.version>
|
||||
<cache.version>1.0.0</cache.version>
|
||||
<hazelcast.version>3.8.4</hazelcast.version>
|
||||
<hazelcast.version>3.8.4</hazelcast.version>
|
||||
<caffeine.version>2.5.5</caffeine.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.baeldung.bouncycastle;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.cert.CertificateEncodingException;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import org.bouncycastle.asn1.ASN1InputStream;
|
||||
import org.bouncycastle.asn1.cms.ContentInfo;
|
||||
import org.bouncycastle.cert.X509CertificateHolder;
|
||||
import org.bouncycastle.cert.jcajce.JcaCertStore;
|
||||
import org.bouncycastle.cms.CMSAlgorithm;
|
||||
import org.bouncycastle.cms.CMSEnvelopedData;
|
||||
import org.bouncycastle.cms.CMSEnvelopedDataGenerator;
|
||||
import org.bouncycastle.cms.CMSException;
|
||||
import org.bouncycastle.cms.CMSProcessableByteArray;
|
||||
import org.bouncycastle.cms.CMSSignedData;
|
||||
import org.bouncycastle.cms.CMSSignedDataGenerator;
|
||||
import org.bouncycastle.cms.CMSTypedData;
|
||||
import org.bouncycastle.cms.KeyTransRecipientInformation;
|
||||
import org.bouncycastle.cms.RecipientInformation;
|
||||
import org.bouncycastle.cms.SignerInformation;
|
||||
import org.bouncycastle.cms.SignerInformationStore;
|
||||
import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;
|
||||
import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder;
|
||||
import org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder;
|
||||
import org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient;
|
||||
import org.bouncycastle.cms.jcajce.JceKeyTransRecipient;
|
||||
import org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator;
|
||||
import org.bouncycastle.operator.ContentSigner;
|
||||
import org.bouncycastle.operator.OperatorCreationException;
|
||||
import org.bouncycastle.operator.OutputEncryptor;
|
||||
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
|
||||
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
|
||||
import org.bouncycastle.util.Store;
|
||||
|
||||
public class BouncyCastleCrypto {
|
||||
|
||||
public static byte[] signData(byte[] data, final X509Certificate signingCertificate, final PrivateKey signingKey)
|
||||
throws CertificateEncodingException, OperatorCreationException, CMSException, IOException {
|
||||
byte[] signedMessage = null;
|
||||
List<X509Certificate> certList = new ArrayList<X509Certificate>();
|
||||
CMSTypedData cmsData = new CMSProcessableByteArray(data);
|
||||
certList.add(signingCertificate);
|
||||
Store certs = new JcaCertStore(certList);
|
||||
CMSSignedDataGenerator cmsGenerator = new CMSSignedDataGenerator();
|
||||
ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA").build(signingKey);
|
||||
cmsGenerator.addSignerInfoGenerator(
|
||||
new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build())
|
||||
.build(contentSigner, signingCertificate));
|
||||
cmsGenerator.addCertificates(certs);
|
||||
CMSSignedData cms = cmsGenerator.generate(cmsData, true);
|
||||
signedMessage = cms.getEncoded();
|
||||
return signedMessage;
|
||||
}
|
||||
|
||||
public static boolean verifSignData(final byte[] signedData)
|
||||
throws CMSException, IOException, OperatorCreationException, CertificateException {
|
||||
ByteArrayInputStream bIn = new ByteArrayInputStream(signedData);
|
||||
ASN1InputStream aIn = new ASN1InputStream(bIn);
|
||||
CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject()));
|
||||
aIn.close();
|
||||
bIn.close();
|
||||
Store certs = s.getCertificates();
|
||||
SignerInformationStore signers = s.getSignerInfos();
|
||||
Collection<SignerInformation> c = signers.getSigners();
|
||||
SignerInformation signer = c.iterator().next();
|
||||
Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID());
|
||||
Iterator<X509CertificateHolder> certIt = certCollection.iterator();
|
||||
X509CertificateHolder certHolder = certIt.next();
|
||||
boolean verifResult = signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certHolder));
|
||||
if (!verifResult) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static byte[] encryptData(final byte[] data, X509Certificate encryptionCertificate)
|
||||
throws CertificateEncodingException, CMSException, IOException {
|
||||
byte[] encryptedData = null;
|
||||
if (null != data && null != encryptionCertificate) {
|
||||
CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator();
|
||||
JceKeyTransRecipientInfoGenerator jceKey = new JceKeyTransRecipientInfoGenerator(encryptionCertificate);
|
||||
cmsEnvelopedDataGenerator.addRecipientInfoGenerator(jceKey);
|
||||
CMSTypedData msg = new CMSProcessableByteArray(data);
|
||||
OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC")
|
||||
.build();
|
||||
CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator.generate(msg, encryptor);
|
||||
encryptedData = cmsEnvelopedData.getEncoded();
|
||||
}
|
||||
return encryptedData;
|
||||
}
|
||||
|
||||
public static byte[] decryptData(final byte[] encryptedData, final PrivateKey decryptionKey) throws CMSException {
|
||||
byte[] decryptedData = null;
|
||||
if (null != encryptedData && null != decryptionKey) {
|
||||
CMSEnvelopedData envelopedData = new CMSEnvelopedData(encryptedData);
|
||||
Collection<RecipientInformation> recip = envelopedData.getRecipientInfos().getRecipients();
|
||||
KeyTransRecipientInformation recipientInfo = (KeyTransRecipientInformation) recip.iterator().next();
|
||||
JceKeyTransRecipient recipient = new JceKeyTransEnvelopedRecipient(decryptionKey);
|
||||
decryptedData = recipientInfo.getContent(recipient);
|
||||
}
|
||||
return decryptedData;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.caffeine;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
final class DataObject {
|
||||
private final String data;
|
||||
|
||||
private static int objectCounter = 0;
|
||||
private static final Logger log = LoggerFactory.getLogger(DataObject.class);
|
||||
|
||||
private DataObject(String data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public String getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "DataObject{" +
|
||||
"data='" + data + '\'' +
|
||||
'}';
|
||||
}
|
||||
|
||||
public static DataObject get(String data) {
|
||||
objectCounter++;
|
||||
log.info("Init DataObject#{} with '{}'", objectCounter, data);
|
||||
return new DataObject(data);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ package com.baeldung.commons.lang3;
|
||||
import org.apache.commons.lang3.builder.EqualsBuilder;
|
||||
import org.apache.commons.lang3.builder.HashCodeBuilder;
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
import org.apache.commons.lang3.concurrent.ConcurrentException;
|
||||
import org.apache.commons.lang3.concurrent.BackgroundInitializer;
|
||||
|
||||
public class BuilderMethods {
|
||||
|
||||
@@ -56,5 +58,36 @@ public class BuilderMethods {
|
||||
System.out.println(simple1.getName());
|
||||
System.out.println(simple1.hashCode());
|
||||
System.out.println(simple1.toString());
|
||||
|
||||
SampleLazyInitializer sampleLazyInitializer = new SampleLazyInitializer();
|
||||
|
||||
try {
|
||||
sampleLazyInitializer.get();
|
||||
} catch (ConcurrentException e1) {
|
||||
// TODO Auto-generated catch block
|
||||
e1.printStackTrace();
|
||||
}
|
||||
|
||||
SampleBackgroundInitializer sampleBackgroundInitializer = new SampleBackgroundInitializer();
|
||||
sampleBackgroundInitializer.start();
|
||||
|
||||
// Proceed with other tasks instead of waiting for the SampleBackgroundInitializer task to finish.
|
||||
|
||||
try {
|
||||
Object result = sampleBackgroundInitializer.get();
|
||||
} catch (ConcurrentException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class SampleBackgroundInitializer extends BackgroundInitializer<String>{
|
||||
|
||||
@Override
|
||||
protected String initialize() throws Exception {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Any complex task that takes some time
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.baeldung.docx;
|
||||
|
||||
import org.docx4j.dml.wordprocessingDrawing.Inline;
|
||||
import org.docx4j.jaxb.Context;
|
||||
import org.docx4j.model.table.TblFactory;
|
||||
import org.docx4j.openpackaging.exceptions.Docx4JException;
|
||||
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
|
||||
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
|
||||
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
|
||||
import org.docx4j.wml.BooleanDefaultTrue;
|
||||
import org.docx4j.wml.Color;
|
||||
import org.docx4j.wml.Drawing;
|
||||
import org.docx4j.wml.ObjectFactory;
|
||||
import org.docx4j.wml.P;
|
||||
import org.docx4j.wml.R;
|
||||
import org.docx4j.wml.RPr;
|
||||
import org.docx4j.wml.Tbl;
|
||||
import org.docx4j.wml.Tc;
|
||||
import org.docx4j.wml.Text;
|
||||
import org.docx4j.wml.Tr;
|
||||
|
||||
import javax.xml.bind.JAXBElement;
|
||||
import javax.xml.bind.JAXBException;
|
||||
import java.io.File;
|
||||
import java.nio.file.Files;
|
||||
import java.util.List;
|
||||
|
||||
class Docx4jExample {
|
||||
|
||||
void createDocumentPackage(String outputPath, String imagePath) throws Exception {
|
||||
WordprocessingMLPackage wordPackage = WordprocessingMLPackage.createPackage();
|
||||
MainDocumentPart mainDocumentPart = wordPackage.getMainDocumentPart();
|
||||
mainDocumentPart.addStyledParagraphOfText("Title", "Hello World!");
|
||||
mainDocumentPart.addParagraphOfText("Welcome To Baeldung!");
|
||||
|
||||
ObjectFactory factory = Context.getWmlObjectFactory();
|
||||
P p = factory.createP();
|
||||
R r = factory.createR();
|
||||
Text t = factory.createText();
|
||||
t.setValue("Welcome To Baeldung");
|
||||
r.getContent().add(t);
|
||||
p.getContent().add(r);
|
||||
RPr rpr = factory.createRPr();
|
||||
BooleanDefaultTrue b = new BooleanDefaultTrue();
|
||||
rpr.setB(b);
|
||||
rpr.setI(b);
|
||||
rpr.setCaps(b);
|
||||
Color red = factory.createColor();
|
||||
red.setVal("green");
|
||||
rpr.setColor(red);
|
||||
r.setRPr(rpr);
|
||||
mainDocumentPart.getContent().add(p);
|
||||
|
||||
File image = new File(imagePath);
|
||||
byte[] fileContent = Files.readAllBytes(image.toPath());
|
||||
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage
|
||||
.createImagePart(wordPackage, fileContent);
|
||||
Inline inline = imagePart.createImageInline(
|
||||
"Baeldung Image", "Alt Text", 1, 2, false);
|
||||
P Imageparagraph = addImageToParagraph(inline);
|
||||
mainDocumentPart.getContent().add(Imageparagraph);
|
||||
|
||||
int writableWidthTwips = wordPackage.getDocumentModel()
|
||||
.getSections().get(0).getPageDimensions()
|
||||
.getWritableWidthTwips();
|
||||
int columnNumber = 3;
|
||||
Tbl tbl = TblFactory.createTable(3, 3, writableWidthTwips / columnNumber);
|
||||
List<Object> rows = tbl.getContent();
|
||||
for (Object row : rows) {
|
||||
Tr tr = (Tr) row;
|
||||
List<Object> cells = tr.getContent();
|
||||
for (Object cell : cells) {
|
||||
Tc td = (Tc) cell;
|
||||
td.getContent().add(p);
|
||||
}
|
||||
}
|
||||
|
||||
mainDocumentPart.getContent().add(tbl);
|
||||
File exportFile = new File(outputPath);
|
||||
wordPackage.save(exportFile);
|
||||
}
|
||||
|
||||
boolean isTextExist(String testText) throws Docx4JException, JAXBException {
|
||||
File doc = new File("helloWorld.docx");
|
||||
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(doc);
|
||||
MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart();
|
||||
String textNodesXPath = "//w:t";
|
||||
List<Object> paragraphs = mainDocumentPart.getJAXBNodesViaXPath(textNodesXPath, true);
|
||||
for (Object obj : paragraphs) {
|
||||
Text text = (Text) ((JAXBElement) obj).getValue();
|
||||
String textValue = text.getValue();
|
||||
if (textValue != null && textValue.contains(testText)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static P addImageToParagraph(Inline inline) {
|
||||
ObjectFactory factory = new ObjectFactory();
|
||||
P p = factory.createP();
|
||||
R r = factory.createR();
|
||||
p.getContent().add(r);
|
||||
Drawing drawing = factory.createDrawing();
|
||||
r.getContent().add(drawing);
|
||||
drawing.getAnchorOrInline().add(inline);
|
||||
return p;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.baeldung.googlehttpclientguide;
|
||||
|
||||
import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler;
|
||||
import com.google.api.client.http.HttpRequest;
|
||||
import com.google.api.client.http.HttpRequestFactory;
|
||||
import com.google.api.client.http.HttpResponse;
|
||||
import com.google.api.client.http.HttpResponseException;
|
||||
import com.google.api.client.http.HttpTransport;
|
||||
import com.google.api.client.http.apache.ApacheHttpTransport;
|
||||
import com.google.api.client.http.javanet.NetHttpTransport;
|
||||
import com.google.api.client.json.JsonFactory;
|
||||
import com.google.api.client.json.JsonObjectParser;
|
||||
import com.google.api.client.json.jackson2.JacksonFactory;
|
||||
import com.google.api.client.util.ExponentialBackOff;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
public class GitHubExample {
|
||||
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
|
||||
//static final HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport();
|
||||
static final JsonFactory JSON_FACTORY = new JacksonFactory();
|
||||
//static final JsonFactory JSON_FACTORY = new GsonFactory();
|
||||
|
||||
private static void run() throws Exception {
|
||||
HttpRequestFactory requestFactory
|
||||
= HTTP_TRANSPORT.createRequestFactory(
|
||||
(HttpRequest request) -> {
|
||||
request.setParser(new JsonObjectParser(JSON_FACTORY));
|
||||
});
|
||||
GitHubUrl url = new GitHubUrl("https://api.github.com/users");
|
||||
url.per_page = 10;
|
||||
url.page = 1;
|
||||
HttpRequest request = requestFactory.buildGetRequest(url);
|
||||
ExponentialBackOff backoff = new ExponentialBackOff.Builder()
|
||||
.setInitialIntervalMillis(500)
|
||||
.setMaxElapsedTimeMillis(900000)
|
||||
.setMaxIntervalMillis(6000)
|
||||
.setMultiplier(1.5)
|
||||
.setRandomizationFactor(0.5)
|
||||
.build();
|
||||
request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
|
||||
Type type = new TypeToken<List<User>>() {}.getType();
|
||||
List<User> users = (List<User>)request.execute().parseAs(type);
|
||||
System.out.println(users);
|
||||
url.appendRawPath("/eugenp");
|
||||
request = requestFactory.buildGetRequest(url);
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
Future<HttpResponse> responseFuture = request.executeAsync(executor);
|
||||
User eugen = responseFuture.get().parseAs(User.class);
|
||||
System.out.println(eugen);
|
||||
executor.shutdown();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
run();
|
||||
} catch (Exception e) {
|
||||
System.err.println(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.googlehttpclientguide;
|
||||
|
||||
import com.google.api.client.http.GenericUrl;
|
||||
import com.google.api.client.util.Key;
|
||||
|
||||
public class GitHubUrl extends GenericUrl{
|
||||
|
||||
public GitHubUrl(String encodedUrl) {
|
||||
super(encodedUrl);
|
||||
}
|
||||
|
||||
@Key
|
||||
public int per_page;
|
||||
|
||||
@Key
|
||||
public int page;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.baeldung.googlehttpclientguide;
|
||||
|
||||
import com.google.api.client.json.GenericJson;
|
||||
import com.google.api.client.util.Key;
|
||||
|
||||
public class User extends GenericJson {
|
||||
@Key
|
||||
private String login;
|
||||
@Key
|
||||
private long id;
|
||||
@Key
|
||||
private String url;
|
||||
@Key
|
||||
private String company;
|
||||
@Key
|
||||
private String blog;
|
||||
@Key
|
||||
private String email;
|
||||
|
||||
@Key("subscriptions_url")
|
||||
private String subscriptionsUrl;
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setUrl(String url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
public String getCompany() {
|
||||
return company;
|
||||
}
|
||||
|
||||
public void setCompany(String company) {
|
||||
this.company = company;
|
||||
}
|
||||
|
||||
public String getBlog() {
|
||||
return blog;
|
||||
}
|
||||
|
||||
public void setBlog(String blog) {
|
||||
this.blog = blog;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}';
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# Properties file which configures the operation of the JDK logging facility.
|
||||
# The system will look for this config file to be specified as a system property:
|
||||
# -Djava.util.logging.config.file=${project_loc:dailymotion-simple-cmdline-sample}/logging.properties
|
||||
|
||||
# Set up the console handler (uncomment "level" to show more fine-grained messages)
|
||||
handlers = java.util.logging.ConsoleHandler
|
||||
java.util.logging.ConsoleHandler.level = ALL
|
||||
|
||||
# Set up logging of HTTP requests and responses (uncomment "level" to show)
|
||||
com.google.api.client.http.level = ALL
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.baeldung.jdo.query;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.jdo.JDOQLTypedQuery;
|
||||
import javax.jdo.PersistenceManager;
|
||||
import javax.jdo.PersistenceManagerFactory;
|
||||
import javax.jdo.Query;
|
||||
|
||||
import org.datanucleus.api.jdo.JDOPersistenceManagerFactory;
|
||||
import org.datanucleus.metadata.PersistenceUnitMetaData;
|
||||
|
||||
public class MyApp {
|
||||
|
||||
private static PersistenceManagerFactory pmf;
|
||||
private static PersistenceManager pm;
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
defineDynamicPersistentUnit();
|
||||
createTestData();
|
||||
queryUsingJDOQL();
|
||||
queryUsingTypedJDOQL();
|
||||
queryUsingSQL();
|
||||
queryUsingJPQL();
|
||||
|
||||
}
|
||||
|
||||
public static void createTestData(){
|
||||
ProductItem item1 = new ProductItem("supportedItem", "price less than 10", "SoldOut",5);
|
||||
ProductItem item2 = new ProductItem("pro2", "price less than 10","InStock", 8);
|
||||
ProductItem item3 = new ProductItem("pro3", "price more than 10","SoldOut", 15);
|
||||
|
||||
if( pm != null ){
|
||||
pm.makePersistent(item1);
|
||||
pm.makePersistent(item2);
|
||||
pm.makePersistent(item3);
|
||||
}
|
||||
}
|
||||
|
||||
public static void defineDynamicPersistentUnit(){
|
||||
|
||||
PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
|
||||
pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:mysql://localhost:3306/jdo_db");
|
||||
pumd.addProperty("javax.jdo.option.ConnectionUserName", "root");
|
||||
pumd.addProperty("javax.jdo.option.ConnectionPassword", "admin");
|
||||
pumd.addProperty("javax.jdo.option.ConnectionDriverName", "com.mysql.jdbc.Driver");
|
||||
pumd.addProperty("datanucleus.schema.autoCreateAll", "true");
|
||||
|
||||
pmf = new JDOPersistenceManagerFactory(pumd, null);
|
||||
pm = pmf.getPersistenceManager();
|
||||
}
|
||||
|
||||
public static void queryUsingJDOQL(){
|
||||
|
||||
Query query = pm.newQuery("SELECT FROM com.baeldung.jdo.query.ProductItem "
|
||||
+ "WHERE price < threshold PARAMETERS double threshold");
|
||||
List<ProductItem> explicitParamResults = (List<ProductItem>)query.execute(10);
|
||||
|
||||
query = pm.newQuery("SELECT FROM "
|
||||
+ "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
|
||||
query.setParameters("double threshold");
|
||||
List<ProductItem> explicitParamResults2 = (List<ProductItem>)query.execute(10);
|
||||
|
||||
query = pm.newQuery("SELECT FROM "
|
||||
+ "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
|
||||
List<ProductItem> implicitParamResults = (List<ProductItem>)query.execute(10);
|
||||
|
||||
}
|
||||
|
||||
public static void queryUsingTypedJDOQL(){
|
||||
|
||||
JDOQLTypedQuery<ProductItem> tq = pm.newJDOQLTypedQuery(ProductItem.class);
|
||||
QProductItem cand = QProductItem.candidate();
|
||||
tq=tq.filter(cand.price.lt(10).and(cand.name.startsWith("pro")));
|
||||
List<ProductItem> results = tq.executeList();
|
||||
|
||||
}
|
||||
|
||||
public static void queryUsingSQL(){
|
||||
|
||||
Query query = pm.newQuery("javax.jdo.query.SQL","select * from "
|
||||
+ "product_item where price < ? and status = ?");
|
||||
query.setClass(ProductItem.class);
|
||||
query.setParameters(10,"InStock");
|
||||
List<ProductItem> results = query.executeList();
|
||||
|
||||
}
|
||||
|
||||
public static void queryUsingJPQL(){
|
||||
Query query = pm.newQuery("JPQL","select i from "
|
||||
+ "com.baeldung.jdo.query.ProductItem i where i.price < 10"
|
||||
+ " and i.status = 'InStock'");
|
||||
List<ProductItem> results = (List<ProductItem>) query.execute();
|
||||
|
||||
}
|
||||
|
||||
public static void namedQuery(){
|
||||
Query<ProductItem> query = pm.newNamedQuery(
|
||||
ProductItem.class, "PriceBelow10");
|
||||
List<ProductItem> results = query.executeList();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.jdo.query;
|
||||
|
||||
import javax.jdo.annotations.IdGeneratorStrategy;
|
||||
import javax.jdo.annotations.PersistenceAware;
|
||||
import javax.jdo.annotations.PersistenceCapable;
|
||||
import javax.jdo.annotations.Persistent;
|
||||
import javax.jdo.annotations.PrimaryKey;
|
||||
|
||||
@PersistenceCapable(table = "product_item")
|
||||
public class ProductItem {
|
||||
|
||||
@PrimaryKey
|
||||
@Persistent(valueStrategy=IdGeneratorStrategy.INCREMENT)
|
||||
int id;
|
||||
String name;
|
||||
String description;
|
||||
String status;
|
||||
double price;
|
||||
|
||||
public ProductItem(){
|
||||
|
||||
}
|
||||
|
||||
public ProductItem(String name,String description,String status,double price){
|
||||
this.name=name;
|
||||
this.description = description;
|
||||
this.status = status;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
public double getPrice() {
|
||||
return price;
|
||||
}
|
||||
public void setPrice(double price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.jdo.xml;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.jdo.annotations.Element;
|
||||
import javax.jdo.annotations.PersistenceCapable;
|
||||
import javax.jdo.annotations.PrimaryKey;
|
||||
import javax.xml.bind.annotation.XmlAttribute;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlElementWrapper;
|
||||
|
||||
@PersistenceCapable(
|
||||
schema="/myproduct/people",
|
||||
table="person"
|
||||
)
|
||||
public class AnnotadedPerson {
|
||||
@XmlAttribute
|
||||
private long personNum;
|
||||
|
||||
@PrimaryKey
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
@XmlElementWrapper(name="phone-numbers")
|
||||
@XmlElement(name="phone-number")
|
||||
@Element(types=String.class)
|
||||
private List phoneNumbers = new ArrayList();
|
||||
|
||||
|
||||
public AnnotadedPerson(long personNum, String firstName, String lastName) {
|
||||
super();
|
||||
this.personNum = personNum;
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public long getPersonNum() {
|
||||
return personNum;
|
||||
}
|
||||
|
||||
public void setPersonNum(long personNum) {
|
||||
this.personNum = personNum;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public List getPhoneNumbers() {
|
||||
return phoneNumbers;
|
||||
}
|
||||
|
||||
public void setPhoneNumbers(List phoneNumbers) {
|
||||
this.phoneNumbers = phoneNumbers;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.baeldung.jdo.xml;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.jdo.JDOHelper;
|
||||
import javax.jdo.PersistenceManager;
|
||||
import javax.jdo.PersistenceManagerFactory;
|
||||
import javax.jdo.Query;
|
||||
import javax.jdo.Transaction;
|
||||
|
||||
import org.datanucleus.api.jdo.JDOPersistenceManagerFactory;
|
||||
import org.datanucleus.metadata.PersistenceUnitMetaData;
|
||||
|
||||
public class MyApp {
|
||||
|
||||
private static PersistenceUnitMetaData pumd;
|
||||
private static PersistenceManagerFactory pmf;
|
||||
private static PersistenceManager pm;
|
||||
|
||||
public static void main( String[] args ) {
|
||||
|
||||
//persist product object using dynamic persistence unit
|
||||
defineDynamicPersistentUnit();
|
||||
Product product = new Product("id1","Sony Discman", "A standard discman from Sony", 49.99);
|
||||
persistObject(product);
|
||||
closePersistenceManager();
|
||||
|
||||
//persist AnnotatedPerson object using named pmf
|
||||
defineNamedPersistenceManagerFactory("XmlDatastore");
|
||||
AnnotadedPerson annotatedPerson = new AnnotadedPerson(654320,"annotated","person");
|
||||
annotatedPerson.getPhoneNumbers().add("999999999");
|
||||
annotatedPerson.getPhoneNumbers().add("000000000");
|
||||
persistObject(annotatedPerson);
|
||||
queryAnnotatedPersonsInXML();
|
||||
closePersistenceManager();
|
||||
|
||||
//persist Person object using PMF created by properties file
|
||||
definePersistenceManagerFactoryUsingPropertiesFile("META-INF\\datanucleus.properties");
|
||||
Person person = new Person(654321,"bealdung","author");
|
||||
person.getPhoneNumbers().add("123456789");
|
||||
person.getPhoneNumbers().add("987654321");
|
||||
persistObject(person);
|
||||
queryPersonsInXML();
|
||||
closePersistenceManager();
|
||||
}
|
||||
|
||||
public static void defineDynamicPersistentUnit(){
|
||||
|
||||
PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
|
||||
pumd.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myfile_dynamicPMF.xml");
|
||||
pumd.addProperty("datanucleus.schema.autoCreateAll", "true");
|
||||
pumd.addProperty("datanucleus.xml.indentSize", "4");
|
||||
|
||||
pmf = new JDOPersistenceManagerFactory(pumd, null);
|
||||
pm = pmf.getPersistenceManager();
|
||||
}
|
||||
|
||||
public static void defineNamedPersistenceManagerFactory(String pmfName){
|
||||
|
||||
pmf = JDOHelper.getPersistenceManagerFactory("XmlDatastore");
|
||||
pm = pmf.getPersistenceManager();
|
||||
}
|
||||
|
||||
public static void definePersistenceManagerFactoryUsingPropertiesFile(String filePath){
|
||||
|
||||
pmf = JDOHelper.getPersistenceManagerFactory(filePath);
|
||||
pm = pmf.getPersistenceManager();
|
||||
}
|
||||
|
||||
public static void closePersistenceManager(){
|
||||
|
||||
if(pm!=null && !pm.isClosed()){
|
||||
pm.close();
|
||||
}
|
||||
}
|
||||
|
||||
public static void persistObject(Object obj){
|
||||
|
||||
Transaction tx = pm.currentTransaction();
|
||||
|
||||
try {
|
||||
tx.begin();
|
||||
pm.makePersistent(obj);
|
||||
tx.commit();
|
||||
} finally {
|
||||
if (tx.isActive()) {
|
||||
tx.rollback();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void queryPersonsInXML(){
|
||||
|
||||
Query<Person> query = pm.newQuery(Person.class);
|
||||
List<Person> result = query.executeList();
|
||||
System.out.println("name: "+result.get(0).getFirstName());
|
||||
}
|
||||
|
||||
public static void queryAnnotatedPersonsInXML(){
|
||||
|
||||
Query<AnnotadedPerson> query = pm.newQuery(AnnotadedPerson.class);
|
||||
List<AnnotadedPerson> result = query.executeList();
|
||||
System.out.println("name: "+result.get(0).getFirstName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.baeldung.jdo.xml;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.jdo.annotations.Element;
|
||||
import javax.jdo.annotations.PersistenceCapable;
|
||||
import javax.jdo.annotations.PrimaryKey;
|
||||
import javax.xml.bind.annotation.XmlAttribute;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlElementWrapper;
|
||||
|
||||
|
||||
@PersistenceCapable
|
||||
public class Person {
|
||||
private long personNum;
|
||||
|
||||
@PrimaryKey
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
private List phoneNumbers = new ArrayList();
|
||||
|
||||
public Person(long personNum, String firstName, String lastName) {
|
||||
super();
|
||||
this.personNum = personNum;
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public long getPersonNum() {
|
||||
return personNum;
|
||||
}
|
||||
|
||||
public void setPersonNum(long personNum) {
|
||||
this.personNum = personNum;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public List getPhoneNumbers() {
|
||||
return phoneNumbers;
|
||||
}
|
||||
|
||||
public void setPhoneNumbers(List phoneNumbers) {
|
||||
this.phoneNumbers = phoneNumbers;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.jdo.xml;
|
||||
|
||||
import javax.jdo.annotations.IdGeneratorStrategy;
|
||||
import javax.jdo.annotations.PersistenceAware;
|
||||
import javax.jdo.annotations.PersistenceCapable;
|
||||
import javax.jdo.annotations.Persistent;
|
||||
import javax.jdo.annotations.PrimaryKey;
|
||||
|
||||
@PersistenceCapable
|
||||
public class Product {
|
||||
|
||||
@PrimaryKey
|
||||
String id;
|
||||
String name;
|
||||
String description;
|
||||
double price;
|
||||
|
||||
public Product(){
|
||||
|
||||
}
|
||||
|
||||
public Product(String id,String name,String description,double price){
|
||||
this.id = id;
|
||||
this.name=name;
|
||||
this.description = description;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
public double getPrice() {
|
||||
return price;
|
||||
}
|
||||
public void setPrice(double price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package com.baeldung.jira;
|
||||
|
||||
import com.atlassian.jira.rest.client.api.JiraRestClient;
|
||||
import com.atlassian.jira.rest.client.api.JiraRestClientFactory;
|
||||
import com.atlassian.jira.rest.client.api.domain.Issue;
|
||||
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
|
||||
public class JiraClient {
|
||||
|
||||
private static final String USERNAME = "jira.user";
|
||||
private static final String PASSWORD = "secret";
|
||||
private static final String JIRA_URL = "http://jira.company.com";
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
final Issue issue = new JiraClient().getIssue("MYKEY-1234");
|
||||
System.out.println(issue.getDescription());
|
||||
}
|
||||
|
||||
private Issue getIssue(String issueKey) {
|
||||
JiraRestClient restClient = getJiraRestClient();
|
||||
Issue issue = restClient.getIssueClient().getIssue(issueKey).claim();
|
||||
|
||||
closeRestClient(restClient);
|
||||
return issue;
|
||||
}
|
||||
|
||||
private JiraRestClient getJiraRestClient() {
|
||||
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
|
||||
|
||||
URI jiraServerUri = getJiraUri();
|
||||
return factory
|
||||
.createWithBasicHttpAuthentication(jiraServerUri, USERNAME, PASSWORD);
|
||||
}
|
||||
|
||||
private URI getJiraUri() {
|
||||
URI jiraServerUri = null;
|
||||
try {
|
||||
jiraServerUri = new URI(JIRA_URL);
|
||||
} catch (URISyntaxException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return jiraServerUri;
|
||||
}
|
||||
|
||||
private void closeRestClient(JiraRestClient restClient) {
|
||||
try {
|
||||
restClient.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.streamex;
|
||||
|
||||
public class Role {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.baeldung.streamex;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import one.util.streamex.DoubleStreamEx;
|
||||
import one.util.streamex.EntryStream;
|
||||
import one.util.streamex.IntStreamEx;
|
||||
import one.util.streamex.StreamEx;
|
||||
|
||||
public class StreamEX {
|
||||
|
||||
public static void main(String[] args) {
|
||||
//Collector shortcut methods (toList, toSet, groupingBy, joining, etc.)
|
||||
List<User> users = Arrays.asList(
|
||||
new User("name"), new User(), new User());
|
||||
users.stream()
|
||||
.map(User::getName)
|
||||
.collect(Collectors.toList());
|
||||
List<String> userNames = StreamEx.of(users)
|
||||
.map(User::getName)
|
||||
.toList();
|
||||
Map<Role, List<User>> role2users = StreamEx.of(users)
|
||||
.groupingBy(User::getRole);
|
||||
StreamEx.of(1, 2, 3).joining("; "); // "1; 2; 3"
|
||||
//Selecting stream elements of specific type
|
||||
List usersAndRoles = Arrays.asList(new User(), new Role());
|
||||
List<Role> roles = IntStreamEx.range(usersAndRoles.size())
|
||||
.mapToObj(usersAndRoles::get)
|
||||
.select(Role.class)
|
||||
.toList();
|
||||
System.out.println(roles);
|
||||
//adding elements to Stream
|
||||
List<String> appendedUsers = StreamEx.of(users)
|
||||
.map(User::getName)
|
||||
.prepend("(none)")
|
||||
.append("LAST")
|
||||
.toList();
|
||||
System.out.println(appendedUsers);
|
||||
//Removing unwanted elements and using the stream as Iterable:
|
||||
for (String line : StreamEx.of(users).map(User::getName)
|
||||
.nonNull()) {
|
||||
System.out.println(line);
|
||||
}
|
||||
//Selecting map keys by value predicate:
|
||||
Map<String, Role> nameToRole = new HashMap<>();
|
||||
nameToRole.put("first", new Role());
|
||||
nameToRole.put("second", null);
|
||||
Set<String> nonNullRoles = StreamEx.
|
||||
ofKeys(nameToRole, Objects::nonNull)
|
||||
.toSet();
|
||||
System.out.println(nonNullRoles);
|
||||
//Operating on key-value pairs:
|
||||
Map<User, List<Role>> users2roles = transformMap(role2users);
|
||||
Map<String, String> mapToString = EntryStream.of(users2roles)
|
||||
.mapKeys(String::valueOf)
|
||||
.mapValues(String::valueOf)
|
||||
.toMap();
|
||||
//Support of byte/char/short/float types:
|
||||
short[] src = {1, 2, 3};
|
||||
char[] output = IntStreamEx.of(src)
|
||||
.map(x -> x * 5)
|
||||
.toCharArray();
|
||||
}
|
||||
|
||||
public double[] getDiffBetweenPairs(double... numbers) {
|
||||
return DoubleStreamEx.of(numbers)
|
||||
.pairMap((a, b) -> b - a).toArray();
|
||||
}
|
||||
|
||||
public static Map<User, List<Role>> transformMap(
|
||||
Map<Role, List<User>> role2users) {
|
||||
Map<User, List<Role>> users2roles = EntryStream.of(role2users)
|
||||
.flatMapValues(List::stream)
|
||||
.invert()
|
||||
.grouping();
|
||||
return users2roles;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.streamex;
|
||||
|
||||
public class User {
|
||||
|
||||
int id;
|
||||
String name;
|
||||
Role role = new Role();
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Role getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(Role role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDPjCCAiagAwIBAgIJAPvd1gx14C3CMA0GCSqGSIb3DQEBBQUAMEcxCzAJBgNV
|
||||
BAYTAk1BMRAwDgYDVQQIEwdNb3JvY2NvMRMwEQYDVQQHEwpDYXNhYmxhbmNhMREw
|
||||
DwYDVQQDEwhCYWVsZHVuZzAeFw0xNzEwMTIxMDQzMTRaFw0yNzEwMTMxMDQzMTRa
|
||||
MEcxCzAJBgNVBAYTAk1BMRAwDgYDVQQIEwdNb3JvY2NvMRMwEQYDVQQHEwpDYXNh
|
||||
YmxhbmNhMREwDwYDVQQDEwhCYWVsZHVuZzCCASIwDQYJKoZIhvcNAQEBBQADggEP
|
||||
ADCCAQoCggEBAMyi5GmOeN4QaH/CP5gSOyHX8znb5TDHWV8wc+ZT7kNU8zt5tGMh
|
||||
jozK6hax155/6tOsBDR0rSYBhL+Dm/+uCVS7qOlRHhf6cNGtzGF1gnNJB2WjI8oM
|
||||
AYm24xpLj1WphKUwKrn3nTMPnQup5OoNAMYl99flANrRYVjjxrLQvDZDUio6Iujr
|
||||
CZ2TtXGM0g/gP++28KT7g1KlUui3xtB0u33wx7UN8Fix3JmjOaPHGwxGpwP3VGSj
|
||||
fs8cuhqVwRQaZpCOoHU/P8wpXKw80sSdhz+SRueMPtVYqK0CiLL5/O0h0Y3le4IV
|
||||
whgg3KG1iTGOWn60UMFn1EYmQ18k5Nsma6UCAwEAAaMtMCswCQYDVR0TBAIwADAR
|
||||
BglghkgBhvhCAQEEBAMCBPAwCwYDVR0PBAQDAgUgMA0GCSqGSIb3DQEBBQUAA4IB
|
||||
AQC8DDBmJ3p4xytxBiE0s4p1715WT6Dm/QJHp0XC0hkSoyZKDh+XVmrzm+J3SiW1
|
||||
vpswb5hLgPo040YX9jnDmgOD+TpleTuKHxZRYj92UYWmdjkWLVtFMcvOh+gxBiAP
|
||||
pHIqZsqo8lfcyAuh8Jx834IXbknfCUtERDLG/rU9P/3XJhrM2GC5qPQznrW4EYhU
|
||||
CGPyIJXmvATMVvXMWCtfogAL+n42vjYXQXZoAWomHhLHoNbSJUErnNdWDOh4WoJt
|
||||
XJCxA6U5LSBplqb3wB2hUTqw+0admKltvmy+KA1PD7OxoGiY7V544zeGqJam1qxU
|
||||
ia7y5BL6uOa/4ShSV8pcJDYz
|
||||
-----END CERTIFICATE-----
|
||||
Binary file not shown.
@@ -0,0 +1,4 @@
|
||||
javax.jdo.PersistenceManagerFactoryClass=org.datanucleus.api.jdo.JDOPersistenceManagerFactory
|
||||
javax.jdo.option.ConnectionURL= xml:file:myfile-ds.xml
|
||||
datanucleus.xml.indentSize=6
|
||||
datanucleus.schema.autoCreateAll=true
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<jdoconfig xmlns="http://xmlns.jcp.org/xml/ns/jdo/jdoconfig"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/jdo/jdoconfig
|
||||
http://xmlns.jcp.org/xml/ns/jdo/jdoconfig_3_2.xsd"
|
||||
version="3.2">
|
||||
|
||||
<!-- Datastore Txn PMF -->
|
||||
<persistence-manager-factory name="XmlDatastore">
|
||||
<property name="javax.jdo.PersistenceManagerFactoryClass"
|
||||
value="org.datanucleus.api.jdo.JDOPersistenceManagerFactory" />
|
||||
<property name="javax.jdo.option.ConnectionURL" value="xml:file:namedPMF-ds.xml" />
|
||||
<property name="datanucleus.xml.indentSize" value="6" />
|
||||
<property name="datanucleus.schema.autoCreateAll"
|
||||
value="true" />
|
||||
</persistence-manager-factory>
|
||||
</jdoconfig>
|
||||
@@ -0,0 +1,29 @@
|
||||
<jdo xmlns="http://xmlns.jcp.org/xml/ns/jdo/jdo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/jdo/jdo http://xmlns.jcp.org/xml/ns/jdo/jdo_3_1.xsd"
|
||||
version="3.1">
|
||||
<package name="com.baeldung.jdo.xml">
|
||||
<class name="Person" detachable="true" schema="/myproduct/people"
|
||||
table="person">
|
||||
<field name="personNum">
|
||||
<extension vendor-name="datanucleus" key="XmlAttribute"
|
||||
value="true" />
|
||||
</field>
|
||||
<field name="firstName" primary-key="true" /> <!-- PK since JAXB requires String -->
|
||||
<field name="lastName" />
|
||||
<field name="phoneNumbers">
|
||||
<collection element-type="java.lang.String" />
|
||||
<element column="phoneNumber" />
|
||||
</field>
|
||||
</class>
|
||||
</package>
|
||||
<package name="com.baeldung.jdo.query">
|
||||
<class name="ProductItem" detachable="true" table="product_item">
|
||||
|
||||
<query name="PriceBelow10" language="javax.jdo.query.SQL">
|
||||
<![CDATA[SELECT * FROM PRODUCT_ITEM WHERE PRICE < 10
|
||||
]]></query>
|
||||
|
||||
</class>
|
||||
</package>
|
||||
|
||||
</jdo>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 69 KiB |
@@ -1,6 +1,5 @@
|
||||
package com.baeldung.awaitility;
|
||||
|
||||
import org.awaitility.Awaitility;
|
||||
import org.awaitility.Duration;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.bouncycastle;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.security.KeyStore;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.NoSuchProviderException;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.Security;
|
||||
import java.security.UnrecoverableKeyException;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
import org.bouncycastle.cms.CMSException;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
import org.bouncycastle.operator.OperatorCreationException;
|
||||
import org.junit.Test;
|
||||
|
||||
public class BouncyCastleLiveTest {
|
||||
|
||||
String certificatePath = "src/main/resources/Baeldung.cer";
|
||||
String privateKeyPath = "src/main/resources/Baeldung.p12";
|
||||
char[] p12Password = "password".toCharArray();
|
||||
char[] keyPassword = "password".toCharArray();
|
||||
|
||||
@Test
|
||||
public void givenCryptographicResource_whenOperationSuccess_returnTrue()
|
||||
throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException,
|
||||
KeyStoreException, UnrecoverableKeyException, CMSException, OperatorCreationException {
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
|
||||
CertificateFactory certFactory = CertificateFactory.getInstance("X.509", "BC");
|
||||
X509Certificate certificate = (X509Certificate) certFactory
|
||||
.generateCertificate(new FileInputStream(certificatePath));
|
||||
KeyStore keystore = KeyStore.getInstance("PKCS12");
|
||||
keystore.load(new FileInputStream(privateKeyPath), p12Password);
|
||||
PrivateKey privateKey = (PrivateKey) keystore.getKey("baeldung", keyPassword);
|
||||
String secretMessage = "My password is 123456Seven";
|
||||
System.out.println("Original Message : " + secretMessage);
|
||||
byte[] stringToEncrypt = secretMessage.getBytes();
|
||||
byte[] encryptedData = BouncyCastleCrypto.encryptData(stringToEncrypt, certificate);
|
||||
byte[] rawData = BouncyCastleCrypto.decryptData(encryptedData, privateKey);
|
||||
String decryptedMessage = new String(rawData);
|
||||
assertTrue(decryptedMessage.equals(secretMessage));
|
||||
byte[] signedData = BouncyCastleCrypto.signData(rawData, certificate, privateKey);
|
||||
Boolean check = BouncyCastleCrypto.verifSignData(signedData);
|
||||
assertTrue(check);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package com.baeldung.caffeine;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.*;
|
||||
|
||||
public class CaffeineUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenCache_whenPopulate_thenValueStored() {
|
||||
Cache<String, DataObject> cache = Caffeine.newBuilder()
|
||||
.expireAfterWrite(1, TimeUnit.MINUTES)
|
||||
.maximumSize(100)
|
||||
.build();
|
||||
|
||||
String key = "A";
|
||||
DataObject dataObject = cache.getIfPresent(key);
|
||||
|
||||
assertNull(dataObject);
|
||||
|
||||
dataObject = cache.get(key, k -> DataObject.get("Data for A"));
|
||||
|
||||
assertNotNull(dataObject);
|
||||
assertEquals("Data for A", dataObject.getData());
|
||||
|
||||
cache.put(key, dataObject);
|
||||
dataObject = cache.getIfPresent(key);
|
||||
|
||||
assertNotNull(dataObject);
|
||||
|
||||
cache.invalidate(key);
|
||||
dataObject = cache.getIfPresent(key);
|
||||
|
||||
assertNull(dataObject);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoadingCache_whenGet_thenValuePopulated() {
|
||||
LoadingCache<String, DataObject> cache = Caffeine.newBuilder()
|
||||
.maximumSize(100)
|
||||
.expireAfterWrite(1, TimeUnit.MINUTES)
|
||||
.build(k -> DataObject.get("Data for " + k));
|
||||
String key = "A";
|
||||
|
||||
DataObject dataObject = cache.get(key);
|
||||
|
||||
assertNotNull(dataObject);
|
||||
assertEquals("Data for " + key, dataObject.getData());
|
||||
|
||||
Map<String, DataObject> dataObjectMap = cache.getAll(Arrays.asList("A", "B", "C"));
|
||||
|
||||
assertEquals(3, dataObjectMap.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAsyncLoadingCache_whenGet_thenValuePopulated() {
|
||||
|
||||
AsyncLoadingCache<String, DataObject> cache = Caffeine.newBuilder()
|
||||
.maximumSize(100)
|
||||
.expireAfterWrite(1, TimeUnit.MINUTES)
|
||||
.buildAsync(k -> DataObject.get("Data for " + k));
|
||||
String key = "A";
|
||||
|
||||
cache.get(key).thenAccept(dataObject -> {
|
||||
assertNotNull(dataObject);
|
||||
assertEquals("Data for " + key, dataObject.getData());
|
||||
});
|
||||
|
||||
cache.getAll(Arrays.asList("A", "B", "C"))
|
||||
.thenAccept(dataObjectMap -> assertEquals(3, dataObjectMap.size()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoadingCacheWithSmallSize_whenPut_thenSizeIsConstant() {
|
||||
LoadingCache<String, DataObject> cache = Caffeine.newBuilder()
|
||||
.maximumSize(1)
|
||||
.refreshAfterWrite(10, TimeUnit.MINUTES)
|
||||
.build(k -> DataObject.get("Data for " + k));
|
||||
|
||||
assertEquals(0, cache.estimatedSize());
|
||||
|
||||
cache.get("A");
|
||||
|
||||
assertEquals(1, cache.estimatedSize());
|
||||
|
||||
cache.get("B");
|
||||
cache.cleanUp();
|
||||
|
||||
assertEquals(1, cache.estimatedSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoadingCacheWithWeigher_whenPut_thenSizeIsConstant() {
|
||||
LoadingCache<String, DataObject> cache = Caffeine.newBuilder()
|
||||
.maximumWeight(10)
|
||||
.weigher((k,v) -> 5)
|
||||
.build(k -> DataObject.get("Data for " + k));
|
||||
|
||||
assertEquals(0, cache.estimatedSize());
|
||||
|
||||
cache.get("A");
|
||||
|
||||
assertEquals(1, cache.estimatedSize());
|
||||
|
||||
cache.get("B");
|
||||
|
||||
assertEquals(2, cache.estimatedSize());
|
||||
|
||||
cache.get("C");
|
||||
cache.cleanUp();
|
||||
|
||||
assertEquals(2, cache.estimatedSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTimeEvictionCache_whenTimeLeft_thenValueEvicted() {
|
||||
LoadingCache<String, DataObject> cache = Caffeine.newBuilder()
|
||||
.expireAfterAccess(5, TimeUnit.MINUTES)
|
||||
.build(k -> DataObject.get("Data for " + k));
|
||||
|
||||
cache = Caffeine.newBuilder()
|
||||
.expireAfterWrite(10, TimeUnit.SECONDS)
|
||||
.weakKeys()
|
||||
.weakValues()
|
||||
.build(k -> DataObject.get("Data for " + k));
|
||||
|
||||
cache = Caffeine.newBuilder()
|
||||
.expireAfterWrite(10, TimeUnit.SECONDS)
|
||||
.softValues()
|
||||
.build(k -> DataObject.get("Data for " + k));
|
||||
|
||||
cache = Caffeine.newBuilder().expireAfter(new Expiry<String, DataObject>() {
|
||||
@Override
|
||||
public long expireAfterCreate(@Nonnull String key, @Nonnull DataObject value, long currentTime) {
|
||||
return value.getData().length() * 1000;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long expireAfterUpdate(@Nonnull String key, @Nonnull DataObject value, long currentTime, long currentDuration) {
|
||||
return currentDuration;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long expireAfterRead(@Nonnull String key, @Nonnull DataObject value, long currentTime, long currentDuration) {
|
||||
return currentDuration;
|
||||
}
|
||||
}).build(k -> DataObject.get("Data for " + k));
|
||||
|
||||
cache = Caffeine.newBuilder()
|
||||
.refreshAfterWrite(1, TimeUnit.MINUTES)
|
||||
.build(k -> DataObject.get("Data for " + k));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCache_whenStatsEnabled_thenStatsRecorded() {
|
||||
LoadingCache<String, DataObject> cache = Caffeine.newBuilder()
|
||||
.maximumSize(100)
|
||||
.recordStats()
|
||||
.build(k -> DataObject.get("Data for " + k));
|
||||
cache.get("A");
|
||||
cache.get("A");
|
||||
|
||||
assertEquals(1, cache.stats().hitCount());
|
||||
assertEquals(1, cache.stats().missCount());
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,9 @@ package com.baeldung.commons.lang3;
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNotSame;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
@@ -20,6 +22,7 @@ import org.apache.commons.lang3.ArchUtils;
|
||||
import org.apache.commons.lang3.BooleanUtils;
|
||||
import org.apache.commons.lang3.SystemUtils;
|
||||
import org.apache.commons.lang3.arch.Processor;
|
||||
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
|
||||
import org.apache.commons.lang3.concurrent.ConcurrentException;
|
||||
import org.apache.commons.lang3.concurrent.ConcurrentRuntimeException;
|
||||
import org.apache.commons.lang3.concurrent.ConcurrentUtils;
|
||||
@@ -133,4 +136,14 @@ public class Lang3UtilsTest {
|
||||
assertEquals(sampleObjectOne, sampleObjectTwo);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildDefaults() {
|
||||
BasicThreadFactory.Builder builder = new BasicThreadFactory.Builder();
|
||||
BasicThreadFactory factory = builder.build();
|
||||
assertNull("No naming pattern set Yet", factory.getNamingPattern());
|
||||
BasicThreadFactory factory2 = builder.namingPattern("sampleNamingPattern").daemon(true).priority(Thread.MIN_PRIORITY).build();
|
||||
assertNotNull("Got a naming pattern", factory2.getNamingPattern());
|
||||
assertEquals("sampleNamingPattern", factory2.getNamingPattern());
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
package com.baeldung.crdt;
|
||||
|
||||
import com.netopyr.wurmloch.crdt.GCounter;
|
||||
import com.netopyr.wurmloch.crdt.GSet;
|
||||
import com.netopyr.wurmloch.crdt.LWWRegister;
|
||||
import com.netopyr.wurmloch.crdt.PNCounter;
|
||||
import com.netopyr.wurmloch.store.LocalCrdtStore;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class CRDTTest {
|
||||
|
||||
@Test
|
||||
public void givenGrowOnlySet_whenTwoReplicasDiverge_thenShouldMergeItWithoutAConflict() {
|
||||
//given
|
||||
final LocalCrdtStore crdtStore1 = new LocalCrdtStore();
|
||||
final LocalCrdtStore crdtStore2 = new LocalCrdtStore();
|
||||
crdtStore1.connect(crdtStore2);
|
||||
|
||||
final GSet<String> replica1 = crdtStore1.createGSet("ID_1");
|
||||
final GSet<String> replica2 = crdtStore2.<String>findGSet("ID_1").get();
|
||||
|
||||
//when
|
||||
replica1.add("apple");
|
||||
replica2.add("banana");
|
||||
|
||||
//then
|
||||
assertThat(replica1).contains("apple", "banana");
|
||||
assertThat(replica2).contains("apple", "banana");
|
||||
|
||||
//when
|
||||
crdtStore1.disconnect(crdtStore2);
|
||||
|
||||
replica1.add("strawberry");
|
||||
replica2.add("pear");
|
||||
|
||||
|
||||
assertThat(replica1).contains("apple", "banana", "strawberry");
|
||||
assertThat(replica2).contains("apple", "banana", "pear");
|
||||
|
||||
crdtStore1.connect(crdtStore2);
|
||||
|
||||
//then
|
||||
assertThat(replica1).contains("apple", "banana", "strawberry", "pear");
|
||||
assertThat(replica2).contains("apple", "banana", "strawberry", "pear");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIncrementOnlyCounter_whenTwoReplicasDiverge_thenShouldMergeIt() {
|
||||
//given
|
||||
final LocalCrdtStore crdtStore1 = new LocalCrdtStore();
|
||||
final LocalCrdtStore crdtStore2 = new LocalCrdtStore();
|
||||
crdtStore1.connect(crdtStore2);
|
||||
|
||||
final GCounter replica1 = crdtStore1.createGCounter("ID_1");
|
||||
final GCounter replica2 = crdtStore2.findGCounter("ID_1").get();
|
||||
|
||||
//when
|
||||
replica1.increment();
|
||||
replica2.increment(2L);
|
||||
|
||||
//then
|
||||
assertThat(replica1.get()).isEqualTo(3L);
|
||||
assertThat(replica2.get()).isEqualTo(3L);
|
||||
|
||||
//when
|
||||
crdtStore1.disconnect(crdtStore2);
|
||||
|
||||
replica1.increment(3L);
|
||||
replica2.increment(5L);
|
||||
|
||||
|
||||
assertThat(replica1.get()).isEqualTo(6L);
|
||||
assertThat(replica2.get()).isEqualTo(8L);
|
||||
|
||||
crdtStore1.connect(crdtStore2);
|
||||
|
||||
// then
|
||||
assertThat(replica1.get()).isEqualTo(11L);
|
||||
assertThat(replica2.get()).isEqualTo(11L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPNCounter_whenReplicasDiverge_thenShouldMergeWithoutAConflict() {
|
||||
// given
|
||||
final LocalCrdtStore crdtStore1 = new LocalCrdtStore();
|
||||
final LocalCrdtStore crdtStore2 = new LocalCrdtStore();
|
||||
crdtStore1.connect(crdtStore2);
|
||||
|
||||
final PNCounter replica1 = crdtStore1.createPNCounter("ID_1");
|
||||
final PNCounter replica2 = crdtStore2.findPNCounter("ID_1").get();
|
||||
|
||||
//when
|
||||
replica1.increment();
|
||||
replica2.decrement(2L);
|
||||
|
||||
//then
|
||||
assertThat(replica1.get()).isEqualTo(-1L);
|
||||
assertThat(replica2.get()).isEqualTo(-1L);
|
||||
|
||||
//when
|
||||
crdtStore1.disconnect(crdtStore2);
|
||||
|
||||
replica1.decrement(3L);
|
||||
replica2.increment(5L);
|
||||
|
||||
assertThat(replica1.get()).isEqualTo(-4L);
|
||||
assertThat(replica2.get()).isEqualTo(4L);
|
||||
|
||||
crdtStore1.connect(crdtStore2);
|
||||
|
||||
//then
|
||||
assertThat(replica1.get()).isEqualTo(1L);
|
||||
assertThat(replica2.get()).isEqualTo(1L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLastWriteWinsStrategy_whenReplicasDiverge_thenAfterMergeShouldKeepOnlyLastValue() {
|
||||
//given
|
||||
final LocalCrdtStore crdtStore1 = new LocalCrdtStore("N_1");
|
||||
final LocalCrdtStore crdtStore2 = new LocalCrdtStore("N_2");
|
||||
crdtStore1.connect(crdtStore2);
|
||||
|
||||
final LWWRegister<String> replica1 = crdtStore1.createLWWRegister("ID_1");
|
||||
final LWWRegister<String> replica2 = crdtStore2.<String>findLWWRegister("ID_1").get();
|
||||
|
||||
//when
|
||||
replica1.set("apple");
|
||||
replica2.set("banana");
|
||||
|
||||
// then
|
||||
assertThat(replica1.get()).isEqualTo("banana");
|
||||
assertThat(replica2.get()).isEqualTo("banana");
|
||||
|
||||
|
||||
// when
|
||||
crdtStore1.disconnect(crdtStore2);
|
||||
|
||||
replica1.set("strawberry");
|
||||
replica2.set("pear");
|
||||
|
||||
|
||||
assertThat(replica1.get()).isEqualTo("strawberry");
|
||||
assertThat(replica2.get()).isEqualTo("pear");
|
||||
|
||||
crdtStore1.connect(crdtStore2);
|
||||
|
||||
//then
|
||||
assertThat(replica1.get()).isEqualTo("pear");
|
||||
assertThat(replica2.get()).isEqualTo("pear");
|
||||
}
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
@@ -51,7 +51,6 @@ public class MemberStatusIntegrationTest {
|
||||
|
||||
/**
|
||||
* This test should fail, comment out <code>@Ignore</code> to see how failed test can be reflected in Serenity report. <br/>
|
||||
* Remember to add <code><testFailureIgnore>true</testFailureIgnore></code> under maven-surefire-plugin configuration.
|
||||
*/
|
||||
@Test
|
||||
@Ignore
|
||||
|
||||
Reference in New Issue
Block a user