Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Philippe 2018-07-23 22:21:30 -03:00
commit 5142d0f0a5
224 changed files with 8092 additions and 1221 deletions

9
.gitignore vendored
View File

@ -48,3 +48,12 @@ dependency-reduced-pom.xml
*.so *.so
*.dylib *.dylib
*.dll *.dll
xml/src/test/resources/example_dom4j_new.xml
xml/src/test/resources/example_dom4j_updated.xml
xml/src/test/resources/example_jaxb_new.xml
core-java-io/hard_link.txt
core-java-io/target_link.txt
core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF
ethereum/logs/
jmeter/src/main/resources/*-JMeter.csv

View File

@ -19,7 +19,7 @@ In additional to Spring, the following technologies are in focus: `core Java`, `
Building the project Building the project
==================== ====================
To do the full build, do: `mvn install -Dgib.enabled=false` To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
Working with the code in Eclipse Working with the code in Eclipse

88
apache-avro/pom.xml Normal file
View File

@ -0,0 +1,88 @@
<?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>
<groupId>com.baeldung</groupId>
<artifactId>apache-avro-tutorial</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<compiler-plugin.version>3.5</compiler-plugin.version>
<avro.version>1.8.2</avro.version>
<java.version>1.8</java.version>
<slf4j.version>1.7.25</slf4j.version>
</properties>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro</artifactId>
<version>${avro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro-compiler</artifactId>
<version>${avro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro-maven-plugin</artifactId>
<version>${avro.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.avro</groupId>
<artifactId>avro-maven-plugin</artifactId>
<version>${avro.version}</version>
<executions>
<execution>
<id>schemas</id>
<phase>generate-sources</phase>
<goals>
<goal>schema</goal>
<goal>protocol</goal>
<goal>idl-protocol</goal>
</goals>
<configuration>
<sourceDirectory>${project.basedir}/src/main/resources/</sourceDirectory>
<outputDirectory>${project.basedir}/src/main/java/</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,14 @@
package com.baeldung.avro.util;
import org.apache.avro.Schema;
import org.apache.avro.compiler.specific.SpecificCompiler;
import java.io.File;
import java.io.IOException;
public class AvroClassGenerator {
public void generateAvroClasses() throws IOException {
SpecificCompiler compiler = new SpecificCompiler(new Schema.Parser().parse(new File("src/main/resources/avroHttpRequest-schema.avsc")));
compiler.compileToDestination(new File("src/main/resources"), new File("src/main/java"));
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.avro.util;
import org.apache.avro.Schema;
import org.apache.avro.SchemaBuilder;
public class AvroSchemaBuilder {
public Schema createAvroHttpRequestSchema(){
Schema clientIdentifier = SchemaBuilder.record("ClientIdentifier").namespace("com.baeldung.avro.model")
.fields().requiredString("hostName").requiredString("ipAddress").endRecord();
Schema avroHttpRequest = SchemaBuilder.record("AvroHttpRequest").namespace("com.baeldung.avro.model").fields()
.requiredLong("requestTime")
.name("clientIdentifier").type(clientIdentifier).noDefault()
.name("employeeNames").type().array().items().stringType().arrayDefault(null)
.name("active").type().enumeration("Active").symbols("YES", "NO").noDefault()
.endRecord();
return avroHttpRequest;
}
}

View File

@ -0,0 +1,13 @@
/**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package com.baeldung.avro.util.model;
@SuppressWarnings("all")
@org.apache.avro.specific.AvroGenerated
public enum Active {
YES, NO ;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"enum\",\"name\":\"Active\",\"namespace\":\"com.baeldung.avro.model\",\"symbols\":[\"YES\",\"NO\"]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
}

View File

@ -0,0 +1,491 @@
/**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package com.baeldung.avro.util.model;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore;
@SuppressWarnings("all")
@org.apache.avro.specific.AvroGenerated
public class AvroHttpRequest extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = -8649010116827875312L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"AvroHttpRequest\",\"namespace\":\"com.baeldung.avro.model\",\"fields\":[{\"name\":\"requestTime\",\"type\":\"long\"},{\"name\":\"clientIdentifier\",\"type\":{\"type\":\"record\",\"name\":\"ClientIdentifier\",\"fields\":[{\"name\":\"hostName\",\"type\":\"string\"},{\"name\":\"ipAddress\",\"type\":\"string\"}]}},{\"name\":\"employeeNames\",\"type\":{\"type\":\"array\",\"items\":\"string\"},\"default\":null},{\"name\":\"active\",\"type\":{\"type\":\"enum\",\"name\":\"Active\",\"symbols\":[\"YES\",\"NO\"]}}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static SpecificData MODEL$ = new SpecificData();
private static final BinaryMessageEncoder<AvroHttpRequest> ENCODER =
new BinaryMessageEncoder<AvroHttpRequest>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<AvroHttpRequest> DECODER =
new BinaryMessageDecoder<AvroHttpRequest>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageDecoder instance used by this class.
*/
public static BinaryMessageDecoder<AvroHttpRequest> getDecoder() {
return DECODER;
}
/**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
* @param resolver a {@link SchemaStore} used to find schemas by fingerprint
*/
public static BinaryMessageDecoder<AvroHttpRequest> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<AvroHttpRequest>(MODEL$, SCHEMA$, resolver);
}
/** Serializes this AvroHttpRequest to a ByteBuffer. */
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/** Deserializes a AvroHttpRequest from a ByteBuffer. */
public static AvroHttpRequest fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
@Deprecated public long requestTime;
@Deprecated public ClientIdentifier clientIdentifier;
@Deprecated public java.util.List<java.lang.CharSequence> employeeNames;
@Deprecated public Active active;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public AvroHttpRequest() {}
/**
* All-args constructor.
* @param requestTime The new value for requestTime
* @param clientIdentifier The new value for clientIdentifier
* @param employeeNames The new value for employeeNames
* @param active The new value for active
*/
public AvroHttpRequest(java.lang.Long requestTime, ClientIdentifier clientIdentifier, java.util.List<java.lang.CharSequence> employeeNames, Active active) {
this.requestTime = requestTime;
this.clientIdentifier = clientIdentifier;
this.employeeNames = employeeNames;
this.active = active;
}
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return requestTime;
case 1: return clientIdentifier;
case 2: return employeeNames;
case 3: return active;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
}
// Used by DatumReader. Applications should not call.
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: requestTime = (java.lang.Long)value$; break;
case 1: clientIdentifier = (ClientIdentifier)value$; break;
case 2: employeeNames = (java.util.List<java.lang.CharSequence>)value$; break;
case 3: active = (Active)value$; break;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
}
/**
* Gets the value of the 'requestTime' field.
* @return The value of the 'requestTime' field.
*/
public java.lang.Long getRequestTime() {
return requestTime;
}
/**
* Sets the value of the 'requestTime' field.
* @param value the value to set.
*/
public void setRequestTime(java.lang.Long value) {
this.requestTime = value;
}
/**
* Gets the value of the 'clientIdentifier' field.
* @return The value of the 'clientIdentifier' field.
*/
public ClientIdentifier getClientIdentifier() {
return clientIdentifier;
}
/**
* Sets the value of the 'clientIdentifier' field.
* @param value the value to set.
*/
public void setClientIdentifier(ClientIdentifier value) {
this.clientIdentifier = value;
}
/**
* Gets the value of the 'employeeNames' field.
* @return The value of the 'employeeNames' field.
*/
public java.util.List<java.lang.CharSequence> getEmployeeNames() {
return employeeNames;
}
/**
* Sets the value of the 'employeeNames' field.
* @param value the value to set.
*/
public void setEmployeeNames(java.util.List<java.lang.CharSequence> value) {
this.employeeNames = value;
}
/**
* Gets the value of the 'active' field.
* @return The value of the 'active' field.
*/
public Active getActive() {
return active;
}
/**
* Sets the value of the 'active' field.
* @param value the value to set.
*/
public void setActive(Active value) {
this.active = value;
}
/**
* Creates a new AvroHttpRequest RecordBuilder.
* @return A new AvroHttpRequest RecordBuilder
*/
public static AvroHttpRequest.Builder newBuilder() {
return new AvroHttpRequest.Builder();
}
/**
* Creates a new AvroHttpRequest RecordBuilder by copying an existing Builder.
* @param other The existing builder to copy.
* @return A new AvroHttpRequest RecordBuilder
*/
public static AvroHttpRequest.Builder newBuilder(AvroHttpRequest.Builder other) {
return new AvroHttpRequest.Builder(other);
}
/**
* Creates a new AvroHttpRequest RecordBuilder by copying an existing AvroHttpRequest instance.
* @param other The existing instance to copy.
* @return A new AvroHttpRequest RecordBuilder
*/
public static AvroHttpRequest.Builder newBuilder(AvroHttpRequest other) {
return new AvroHttpRequest.Builder(other);
}
/**
* RecordBuilder for AvroHttpRequest instances.
*/
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<AvroHttpRequest>
implements org.apache.avro.data.RecordBuilder<AvroHttpRequest> {
private long requestTime;
private ClientIdentifier clientIdentifier;
private ClientIdentifier.Builder clientIdentifierBuilder;
private java.util.List<java.lang.CharSequence> employeeNames;
private Active active;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$);
}
/**
* Creates a Builder by copying an existing Builder.
* @param other The existing Builder to copy.
*/
private Builder(AvroHttpRequest.Builder other) {
super(other);
if (isValidValue(fields()[0], other.requestTime)) {
this.requestTime = data().deepCopy(fields()[0].schema(), other.requestTime);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.clientIdentifier)) {
this.clientIdentifier = data().deepCopy(fields()[1].schema(), other.clientIdentifier);
fieldSetFlags()[1] = true;
}
if (other.hasClientIdentifierBuilder()) {
this.clientIdentifierBuilder = ClientIdentifier.newBuilder(other.getClientIdentifierBuilder());
}
if (isValidValue(fields()[2], other.employeeNames)) {
this.employeeNames = data().deepCopy(fields()[2].schema(), other.employeeNames);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.active)) {
this.active = data().deepCopy(fields()[3].schema(), other.active);
fieldSetFlags()[3] = true;
}
}
/**
* Creates a Builder by copying an existing AvroHttpRequest instance
* @param other The existing instance to copy.
*/
private Builder(AvroHttpRequest other) {
super(SCHEMA$);
if (isValidValue(fields()[0], other.requestTime)) {
this.requestTime = data().deepCopy(fields()[0].schema(), other.requestTime);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.clientIdentifier)) {
this.clientIdentifier = data().deepCopy(fields()[1].schema(), other.clientIdentifier);
fieldSetFlags()[1] = true;
}
this.clientIdentifierBuilder = null;
if (isValidValue(fields()[2], other.employeeNames)) {
this.employeeNames = data().deepCopy(fields()[2].schema(), other.employeeNames);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.active)) {
this.active = data().deepCopy(fields()[3].schema(), other.active);
fieldSetFlags()[3] = true;
}
}
/**
* Gets the value of the 'requestTime' field.
* @return The value.
*/
public java.lang.Long getRequestTime() {
return requestTime;
}
/**
* Sets the value of the 'requestTime' field.
* @param value The value of 'requestTime'.
* @return This builder.
*/
public AvroHttpRequest.Builder setRequestTime(long value) {
validate(fields()[0], value);
this.requestTime = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'requestTime' field has been set.
* @return True if the 'requestTime' field has been set, false otherwise.
*/
public boolean hasRequestTime() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'requestTime' field.
* @return This builder.
*/
public AvroHttpRequest.Builder clearRequestTime() {
fieldSetFlags()[0] = false;
return this;
}
/**
* Gets the value of the 'clientIdentifier' field.
* @return The value.
*/
public ClientIdentifier getClientIdentifier() {
return clientIdentifier;
}
/**
* Sets the value of the 'clientIdentifier' field.
* @param value The value of 'clientIdentifier'.
* @return This builder.
*/
public AvroHttpRequest.Builder setClientIdentifier(ClientIdentifier value) {
validate(fields()[1], value);
this.clientIdentifierBuilder = null;
this.clientIdentifier = value;
fieldSetFlags()[1] = true;
return this;
}
/**
* Checks whether the 'clientIdentifier' field has been set.
* @return True if the 'clientIdentifier' field has been set, false otherwise.
*/
public boolean hasClientIdentifier() {
return fieldSetFlags()[1];
}
/**
* Gets the Builder instance for the 'clientIdentifier' field and creates one if it doesn't exist yet.
* @return This builder.
*/
public ClientIdentifier.Builder getClientIdentifierBuilder() {
if (clientIdentifierBuilder == null) {
if (hasClientIdentifier()) {
setClientIdentifierBuilder(ClientIdentifier.newBuilder(clientIdentifier));
} else {
setClientIdentifierBuilder(ClientIdentifier.newBuilder());
}
}
return clientIdentifierBuilder;
}
/**
* Sets the Builder instance for the 'clientIdentifier' field
* @param value The builder instance that must be set.
* @return This builder.
*/
public AvroHttpRequest.Builder setClientIdentifierBuilder(ClientIdentifier.Builder value) {
clearClientIdentifier();
clientIdentifierBuilder = value;
return this;
}
/**
* Checks whether the 'clientIdentifier' field has an active Builder instance
* @return True if the 'clientIdentifier' field has an active Builder instance
*/
public boolean hasClientIdentifierBuilder() {
return clientIdentifierBuilder != null;
}
/**
* Clears the value of the 'clientIdentifier' field.
* @return This builder.
*/
public AvroHttpRequest.Builder clearClientIdentifier() {
clientIdentifier = null;
clientIdentifierBuilder = null;
fieldSetFlags()[1] = false;
return this;
}
/**
* Gets the value of the 'employeeNames' field.
* @return The value.
*/
public java.util.List<java.lang.CharSequence> getEmployeeNames() {
return employeeNames;
}
/**
* Sets the value of the 'employeeNames' field.
* @param value The value of 'employeeNames'.
* @return This builder.
*/
public AvroHttpRequest.Builder setEmployeeNames(java.util.List<java.lang.CharSequence> value) {
validate(fields()[2], value);
this.employeeNames = value;
fieldSetFlags()[2] = true;
return this;
}
/**
* Checks whether the 'employeeNames' field has been set.
* @return True if the 'employeeNames' field has been set, false otherwise.
*/
public boolean hasEmployeeNames() {
return fieldSetFlags()[2];
}
/**
* Clears the value of the 'employeeNames' field.
* @return This builder.
*/
public AvroHttpRequest.Builder clearEmployeeNames() {
employeeNames = null;
fieldSetFlags()[2] = false;
return this;
}
/**
* Gets the value of the 'active' field.
* @return The value.
*/
public Active getActive() {
return active;
}
/**
* Sets the value of the 'active' field.
* @param value The value of 'active'.
* @return This builder.
*/
public AvroHttpRequest.Builder setActive(Active value) {
validate(fields()[3], value);
this.active = value;
fieldSetFlags()[3] = true;
return this;
}
/**
* Checks whether the 'active' field has been set.
* @return True if the 'active' field has been set, false otherwise.
*/
public boolean hasActive() {
return fieldSetFlags()[3];
}
/**
* Clears the value of the 'active' field.
* @return This builder.
*/
public AvroHttpRequest.Builder clearActive() {
active = null;
fieldSetFlags()[3] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public AvroHttpRequest build() {
try {
AvroHttpRequest record = new AvroHttpRequest();
record.requestTime = fieldSetFlags()[0] ? this.requestTime : (java.lang.Long) defaultValue(fields()[0]);
if (clientIdentifierBuilder != null) {
record.clientIdentifier = this.clientIdentifierBuilder.build();
} else {
record.clientIdentifier = fieldSetFlags()[1] ? this.clientIdentifier : (ClientIdentifier) defaultValue(fields()[1]);
}
record.employeeNames = fieldSetFlags()[2] ? this.employeeNames : (java.util.List<java.lang.CharSequence>) defaultValue(fields()[2]);
record.active = fieldSetFlags()[3] ? this.active : (Active) defaultValue(fields()[3]);
return record;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<AvroHttpRequest>
WRITER$ = (org.apache.avro.io.DatumWriter<AvroHttpRequest>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<AvroHttpRequest>
READER$ = (org.apache.avro.io.DatumReader<AvroHttpRequest>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
}

View File

@ -0,0 +1,308 @@
/**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package com.baeldung.avro.util.model;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore;
@SuppressWarnings("all")
@org.apache.avro.specific.AvroGenerated
public class ClientIdentifier extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = 8754570983127295424L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"ClientIdentifier\",\"namespace\":\"com.baeldung.avro.model\",\"fields\":[{\"name\":\"hostName\",\"type\":\"string\"},{\"name\":\"ipAddress\",\"type\":\"string\"}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static SpecificData MODEL$ = new SpecificData();
private static final BinaryMessageEncoder<ClientIdentifier> ENCODER =
new BinaryMessageEncoder<ClientIdentifier>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<ClientIdentifier> DECODER =
new BinaryMessageDecoder<ClientIdentifier>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageDecoder instance used by this class.
*/
public static BinaryMessageDecoder<ClientIdentifier> getDecoder() {
return DECODER;
}
/**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
* @param resolver a {@link SchemaStore} used to find schemas by fingerprint
*/
public static BinaryMessageDecoder<ClientIdentifier> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<ClientIdentifier>(MODEL$, SCHEMA$, resolver);
}
/** Serializes this ClientIdentifier to a ByteBuffer. */
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/** Deserializes a ClientIdentifier from a ByteBuffer. */
public static ClientIdentifier fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
@Deprecated public java.lang.CharSequence hostName;
@Deprecated public java.lang.CharSequence ipAddress;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public ClientIdentifier() {}
/**
* All-args constructor.
* @param hostName The new value for hostName
* @param ipAddress The new value for ipAddress
*/
public ClientIdentifier(java.lang.CharSequence hostName, java.lang.CharSequence ipAddress) {
this.hostName = hostName;
this.ipAddress = ipAddress;
}
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return hostName;
case 1: return ipAddress;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
}
// Used by DatumReader. Applications should not call.
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: hostName = (java.lang.CharSequence)value$; break;
case 1: ipAddress = (java.lang.CharSequence)value$; break;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
}
/**
* Gets the value of the 'hostName' field.
* @return The value of the 'hostName' field.
*/
public java.lang.CharSequence getHostName() {
return hostName;
}
/**
* Sets the value of the 'hostName' field.
* @param value the value to set.
*/
public void setHostName(java.lang.CharSequence value) {
this.hostName = value;
}
/**
* Gets the value of the 'ipAddress' field.
* @return The value of the 'ipAddress' field.
*/
public java.lang.CharSequence getIpAddress() {
return ipAddress;
}
/**
* Sets the value of the 'ipAddress' field.
* @param value the value to set.
*/
public void setIpAddress(java.lang.CharSequence value) {
this.ipAddress = value;
}
/**
* Creates a new ClientIdentifier RecordBuilder.
* @return A new ClientIdentifier RecordBuilder
*/
public static ClientIdentifier.Builder newBuilder() {
return new ClientIdentifier.Builder();
}
/**
* Creates a new ClientIdentifier RecordBuilder by copying an existing Builder.
* @param other The existing builder to copy.
* @return A new ClientIdentifier RecordBuilder
*/
public static ClientIdentifier.Builder newBuilder(ClientIdentifier.Builder other) {
return new ClientIdentifier.Builder(other);
}
/**
* Creates a new ClientIdentifier RecordBuilder by copying an existing ClientIdentifier instance.
* @param other The existing instance to copy.
* @return A new ClientIdentifier RecordBuilder
*/
public static ClientIdentifier.Builder newBuilder(ClientIdentifier other) {
return new ClientIdentifier.Builder(other);
}
/**
* RecordBuilder for ClientIdentifier instances.
*/
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<ClientIdentifier>
implements org.apache.avro.data.RecordBuilder<ClientIdentifier> {
private java.lang.CharSequence hostName;
private java.lang.CharSequence ipAddress;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$);
}
/**
* Creates a Builder by copying an existing Builder.
* @param other The existing Builder to copy.
*/
private Builder(ClientIdentifier.Builder other) {
super(other);
if (isValidValue(fields()[0], other.hostName)) {
this.hostName = data().deepCopy(fields()[0].schema(), other.hostName);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.ipAddress)) {
this.ipAddress = data().deepCopy(fields()[1].schema(), other.ipAddress);
fieldSetFlags()[1] = true;
}
}
/**
* Creates a Builder by copying an existing ClientIdentifier instance
* @param other The existing instance to copy.
*/
private Builder(ClientIdentifier other) {
super(SCHEMA$);
if (isValidValue(fields()[0], other.hostName)) {
this.hostName = data().deepCopy(fields()[0].schema(), other.hostName);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.ipAddress)) {
this.ipAddress = data().deepCopy(fields()[1].schema(), other.ipAddress);
fieldSetFlags()[1] = true;
}
}
/**
* Gets the value of the 'hostName' field.
* @return The value.
*/
public java.lang.CharSequence getHostName() {
return hostName;
}
/**
* Sets the value of the 'hostName' field.
* @param value The value of 'hostName'.
* @return This builder.
*/
public ClientIdentifier.Builder setHostName(java.lang.CharSequence value) {
validate(fields()[0], value);
this.hostName = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'hostName' field has been set.
* @return True if the 'hostName' field has been set, false otherwise.
*/
public boolean hasHostName() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'hostName' field.
* @return This builder.
*/
public ClientIdentifier.Builder clearHostName() {
hostName = null;
fieldSetFlags()[0] = false;
return this;
}
/**
* Gets the value of the 'ipAddress' field.
* @return The value.
*/
public java.lang.CharSequence getIpAddress() {
return ipAddress;
}
/**
* Sets the value of the 'ipAddress' field.
* @param value The value of 'ipAddress'.
* @return This builder.
*/
public ClientIdentifier.Builder setIpAddress(java.lang.CharSequence value) {
validate(fields()[1], value);
this.ipAddress = value;
fieldSetFlags()[1] = true;
return this;
}
/**
* Checks whether the 'ipAddress' field has been set.
* @return True if the 'ipAddress' field has been set, false otherwise.
*/
public boolean hasIpAddress() {
return fieldSetFlags()[1];
}
/**
* Clears the value of the 'ipAddress' field.
* @return This builder.
*/
public ClientIdentifier.Builder clearIpAddress() {
ipAddress = null;
fieldSetFlags()[1] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public ClientIdentifier build() {
try {
ClientIdentifier record = new ClientIdentifier();
record.hostName = fieldSetFlags()[0] ? this.hostName : (java.lang.CharSequence) defaultValue(fields()[0]);
record.ipAddress = fieldSetFlags()[1] ? this.ipAddress : (java.lang.CharSequence) defaultValue(fields()[1]);
return record;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<ClientIdentifier>
WRITER$ = (org.apache.avro.io.DatumWriter<ClientIdentifier>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<ClientIdentifier>
READER$ = (org.apache.avro.io.DatumReader<ClientIdentifier>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.avro.util.serealization;
import com.baeldung.avro.util.model.AvroHttpRequest;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.specific.SpecificDatumReader;
import java.io.IOException;
public class AvroDeSerealizer {
public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data){
DatumReader<AvroHttpRequest> reader = new SpecificDatumReader<>(AvroHttpRequest.class);
Decoder decoder = null;
try {
decoder = DecoderFactory.get().jsonDecoder(AvroHttpRequest.getClassSchema(), new String(data));
return reader.read(null, decoder);
} catch (IOException e) {
return null;
}
}
public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data){
DatumReader<AvroHttpRequest> employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class);
Decoder decoder = DecoderFactory.get().binaryDecoder(data, null);
try {
return employeeReader.read(null, decoder);
} catch (IOException e) {
return null;
}
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.avro.util.serealization;
import com.baeldung.avro.util.model.AvroHttpRequest;
import org.apache.avro.io.*;
import org.apache.avro.specific.SpecificDatumWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class AvroSerealizer {
public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request){
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
byte[] data = new byte[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Encoder jsonEncoder = null;
try {
jsonEncoder = EncoderFactory.get().jsonEncoder(AvroHttpRequest.getClassSchema(), stream);
writer.write(request, jsonEncoder);
jsonEncoder.flush();
data = stream.toByteArray();
} catch (IOException e) {
data =null;
}
return data;
}
public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request){
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
byte[] data = new byte[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Encoder jsonEncoder = EncoderFactory.get().binaryEncoder(stream,null);
try {
writer.write(request, jsonEncoder);
jsonEncoder.flush();
data = stream.toByteArray();
} catch (IOException e) {
data = null;
}
return data;
}
}

View File

@ -0,0 +1,47 @@
{
"type":"record",
"name":"AvroHttpRequest",
"namespace":"com.baeldung.avro.model",
"fields":[
{
"name":"requestTime",
"type":"long"
},
{
"name":"clientIdentifier",
"type":{
"type":"record",
"name":"ClientIdentifier",
"fields":[
{
"name":"hostName",
"type":"string"
},
{
"name":"ipAddress",
"type":"string"
}
]
}
},
{
"name":"employeeNames",
"type":{
"type":"array",
"items":"string"
},
"default":null
},
{
"name":"active",
"type":{
"type":"enum",
"name":"Active",
"symbols":[
"YES",
"NO"
]
}
}
]
}

View File

@ -0,0 +1,75 @@
package com.baeldung.avro.util.serealization;
import com.baeldung.avro.util.model.Active;
import com.baeldung.avro.util.model.AvroHttpRequest;
import com.baeldung.avro.util.model.ClientIdentifier;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static org.junit.Assert.*;
public class AvroSerealizerDeSerealizerTest {
AvroSerealizer serealizer;
AvroDeSerealizer deSerealizer;
AvroHttpRequest request;
@Before
public void setUp() throws Exception {
serealizer = new AvroSerealizer();
deSerealizer = new AvroDeSerealizer();
ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder().
setHostName("localhost").setIpAddress("255.255.255.0").build();
List<CharSequence> employees = new ArrayList();
employees.add("James");
employees.add("Alice");
employees.add("David");
employees.add("Han");
request = AvroHttpRequest.newBuilder().setRequestTime(01l)
.setActive(Active.YES).setClientIdentifier(clientIdentifier)
.setEmployeeNames(employees).build();
}
@After
public void tearDown() throws Exception {
}
@Test
public void WhenSerialized_UsingJSONEncoder_ObjectGetsSerialized(){
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
assertTrue(Objects.nonNull(data));
assertTrue(data.length > 0);
}
@Test
public void WhenSerialized_UsingBinaryEncoder_ObjectGetsSerialized(){
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
assertTrue(Objects.nonNull(data));
assertTrue(data.length > 0);
}
@Test
public void WhenDeserialize_UsingJSONDecoder_ActualAndExpectedObjectsAreEqual(){
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data);
assertEquals(actualRequest,request);
assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
}
@Test
public void WhenDeserialize_UsingBinaryecoder_ActualAndExpectedObjectsAreEqual(){
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data);
assertEquals(actualRequest,request);
assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
}
}

View File

@ -99,6 +99,16 @@
<artifactId>joda-time</artifactId> <artifactId>joda-time</artifactId>
<version>${joda.version}</version> <version>${joda.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${asspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${asspectj.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -170,6 +180,7 @@
<joda.version>2.10</joda.version> <joda.version>2.10</joda.version>
<!-- testing --> <!-- testing -->
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>
<asspectj.version>1.8.9</asspectj.version>
<avaitility.version>1.7.0</avaitility.version> <avaitility.version>1.7.0</avaitility.version>
<jmh-core.version>1.19</jmh-core.version> <jmh-core.version>1.19</jmh-core.version>
<jmh-generator.version>1.19</jmh-generator.version> <jmh-generator.version>1.19</jmh-generator.version>

View File

@ -0,0 +1,9 @@
package com.baeldung.aspect;
public aspect ChangeCallsToCurrentTimeInMillisMethod {
long around():
call(public static native long java.lang.System.currentTimeMillis())
&& within(user.code.base.pckg.*) {
return 0;
}
}

View File

@ -1,6 +1,7 @@
package com.baeldung.util; package com.baeldung.util;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.time.Clock; import java.time.Clock;
import java.time.Instant; import java.time.Instant;
@ -9,6 +10,8 @@ import java.time.LocalTime;
import java.time.ZoneId; import java.time.ZoneId;
import java.time.temporal.ChronoField; import java.time.temporal.ChronoField;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.junit.Test; import org.junit.Test;
public class CurrentDateTimeUnitTest { public class CurrentDateTimeUnitTest {
@ -39,5 +42,4 @@ public class CurrentDateTimeUnitTest {
assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond()); assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
} }
} }

View File

@ -0,0 +1,27 @@
package com.baeldung.convertlisttomap;
public class Animal {
private int id;
private String name;
public Animal(int id, String name) {
this.id = id;
this.setName(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;
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.convertlisttomap;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.MapUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ConvertListToMapService {
public Map<Integer, Animal> convertListBeforeJava8(List<Animal> list) {
Map<Integer, Animal> map = new HashMap<>();
for (Animal animal : list) {
map.put(animal.getId(), animal);
}
return map;
}
public Map<Integer, Animal> convertListAfterJava8(List<Animal> list) {
Map<Integer, Animal> map = list.stream().collect(Collectors.toMap(Animal::getId, animal -> animal));
return map;
}
public Map<Integer, Animal> convertListWithGuava(List<Animal> list) {
Map<Integer, Animal> map = Maps.uniqueIndex(list, Animal::getId);
return map;
}
public Map<Integer, Animal> convertListWithApacheCommons(List<Animal> list) {
Map<Integer, Animal> map = new HashMap<>();
MapUtils.populateMap(map, list, Animal::getId);
return map;
}
}

View File

@ -0,0 +1,68 @@
package com.baeldung.convertlisttomap;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
public class ConvertListToMapServiceUnitTest {
List<Animal> list;
private ConvertListToMapService convertListService;
@Before
public void init() {
this.convertListService = new ConvertListToMapService();
this.list = new ArrayList<>();
Animal cat = new Animal(1, "Cat");
list.add(cat);
Animal dog = new Animal(2, "Dog");
list.add(dog);
Animal pig = new Animal(3, "Pig");
list.add(pig);
Animal cow = new Animal(4, "Cow");
list.add(cow);
Animal goat = new Animal(5, "Goat");
list.add(goat);
}
@Test
public void givenAList_whenConvertBeforeJava8_thenReturnMapWithTheSameElements() {
Map<Integer, Animal> map = convertListService.convertListBeforeJava8(list);
assertThat(map.values(), containsInAnyOrder(list.toArray()));
}
@Test
public void givenAList_whenConvertAfterJava8_thenReturnMapWithTheSameElements() {
Map<Integer, Animal> map = convertListService.convertListAfterJava8(list);
assertThat(map.values(), containsInAnyOrder(list.toArray()));
}
@Test
public void givenAList_whenConvertWithGuava_thenReturnMapWithTheSameElements() {
Map<Integer, Animal> map = convertListService.convertListWithGuava(list);
assertThat(map.values(), containsInAnyOrder(list.toArray()));
}
@Test
public void givenAList_whenConvertWithApacheCommons_thenReturnMapWithTheSameElements() {
Map<Integer, Animal> map = convertListService.convertListWithApacheCommons(list);
assertThat(map.values(), containsInAnyOrder(list.toArray()));
}
}

View File

@ -0,0 +1,68 @@
package com.baeldung.convertlisttomap;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
public class ConvertListWithDiplicatedIdToMapServiceUnitTest {
List<Animal> duplicatedIdList;
private ConvertListToMapService convertListService = new ConvertListToMapService();
@Before
public void init() {
this.duplicatedIdList = new ArrayList<>();
Animal cat = new Animal(1, "Cat");
duplicatedIdList.add(cat);
Animal dog = new Animal(2, "Dog");
duplicatedIdList.add(dog);
Animal pig = new Animal(3, "Pig");
duplicatedIdList.add(pig);
Animal cow = new Animal(4, "Cow");
duplicatedIdList.add(cow);
Animal goat = new Animal(4, "Goat");
duplicatedIdList.add(goat);
}
@Test
public void givenADupIdList_whenConvertBeforeJava8_thenReturnMapWithRewrittenElement() {
Map<Integer, Animal> map = convertListService.convertListBeforeJava8(duplicatedIdList);
assertThat(map.values(), hasSize(4));
assertThat(map.values(), hasItem(duplicatedIdList.get(4)));
}
@Test
public void givenADupIdList_whenConvertWithApacheCommons_thenReturnMapWithRewrittenElement() {
Map<Integer, Animal> map = convertListService.convertListWithApacheCommons(duplicatedIdList);
assertThat(map.values(), hasSize(4));
assertThat(map.values(), hasItem(duplicatedIdList.get(4)));
}
@Test(expected = IllegalStateException.class)
public void givenADupIdList_whenConvertAfterJava8_thenException() {
convertListService.convertListAfterJava8(duplicatedIdList);
}
@Test(expected = IllegalArgumentException.class)
public void givenADupIdList_whenConvertWithGuava_thenException() {
convertListService.convertListWithGuava(duplicatedIdList);
}
}

View File

@ -50,22 +50,9 @@ public class HashSetInitalizingUnitTest {
@Test @Test
public void whenUsingJava8_usingCollectOnStream_thenCorrectSize() { public void whenUsingJava8_usingCollectOnStream_thenCorrectSize() {
Set<String> set = Stream.of("a", "b", "c").collect(Collectors.toSet()); Set<String> set = Stream.of("a", "b", "c").collect(Collectors.toCollection(HashSet::new));
assertEquals(3, set.size()); assertEquals(3, set.size());
} }
@Test
public void whenUsingJava8_fromStringArray_thenCorrectSize() {
String[] stringArray = {"a","b","c"};
Set<String> set = Arrays.stream(stringArray).collect(Collectors.toCollection(HashSet::new));
assertEquals(3, set.size());
}
// Requires Java9 - uncomment if you are using Java 9 or higher
/*@Test
public void whenUsingJava9_usingCollectOnStream_thenCorrectSize() {
Set set = Set.of("a", "b", "c");
assertEquals(3, set.size());
}*/
@Test @Test
public void whenUsingGoogleGuava_createMutableSet_thenCorrectSize() { public void whenUsingGoogleGuava_createMutableSet_thenCorrectSize() {
@ -78,4 +65,6 @@ public class HashSetInitalizingUnitTest {
Set<String> set = ImmutableSet.of("a", "b", "c"); Set<String> set = ImmutableSet.of("a", "b", "c");
assertEquals(3, set.size()); assertEquals(3, set.size());
} }
} }

View File

@ -1,5 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>core-java</artifactId> <artifactId>core-java</artifactId>
@ -73,9 +73,10 @@
<dependency> <dependency>
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId> <artifactId>assertj-core</artifactId>
<version>${assertj.version}</version> <version>${assertj-core.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-codec</groupId> <groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId> <artifactId>commons-codec</artifactId>
@ -146,6 +147,45 @@
<artifactId>icu4j</artifactId> <artifactId>icu4j</artifactId>
<version>${icu4j.version}</version> <version>${icu4j.version}</version>
</dependency> </dependency>
<!-- Mime Type Resolution Libraries -->
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>${tika.version}</version>
</dependency>
<dependency>
<groupId>net.sf.jmimemagic</groupId>
<artifactId>jmimemagic</artifactId>
<version>${jmime-magic.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${commons-dbcp2.version}</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>${HikariCP.version}</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
<!-- instrumentation -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>${javaassist.version}</version>
</dependency>
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.8.0</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -348,6 +388,7 @@
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId> <artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
<executions> <executions>
<execution> <execution>
<id>run-benchmarks</id> <id>run-benchmarks</id>
@ -372,9 +413,115 @@
</plugins> </plugins>
</build> </build>
</profile> </profile>
<!-- java instrumentation profiles to build jars -->
<profile>
<id>buildAgentLoader</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>agentLoader</classifier>
<classesDirectory>target/classes</classesDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
<includes>
<include>com/baeldung/instrumentation/application/AgentLoader.class</include>
<include>com/baeldung/instrumentation/application/Launcher.class</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>buildApplication</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>application</classifier>
<classesDirectory>target/classes</classesDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
<includes>
<include>com/baeldung/instrumentation/application/MyAtm.class</include>
<include>com/baeldung/instrumentation/application/MyAtmApplication.class</include>
<include>com/baeldung/instrumentation/application/Launcher.class</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>buildAgent</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>agent</classifier>
<classesDirectory>target/classes</classesDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
<includes>
<include>com/baeldung/instrumentation/agent/AtmTransformer.class</include>
<include>com/baeldung/instrumentation/agent/MyInstrumentationAgent.class</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles> </profiles>
<properties> <properties>
<!-- marshalling --> <!-- marshalling -->
<jackson.version>2.8.5</jackson.version> <jackson.version>2.8.5</jackson.version>
<gson.version>2.8.2</gson.version> <gson.version>2.8.2</gson.version>
@ -395,16 +542,23 @@
<vavr.version>0.9.0</vavr.version> <vavr.version>0.9.0</vavr.version>
<!-- testing --> <!-- testing -->
<assertj.version>3.6.1</assertj.version> <assertj-core.version>3.10.0</assertj-core.version>
<!-- JDBC pooling frameworks -->
<commons-dbcp2.version>2.4.0</commons-dbcp2.version>
<HikariCP.version>3.2.0</HikariCP.version>
<c3p0.version>0.9.5.2</c3p0.version>
<!-- maven plugins --> <!-- maven plugins -->
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version> <maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version> <springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
<springframework.boot.spring-boot-starter.version>1.5.8.RELEASE</springframework.boot.spring-boot-starter.version> <springframework.boot.spring-boot-starter.version>1.5.8.RELEASE</springframework.boot.spring-boot-starter.version>
<javamoney.moneta.version>1.1</javamoney.moneta.version> <javamoney.moneta.version>1.1</javamoney.moneta.version>
<h2database.version>1.4.197</h2database.version> <h2database.version>1.4.197</h2database.version>
<esapi.version>2.1.0.1</esapi.version> <esapi.version>2.1.0.1</esapi.version>
<jmh-core.version>1.19</jmh-core.version> <jmh-core.version>1.19</jmh-core.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version> <jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version> <maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<javax.mail.version>1.5.0-b01</javax.mail.version> <javax.mail.version>1.5.0-b01</javax.mail.version>
@ -412,7 +566,13 @@
<onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version> <onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version>
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version> <maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
<spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version> <spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version>
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
<icu4j.version>61.1</icu4j.version> <icu4j.version>61.1</icu4j.version>
<!-- Mime Type Libraries -->
<tika.version>1.18</tika.version>
<jmime-magic.version>0.1.5</jmime-magic.version>
<!-- instrumentation -->
<javaassist.version>3.21.0-GA</javaassist.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,85 @@
package com.baeldung.connectionpool.connectionpools;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class BasicConnectionPool implements ConnectionPool {
private final String url;
private final String user;
private final String password;
private final List<Connection> connectionPool;
private final List<Connection> usedConnections = new ArrayList<>();
private static final int INITIAL_POOL_SIZE = 10;
private final int MAX_POOL_SIZE = 20;
public static BasicConnectionPool create(String url, String user, String password) throws SQLException {
List<Connection> pool = new ArrayList<>(INITIAL_POOL_SIZE);
for (int i = 0; i < INITIAL_POOL_SIZE; i++) {
pool.add(createConnection(url, user, password));
}
return new BasicConnectionPool(url, user, password, pool);
}
private BasicConnectionPool(String url, String user, String password, List<Connection> connectionPool) {
this.url = url;
this.user = user;
this.password = password;
this.connectionPool = connectionPool;
}
@Override
public Connection getConnection() throws SQLException {
if (connectionPool.isEmpty()) {
if (usedConnections.size() < MAX_POOL_SIZE) {
connectionPool.add(createConnection(url, user, password));
} else {
throw new RuntimeException("Maximum pool size reached, no available connections!");
}
}
Connection connection = connectionPool.remove(connectionPool.size() - 1);
usedConnections.add(connection);
return connection;
}
@Override
public boolean releaseConnection(Connection connection) {
connectionPool.add(connection);
return usedConnections.remove(connection);
}
private static Connection createConnection(String url, String user, String password) throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public int getSize() {
return connectionPool.size() + usedConnections.size();
}
@Override
public String getUrl() {
return url;
}
@Override
public String getUser() {
return user;
}
@Override
public String getPassword() {
return password;
}
public void shutdown() throws SQLException {
usedConnections.forEach(this::releaseConnection);
for (Connection c : connectionPool) {
c.close();
}
connectionPool.clear();
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.connectionpool.connectionpools;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
public class C3poDataSource {
private static final ComboPooledDataSource cpds = new ComboPooledDataSource();
static {
try {
cpds.setDriverClass("org.h2.Driver");
cpds.setJdbcUrl("jdbc:h2:mem:test");
cpds.setUser("user");
cpds.setPassword("password");
} catch (PropertyVetoException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return cpds.getConnection();
}
private C3poDataSource(){}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.connectionpool.connectionpools;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public interface ConnectionPool {
Connection getConnection() throws SQLException;
boolean releaseConnection(Connection connection);
String getUrl();
String getUser();
String getPassword();
}

View File

@ -0,0 +1,25 @@
package com.baeldung.connectionpool.connectionpools;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbcp2.BasicDataSource;
public class DBCPDataSource {
private static final BasicDataSource ds = new BasicDataSource();
static {
ds.setUrl("jdbc:h2:mem:test");
ds.setUsername("user");
ds.setPassword("password");
ds.setMinIdle(5);
ds.setMaxIdle(10);
ds.setMaxOpenPreparedStatements(100);
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
private DBCPDataSource(){}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.connectionpool.connectionpools;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class HikariCPDataSource {
private static final HikariConfig config = new HikariConfig();
private static final HikariDataSource ds;
static {
config.setJdbcUrl("jdbc:h2:mem:test");
config.setUsername("user");
config.setPassword("password");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
ds = new HikariDataSource(config);
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
private HikariCPDataSource(){}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.instrumentation.agent;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
public class AtmTransformer implements ClassFileTransformer {
private static Logger LOGGER = LoggerFactory.getLogger(AtmTransformer.class);
private static final String WITHDRAW_MONEY_METHOD = "withdrawMoney";
/** The internal form class name of the class to transform */
private String targetClassName;
/** The class loader of the class we want to transform */
private ClassLoader targetClassLoader;
public AtmTransformer(String targetClassName, ClassLoader targetClassLoader) {
this.targetClassName = targetClassName;
this.targetClassLoader = targetClassLoader;
}
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
byte[] byteCode = classfileBuffer;
String finalTargetClassName = this.targetClassName.replaceAll("\\.", "/"); //replace . with /
if (!className.equals(finalTargetClassName)) {
return byteCode;
}
if (className.equals(finalTargetClassName) && loader.equals(targetClassLoader)) {
LOGGER.info("[Agent] Transforming class MyAtm");
try {
ClassPool cp = ClassPool.getDefault();
CtClass cc = cp.get(targetClassName);
CtMethod m = cc.getDeclaredMethod(WITHDRAW_MONEY_METHOD);
m.addLocalVariable("startTime", CtClass.longType);
m.insertBefore("startTime = System.currentTimeMillis();");
StringBuilder endBlock = new StringBuilder();
m.addLocalVariable("endTime", CtClass.longType);
m.addLocalVariable("opTime", CtClass.longType);
endBlock.append("endTime = System.currentTimeMillis();");
endBlock.append("opTime = (endTime-startTime)/1000;");
endBlock.append("LOGGER.info(\"[Application] Withdrawal operation completed in:\" + opTime + \" seconds!\");");
m.insertAfter(endBlock.toString());
byteCode = cc.toBytecode();
cc.detach();
} catch (NotFoundException | CannotCompileException | IOException e) {
LOGGER.error("Exception", e);
}
}
return byteCode;
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.instrumentation.agent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.instrument.Instrumentation;
public class MyInstrumentationAgent {
private static Logger LOGGER = LoggerFactory.getLogger(MyInstrumentationAgent.class);
public static void premain(String agentArgs, Instrumentation inst) {
LOGGER.info("[Agent] In premain method");
String className = "com.baeldung.instrumentation.application.MyAtm";
transformClass(className,inst);
}
public static void agentmain(String agentArgs, Instrumentation inst) {
LOGGER.info("[Agent] In agentmain method");
String className = "com.baeldung.instrumentation.application.MyAtm";
transformClass(className,inst);
}
private static void transformClass(String className, Instrumentation instrumentation) {
Class<?> targetCls = null;
ClassLoader targetClassLoader = null;
// see if we can get the class using forName
try {
targetCls = Class.forName(className);
targetClassLoader = targetCls.getClassLoader();
transform(targetCls, targetClassLoader, instrumentation);
return;
} catch (Exception ex) {
LOGGER.error("Class [{}] not found with Class.forName");
}
// otherwise iterate all loaded classes and find what we want
for(Class<?> clazz: instrumentation.getAllLoadedClasses()) {
if(clazz.getName().equals(className)) {
targetCls = clazz;
targetClassLoader = targetCls.getClassLoader();
transform(targetCls, targetClassLoader, instrumentation);
return;
}
}
throw new RuntimeException("Failed to find class [" + className + "]");
}
private static void transform(Class<?> clazz, ClassLoader classLoader, Instrumentation instrumentation) {
AtmTransformer dt = new AtmTransformer(clazz.getName(), classLoader);
instrumentation.addTransformer(dt, true);
try {
instrumentation.retransformClasses(clazz);
} catch (Exception ex) {
throw new RuntimeException("Transform failed for class: [" + clazz.getName() + "]", ex);
}
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.instrumentation.application;
import com.sun.tools.attach.VirtualMachine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Optional;
/**
* Created by adi on 6/10/18.
*/
public class AgentLoader {
private static Logger LOGGER = LoggerFactory.getLogger(AgentLoader.class);
public static void run(String[] args) {
String agentFilePath = "/home/adi/Desktop/agent-1.0.0-jar-with-dependencies.jar";
String applicationName = "MyAtmApplication";
//iterate all jvms and get the first one that matches our application name
Optional<String> jvmProcessOpt = Optional.ofNullable(VirtualMachine.list()
.stream()
.filter(jvm -> {
LOGGER.info("jvm:{}", jvm.displayName());
return jvm.displayName().contains(applicationName);
})
.findFirst().get().id());
if(!jvmProcessOpt.isPresent()) {
LOGGER.error("Target Application not found");
return;
}
File agentFile = new File(agentFilePath);
try {
String jvmPid = jvmProcessOpt.get();
LOGGER.info("Attaching to target JVM with PID: " + jvmPid);
VirtualMachine jvm = VirtualMachine.attach(jvmPid);
jvm.loadAgent(agentFile.getAbsolutePath());
jvm.detach();
LOGGER.info("Attached to target JVM and loaded Java agent successfully");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.instrumentation.application;
/**
* Created by adi on 6/14/18.
*/
public class Launcher {
public static void main(String[] args) throws Exception {
if(args[0].equals("StartMyAtmApplication")) {
new MyAtmApplication().run(args);
} else if(args[0].equals("LoadAgent")) {
new AgentLoader().run(args);
}
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.instrumentation.application;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by adi on 6/11/18.
*/
public class MyAtm {
private static Logger LOGGER = LoggerFactory.getLogger(MyAtm.class);
private static final int account = 10;
public static void withdrawMoney(int amount) throws InterruptedException {
Thread.sleep(2000l); //processing going on here
LOGGER.info("[Application] Successful Withdrawal of [{}] units!", amount);
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.instrumentation.application;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyAtmApplication {
private static Logger LOGGER = LoggerFactory.getLogger(MyAtmApplication.class);
public static void run(String[] args) throws Exception {
LOGGER.info("[Application] Starting ATM application");
MyAtm.withdrawMoney(Integer.parseInt(args[2]));
Thread.sleep(Long.valueOf(args[1]));
MyAtm.withdrawMoney(Integer.parseInt(args[3]));
}
}

View File

@ -0,0 +1,5 @@
Agent-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent
Can-Redefine-Classes: true
Can-Retransform-Classes: true
Premain-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent
Main-Class: com.baeldung.instrumentation.application.Launcher

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

View File

@ -0,0 +1,69 @@
package com.baeldung.connectionpool;
import com.baeldung.connectionpool.connectionpools.BasicConnectionPool;
import com.baeldung.connectionpool.connectionpools.ConnectionPool;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.BeforeClass;
import org.junit.Test;
public class BasicConnectionPoolUnitTest {
private static ConnectionPool connectionPool;
@BeforeClass
public static void setUpBasicConnectionPoolInstance() throws SQLException {
connectionPool = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password");
}
@Test
public void givenBasicConnectionPoolInstance_whenCalledgetConnection_thenCorrect() throws Exception {
assertTrue(connectionPool.getConnection().isValid(1));
}
@Test
public void givenBasicConnectionPoolInstance_whenCalledreleaseConnection_thenCorrect() throws Exception {
Connection connection = connectionPool.getConnection();
assertThat(connectionPool.releaseConnection(connection)).isTrue();
}
@Test
public void givenBasicConnectionPoolInstance_whenCalledgetUrl_thenCorrect() {
assertThat(connectionPool.getUrl()).isEqualTo("jdbc:h2:mem:test");
}
@Test
public void givenBasicConnectionPoolInstance_whenCalledgetUser_thenCorrect() {
assertThat(connectionPool.getUser()).isEqualTo("user");
}
@Test
public void givenBasicConnectionPoolInstance_whenCalledgetPassword_thenCorrect() {
assertThat(connectionPool.getPassword()).isEqualTo("password");
}
@Test(expected = RuntimeException.class)
public void givenBasicConnectionPoolInstance_whenAskedForMoreThanMax_thenError() throws Exception {
// this test needs to be independent so it doesn't share the same connection pool as other tests
ConnectionPool cp = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password");
final int MAX_POOL_SIZE = 20;
for (int i = 0; i < MAX_POOL_SIZE + 1; i++) {
cp.getConnection();
}
fail();
}
@Test
public void givenBasicConnectionPoolInstance_whenSutdown_thenEmpty() throws Exception {
ConnectionPool cp = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password");
assertThat(((BasicConnectionPool)cp).getSize()).isEqualTo(10);
((BasicConnectionPool) cp).shutdown();
assertThat(((BasicConnectionPool)cp).getSize()).isEqualTo(0);
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.connectionpool;
import com.baeldung.connectionpool.connectionpools.C3poDataSource;
import java.sql.SQLException;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class C3poDataSourceUnitTest {
@Test
public void givenC3poDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException {
assertTrue(C3poDataSource.getConnection().isValid(1));
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.connectionpool;
import com.baeldung.connectionpool.connectionpools.DBCPDataSource;
import java.sql.SQLException;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class DBCPDataSourceUnitTest {
@Test
public void givenDBCPDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException {
assertTrue(DBCPDataSource.getConnection().isValid(1));
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.connectionpool;
import com.baeldung.connectionpool.connectionpools.HikariCPDataSource;
import java.sql.SQLException;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class HikariCPDataSourceUnitTest {
@Test
public void givenHikariDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException {
assertTrue(HikariCPDataSource.getConnection().isValid(1));
}
}

View File

@ -0,0 +1,131 @@
package com.baeldung.java.mimetype;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.net.FileNameMap;
import java.net.MalformedURLException;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.activation.MimetypesFileTypeMap;
import org.apache.tika.Tika;
import org.junit.Test;
import net.sf.jmimemagic.Magic;
import net.sf.jmimemagic.MagicException;
import net.sf.jmimemagic.MagicMatch;
import net.sf.jmimemagic.MagicMatchNotFoundException;
import net.sf.jmimemagic.MagicParseException;
/**
* Test class demonstrating various strategies to resolve MIME type of a file.
* @author tritty
*
*/
public class MimeTypeUnitTest {
/**
* Expected Ouput.
*/
public static final String PNG_EXT = "image/png";
/**
* The location of the file.
*/
public static final String FILE_LOC = "src/test/resources/product.png";
/**
* Test method, demonstrating usage in Java 7.
*
* @throws IOException
*/
@Test
public void whenUsingJava7_thenSuccess() throws IOException {
final Path path = new File(FILE_LOC).toPath();
final String mimeType = Files.probeContentType(path);
assertEquals(mimeType, PNG_EXT);
}
/**
* Test method demonstrating the usage of URLConnection to resolve MIME type.
*
* @throws MalformedURLException
* @throws IOException
*/
@Test
public void whenUsingGetContentType_thenSuccess() throws MalformedURLException, IOException {
final File file = new File(FILE_LOC);
final URLConnection connection = file.toURL()
.openConnection();
final String mimeType = connection.getContentType();
assertEquals(mimeType, PNG_EXT);
}
/**
* Test method demonstrating the usage of URLConnection to resolve MIME type.
*
*/
@Test
public void whenUsingGuessContentTypeFromName_thenSuccess() {
final File file = new File(FILE_LOC);
final String mimeType = URLConnection.guessContentTypeFromName(file.getName());
assertEquals(mimeType, PNG_EXT);
}
/**
* Test method demonstrating the usage of FileNameMap from URLConnection
* to resolve MIME type of a file.
*
*/
@Test
public void whenUsingGetFileNameMap_thenSuccess() {
final File file = new File(FILE_LOC);
final FileNameMap fileNameMap = URLConnection.getFileNameMap();
final String mimeType = fileNameMap.getContentTypeFor(file.getName());
assertEquals(mimeType, PNG_EXT);
}
/**
* Test method demonstrating the usage of MimeTypesFileTypeMap for resolution of
* MIME type.
*
*/
@Test
public void whenUsingMimeTypesFileTypeMap_thenSuccess() {
final File file = new File(FILE_LOC);
final MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
final String mimeType = fileTypeMap.getContentType(file.getName());
assertEquals(mimeType, PNG_EXT);
}
/**
* Test method demonstrating usage of jMimeMagic.
*
* @throws MagicParseException
* @throws MagicMatchNotFoundException
* @throws MagicException
*/
@Test
public void whenUsingJmimeMagic_thenSuccess() throws MagicParseException, MagicMatchNotFoundException, MagicException {
final File file = new File(FILE_LOC);
final Magic magic = new Magic();
final MagicMatch match = magic.getMagicMatch(file, false);
assertEquals(match.getMimeType(), PNG_EXT);
}
/**
* Test method demonstrating usage of Apache Tika.
*
* @throws IOException
*/
@Test
public void whenUsingTika_thenSuccess() throws IOException {
final File file = new File(FILE_LOC);
final Tika tika = new Tika();
final String mimeType = tika.detect(file);
assertEquals(mimeType, PNG_EXT);
}
}

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

View File

@ -60,7 +60,6 @@
<groupId>org.jetbrains.kotlin</groupId> <groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId> <artifactId>kotlin-reflect</artifactId>
<version>${kotlin-reflect.version}</version> <version>${kotlin-reflect.version}</version>
<scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.jetbrains.kotlinx</groupId> <groupId>org.jetbrains.kotlinx</groupId>
@ -224,10 +223,11 @@
</build> </build>
<properties> <properties>
<kotlin-maven-plugin.version>1.2.41</kotlin-maven-plugin.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<kotlin-test-junit.version>1.2.41</kotlin-test-junit.version> <kotlin-maven-plugin.version>1.2.51</kotlin-maven-plugin.version>
<kotlin-stdlib.version>1.2.41</kotlin-stdlib.version> <kotlin-test-junit.version>1.2.51</kotlin-test-junit.version>
<kotlin-reflect.version>1.2.41</kotlin-reflect.version> <kotlin-stdlib.version>1.2.51</kotlin-stdlib.version>
<kotlin-reflect.version>1.2.51</kotlin-reflect.version>
<kotlinx.version>0.22.5</kotlinx.version> <kotlinx.version>0.22.5</kotlinx.version>
<ktor.io.version>0.9.2</ktor.io.version> <ktor.io.version>0.9.2</ktor.io.version>
<mockito-kotlin.version>1.5.0</mockito-kotlin.version> <mockito-kotlin.version>1.5.0</mockito-kotlin.version>

View File

@ -0,0 +1,30 @@
package com.baeldung.kotlin.logging
import org.slf4j.Logger
open class LoggerAsExtensionOnAny {
val logger = logger()
fun log(s: String) {
logger().info(s)
logger.info(s)
}
}
class ExtensionSubclass : LoggerAsExtensionOnAny()
fun <T : Any> T.logger(): Logger = getLogger(getClassForLogging(javaClass))
fun main(args: Array<String>) {
LoggerAsExtensionOnAny().log("test")
ExtensionSubclass().log("sub")
"foo".logger().info("foo")
1.logger().info("uh-oh!")
SomeOtherClass().logger()
}
class SomeOtherClass {
fun logger(): String {
return "foo"
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.kotlin.logging
import org.slf4j.Logger
import org.slf4j.LoggerFactory
interface Logging
inline fun <reified T : Logging> T.logger(): Logger =
//Wrong logger name!
//LoggerFactory.getLogger(javaClass.name + " w/interface")
LoggerFactory.getLogger(getClassForLogging(T::class.java).name + " w/interface")
open class LoggerAsExtensionOnMarkerInterface : Logging {
companion object : Logging {
val logger = logger()
}
fun log(s: String) {
logger().info(s)
logger.info(s)
}
}
class MarkerExtensionSubclass : LoggerAsExtensionOnMarkerInterface()
fun main(args: Array<String>) {
LoggerAsExtensionOnMarkerInterface().log("test")
MarkerExtensionSubclass().log("sub")
"foo".logger().info("foo")
}

View File

@ -0,0 +1,17 @@
package com.baeldung.kotlin.logging
open class LoggerAsProperty {
private val logger = getLogger(javaClass)
fun log(s: String) {
logger.info(s)
}
}
class PropertySubclass : LoggerAsProperty()
fun main(args: Array<String>) {
LoggerAsProperty().log("test")
PropertySubclass().log("sub")
}

View File

@ -0,0 +1,47 @@
package com.baeldung.kotlin.logging
import org.slf4j.Logger
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
open class LoggerAsPropertyDelegate {
private val lazyLogger by lazyLogger()
protected val logger by LoggerDelegate()
private val logger2 = logger
companion object {
private val lazyLoggerComp by lazyLogger()
private val loggerComp by LoggerDelegate()
}
open fun log(s: String) {
logger.info(s)
logger2.info(s)
lazyLogger.info(s)
loggerComp.info(s)
lazyLoggerComp.info(s)
}
}
class DelegateSubclass : LoggerAsPropertyDelegate() {
override fun log(s: String) {
logger.info("-- in sub")
super.log(s)
}
}
fun lazyLogger(forClass: Class<*>): Lazy<Logger> =
lazy { getLogger(getClassForLogging(forClass)) }
fun <T : Any> T.lazyLogger(): Lazy<Logger> = lazyLogger(javaClass)
fun main(args: Array<String>) {
LoggerAsPropertyDelegate().log("test")
DelegateSubclass().log("sub")
}
class LoggerDelegate<in R : Any> : ReadOnlyProperty<R, Logger> {
override fun getValue(thisRef: R, property: KProperty<*>) =
getLogger(getClassForLogging(thisRef.javaClass))
}

View File

@ -0,0 +1,44 @@
package com.baeldung.kotlin.logging
open class LoggerInCompanionObject {
companion object {
private val loggerWithExplicitClass = getLogger(LoggerInCompanionObject::class.java)
@Suppress("JAVA_CLASS_ON_COMPANION")
private val loggerWithWrongClass = getLogger(javaClass)
@Suppress("JAVA_CLASS_ON_COMPANION")
private val logger = getLogger(javaClass.enclosingClass)
}
fun log(s: String) {
loggerWithExplicitClass.info(s)
loggerWithWrongClass.info(s)
logger.info(s)
}
class Inner {
companion object {
private val loggerWithExplicitClass = getLogger(Inner::class.java)
@Suppress("JAVA_CLASS_ON_COMPANION")
@JvmStatic
private val loggerWithWrongClass = getLogger(javaClass)
@Suppress("JAVA_CLASS_ON_COMPANION")
@JvmStatic
private val logger = getLogger(javaClass.enclosingClass)
}
fun log(s: String) {
loggerWithExplicitClass.info(s)
loggerWithWrongClass.info(s)
logger.info(s)
}
}
}
class CompanionSubclass : LoggerInCompanionObject()
fun main(args: Array<String>) {
LoggerInCompanionObject().log("test")
LoggerInCompanionObject.Inner().log("test")
CompanionSubclass().log("sub")
}

View File

@ -0,0 +1,13 @@
package com.baeldung.kotlin.logging
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import kotlin.reflect.full.companionObject
fun getLogger(forClass: Class<*>): Logger = LoggerFactory.getLogger(forClass)
fun <T : Any> getClassForLogging(javaClass: Class<T>): Class<*> {
return javaClass.enclosingClass?.takeIf {
it.kotlin.companionObject?.java == javaClass
} ?: javaClass
}

View File

@ -1,61 +1,62 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<modelVersion>4.0.0</modelVersion> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<groupId>com.baeldung</groupId> <modelVersion>4.0.0</modelVersion>
<artifactId>geotools</artifactId> <artifactId>geotools</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>geotools</name> <name>geotools</name>
<url>http://maven.apache.org</url> <url>http://maven.apache.org</url>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId> <artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.0-SNAPSHOT</version>
</parent> </parent>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.geotools</groupId> <groupId>org.geotools</groupId>
<artifactId>gt-shapefile</artifactId> <artifactId>gt-shapefile</artifactId>
<version>${geotools-shapefile.version}</version> <version>${geotools-shapefile.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.geotools</groupId> <groupId>org.geotools</groupId>
<artifactId>gt-epsg-hsql</artifactId> <artifactId>gt-epsg-hsql</artifactId>
<version>${geotools.version}</version> <version>${geotools.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.geotools</groupId> <groupId>org.geotools</groupId>
<artifactId>gt-swing</artifactId> <artifactId>gt-swing</artifactId>
<version>${geotools-swing.version}</version> <version>${geotools-swing.version}</version>
</dependency> </dependency>
</dependencies> </dependencies>
<repositories> <repositories>
<repository> <repository>
<id>maven2-repository.dev.java.net</id> <id>maven2-repository.dev.java.net</id>
<name>Java.net repository</name> <name>Java.net repository</name>
<url>http://download.java.net/maven/2</url> <url>http://download.java.net/maven/2</url>
</repository> </repository>
<repository> <repository>
<id>osgeo</id> <id>osgeo</id>
<name>Open Source Geospatial Foundation Repository</name> <name>Open Source Geospatial Foundation Repository</name>
<url>http://download.osgeo.org/webdav/geotools/</url> <url>http://download.osgeo.org/webdav/geotools/</url>
</repository> </repository>
<repository> <repository>
<snapshots> <snapshots>
<enabled>true</enabled> <enabled>true</enabled>
</snapshots> </snapshots>
<id>opengeo</id> <id>opengeo</id>
<name>OpenGeo Maven Repository</name> <name>OpenGeo Maven Repository</name>
<url>http://repo.opengeo.org</url> <url>http://repo.opengeo.org</url>
</repository> </repository>
</repositories> </repositories>
<properties>
<geotools.version>15.2</geotools.version>
<geotools-swing.version>15.2</geotools-swing.version>
<geotools-shapefile.version>15.2</geotools-shapefile.version>
</properties>
<properties>
<geotools.version>15.2</geotools.version>
<geotools-swing.version>15.2</geotools-swing.version>
<geotools-shapefile.version>15.2</geotools-shapefile.version>
</properties>
</project> </project>

View File

@ -5,8 +5,6 @@
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>hibernate5</artifactId> <artifactId>hibernate5</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>hibernate5</name>
<url>http://maven.apache.org</url>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
@ -59,9 +57,6 @@
</build> </build>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Maven plugins -->
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
<hibernate.version>5.3.2.Final</hibernate.version> <hibernate.version>5.3.2.Final</hibernate.version>
<mysql.version>6.0.6</mysql.version> <mysql.version>6.0.6</mysql.version>
<mariaDB4j.version>2.2.3</mariaDB4j.version> <mariaDB4j.version>2.2.3</mariaDB4j.version>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern> %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -347,7 +347,7 @@
</plugins> </plugins>
</pluginManagement> </pluginManagement>
<plugins> <plugins>
<plugin> <!-- <plugin>
<groupId>com.github.ekryd.sortpom</groupId> <groupId>com.github.ekryd.sortpom</groupId>
<artifactId>sortpom-maven-plugin</artifactId> <artifactId>sortpom-maven-plugin</artifactId>
<version>${sortpom-maven-plugin.version}</version> <version>${sortpom-maven-plugin.version}</version>
@ -367,7 +367,7 @@
<keepBlankLines>true</keepBlankLines> <keepBlankLines>true</keepBlankLines>
<expandEmptyElements>false</expandEmptyElements> <expandEmptyElements>false</expandEmptyElements>
</configuration> </configuration>
</plugin> </plugin> -->
<plugin> <plugin>
<groupId>com.spotify</groupId> <groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId> <artifactId>docker-maven-plugin</artifactId>

View File

@ -3,28 +3,9 @@
<configuration scan="true"> <configuration scan="true">
<include resource="org/springframework/boot/logging/logback/base.xml"/> <include resource="org/springframework/boot/logging/logback/base.xml"/>
<!-- The FILE and ASYNC appenders are here as examples for a production configuration --> <logger name="com.baeldung" level="INFO"/>
<!--
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>90</maxHistory>
</rollingPolicy>
<encoder>
<charset>utf-8</charset>
<Pattern>%d %-5level [%thread] %logger{0}: %msg%n</Pattern>
</encoder>
</appender>
<appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender"> <logger name="io.github.jhipster" level="INFO"/>
<queueSize>512</queueSize>
<appender-ref ref="FILE"/>
</appender>
-->
<logger name="com.baeldung" level="#logback.loglevel#"/>
<logger name="io.github.jhipster" level="DEBUG"/>
<logger name="javax.activation" level="WARN"/> <logger name="javax.activation" level="WARN"/>
<logger name="javax.mail" level="WARN"/> <logger name="javax.mail" level="WARN"/>

View File

@ -0,0 +1,88 @@
<?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>
<parent>
<groupId>com.baeldung.jnosql</groupId>
<artifactId>jnosql</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>jnosql-artemis</artifactId>
<packaging>war</packaging>
<properties>
<liberty-maven-plugin.version>2.4.2</liberty-maven-plugin.version>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
<build>
<finalName>${artifactId}</finalName>
<plugins>
<plugin>
<groupId>net.wasdev.wlp.maven.plugins</groupId>
<artifactId>liberty-maven-plugin</artifactId>
<version>${liberty-maven-plugin.version}</version>
<configuration>
<assemblyArtifact>
<groupId>io.openliberty</groupId>
<artifactId>openliberty-webProfile8</artifactId>
<version>RELEASE</version>
<type>zip</type>
</assemblyArtifact>
<installAppPackages>project</installAppPackages>
<looseApplication>true</looseApplication>
<configFile>src/main/liberty/config/server.xml</configFile>
</configuration>
<executions>
<execution>
<id>install-server</id>
<phase>prepare-package</phase>
<goals>
<goal>install-server</goal>
<goal>create-server</goal>
<goal>install-feature</goal>
</goals>
</execution>
<execution>
<id>install-apps</id>
<phase>package</phase>
<goals>
<goal>install-apps</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>8.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jnosql.artemis</groupId>
<artifactId>artemis-configuration</artifactId>
<version>${jnosql.version}</version>
</dependency>
<dependency>
<groupId>org.jnosql.artemis</groupId>
<artifactId>artemis-document</artifactId>
<version>${jnosql.version}</version>
</dependency>
<dependency>
<groupId>org.jnosql.diana</groupId>
<artifactId>mongodb-driver</artifactId>
<version>${jnosql.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,10 @@
package com.baeldung.jnosql.artemis;
import javax.enterprise.context.Initialized;
import javax.enterprise.event.Observes;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("")
public class AppConfig extends Application {
}

View File

@ -0,0 +1,52 @@
package com.baeldung.jnosql.artemis;
import de.flapdoodle.embed.mongo.MongodExecutable;
import de.flapdoodle.embed.mongo.MongodProcess;
import de.flapdoodle.embed.mongo.MongodStarter;
import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
import de.flapdoodle.embed.mongo.config.Net;
import de.flapdoodle.embed.mongo.distribution.Version;
import de.flapdoodle.embed.process.runtime.Network;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Destroyed;
import javax.enterprise.context.Initialized;
import javax.enterprise.event.Observes;
import java.io.IOException;
@ApplicationScoped
public class EmbeddedMongoDBSetup {
private static final String MONGODB_HOST = "localhost";
private static final int MONGODB_PORT = 27019;
private static final MongodStarter starter = MongodStarter.getDefaultInstance();
private static MongodExecutable _mongodExe;
private static MongodProcess _mongod;
public void init(@Observes @Initialized(ApplicationScoped.class) Object init) {
try {
System.out.println("Starting Embedded MongoDB");
initdb();
System.out.println("Embedded MongoDB started");
} catch (IOException e) {
System.out.println("Embedded MongoDB starting error !!");
e.printStackTrace();
}
}
private void initdb() throws IOException {
_mongodExe = starter.prepare(new MongodConfigBuilder()
.version(Version.Main.DEVELOPMENT)
.net(new Net(MONGODB_HOST, MONGODB_PORT, Network.localhostIsIPv6()))
.build());
_mongod = _mongodExe.start();
}
public void destroy(@Observes @Destroyed(ApplicationScoped.class) Object init) {
System.out.println("Stopping Embedded MongoDB");
_mongod.stop();
_mongodExe.stop();
System.out.println("Embedded MongoDB stopped !");
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.jnosql.artemis;
import org.jnosql.artemis.ConfigurationUnit;
import org.jnosql.diana.api.document.DocumentCollectionManager;
import org.jnosql.diana.api.document.DocumentCollectionManagerFactory;
import org.jnosql.diana.mongodb.document.MongoDBDocumentCollectionManager;
import org.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
@ApplicationScoped
public class EntityManagerProducer {
private static final String DATABASE = "todos";
@Inject
@ConfigurationUnit(name = "document")
private DocumentCollectionManagerFactory<MongoDBDocumentCollectionManager> managerFactory;
@Produces
public DocumentCollectionManager getEntityManager() {
return managerFactory.get(DATABASE);
}
public void close(@Disposes DocumentCollectionManager entityManager) {
entityManager.close();
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.jnosql.artemis;
import com.baeldung.jnosql.artemis.qualifier.Repo;
import org.jnosql.artemis.Database;
import org.jnosql.artemis.DatabaseType;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.List;
import java.util.Optional;
@ApplicationScoped
@Repo
public class RepositoryTodoManager implements TodoManager {
@Inject
@Database(DatabaseType.DOCUMENT)
private TodoRepository repository;
@Override
public Todo add(Todo todo) {
return repository.save(todo);
}
@Override
public Todo get(String id) {
Optional<Todo> todo = repository.findById(id);
return todo.get();
}
@Override
public List<Todo> getAll() {
return repository.findAll();
}
@Override
public void delete(String id) {
repository.deleteById(id);
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.jnosql.artemis;
import com.baeldung.jnosql.artemis.qualifier.Template;
import org.jnosql.artemis.document.DocumentTemplate;
import org.jnosql.diana.api.document.DocumentQuery;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.List;
import java.util.Optional;
import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.select;
@ApplicationScoped
@Template
public class TemplateTodoManager implements TodoManager {
@Inject
private DocumentTemplate documentTemplate;
@Override
public Todo add(Todo todo) {
return documentTemplate.insert(todo);
}
@Override
public Todo get(String id) {
Optional<Todo> todo = documentTemplate.find(Todo.class, id);
return todo.get();
}
@Override
public List<Todo> getAll() {
DocumentQuery query = select().from("Todo").build();
return documentTemplate.select(query);
}
@Override
public void delete(String id) {
documentTemplate.delete(Todo.class, id);
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.jnosql.artemis;
import org.jnosql.artemis.Column;
import org.jnosql.artemis.Entity;
import org.jnosql.artemis.Id;
import java.io.Serializable;
@Entity
public class Todo implements Serializable {
@Id("id")
public String id;
@Column
public String name;
@Column
public String description;
public Todo() {
}
public Todo(String id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
}
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;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.jnosql.artemis;
import java.util.List;
public interface TodoManager {
Todo add(Todo todo);
Todo get(String id);
List<Todo> getAll();
void delete(String id);
}

View File

@ -0,0 +1,10 @@
package com.baeldung.jnosql.artemis;
import org.jnosql.artemis.Repository;
import java.util.List;
public interface TodoRepository extends Repository<Todo, String> {
List<Todo> findByName(String name);
List<Todo> findAll();
}

View File

@ -0,0 +1,48 @@
package com.baeldung.jnosql.artemis;
import com.baeldung.jnosql.artemis.qualifier.Repo;
import com.baeldung.jnosql.artemis.qualifier.Template;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
@Path("todos")
public class TodoResource {
/*
Use eiher @Template or @Repo
*/
@Inject
@Template
//@Repo
private TodoManager todoManager;
@GET
@Path("")
@Produces(MediaType.APPLICATION_JSON)
public Response all() {
return Response.ok(todoManager.getAll()).build();
}
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response get(@PathParam("id") String id) {
Todo todo = todoManager.get(id);
return Response.ok(todo).build();
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response add(Todo todo) {
Todo savedTodo = todoManager.add(todo);
System.out.println(savedTodo.id);
return Response.created(
UriBuilder.fromResource(this.getClass()).path(String.valueOf(savedTodo.id)).build())
.build();
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.jnosql.artemis.qualifier;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
@Qualifier
public @interface Repo {
}

View File

@ -0,0 +1,13 @@
package com.baeldung.jnosql.artemis.qualifier;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
@Qualifier
public @interface Template {
}

View File

@ -0,0 +1,6 @@
<server description="OpenLiberty Server">
<featureManager>
<feature>webProfile-8.0</feature>
</featureManager>
<httpEndpoint httpPort="9080" httpsPort="9443" id="defaultHttpEndpoint" host="*"/>
</server>

View File

@ -0,0 +1,6 @@
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
bean-discovery-mode="all">
</beans>

View File

@ -0,0 +1,10 @@
[
{
"description": "The mongodb document configuration",
"name": "document",
"provider": "org.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration",
"settings": {
"mongodb-server-host-1":"localhost:27019"
}
}
]

View File

@ -0,0 +1,10 @@
[
{
"description": "The mongodb document configuration",
"name": "document",
"provider": "org.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration",
"settings": {
"mongodb-server-host-1":"localhost:27019"
}
}
]

View File

@ -0,0 +1,93 @@
<?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>
<parent>
<groupId>com.baeldung.jnosql</groupId>
<artifactId>jnosql</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>jnosql-diana</artifactId>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<executions>
<execution>
<id>document</id>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>com.baeldung.jnosql.diana.document.DocumentApp</mainClass>
</configuration>
</execution>
<execution>
<id>column</id>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>com.baeldung.jnosql.diana.column.ColumnFamilyApp</mainClass>
</configuration>
</execution>
<execution>
<id>key</id>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>com.baeldung.jnosql.diana.key.KeyValueApp</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!--NoSQL Document oriented-->
<dependency>
<groupId>org.jnosql.diana</groupId>
<artifactId>diana-document</artifactId>
<version>0.0.5</version>
</dependency>
<dependency>
<groupId>org.jnosql.diana</groupId>
<artifactId>mongodb-driver</artifactId>
<version>0.0.5</version>
</dependency>
<!--NoSQL Column oriented-->
<dependency>
<groupId>org.jnosql.diana</groupId>
<artifactId>diana-column</artifactId>
<version>0.0.5</version>
</dependency>
<dependency>
<groupId>org.jnosql.diana</groupId>
<artifactId>cassandra-driver</artifactId>
<version>0.0.5</version>
</dependency>
<!--NoSQL Key Value oriented-->
<dependency>
<groupId>org.jnosql.diana</groupId>
<artifactId>diana-key-value</artifactId>
<version>0.0.5</version>
</dependency>
<dependency>
<groupId>org.jnosql.diana</groupId>
<artifactId>hazelcast-driver</artifactId>
<version>0.0.5</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,32 @@
package com.baeldung.jnosql.diana.column;
import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
import org.jnosql.diana.api.column.*;
import org.jnosql.diana.cassandra.column.CassandraConfiguration;
public class ColumnFamilyApp {
private static final String KEY_SPACE = "myKeySpace";
private static final String COLUMN_FAMILY = "books";
public static void main(String... args) throws Exception {
EmbeddedCassandraServerHelper.startEmbeddedCassandra();
ColumnConfiguration configuration = new CassandraConfiguration();
try(ColumnFamilyManagerFactory entityManagerFactory = configuration.get()) {
ColumnFamilyManager entityManager = entityManagerFactory.get(KEY_SPACE);
ColumnEntity columnEntity = ColumnEntity.of(COLUMN_FAMILY);
Column key = Columns.of("id", 10L);
Column name = Columns.of("name", "JNoSQL in Acion");
columnEntity.add(key);
columnEntity.add(name);
ColumnEntity saved = entityManager.insert(columnEntity);
System.out.println(saved);
}
EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
EmbeddedCassandraServerHelper.stopEmbeddedCassandra();
}
}

View File

@ -0,0 +1,67 @@
package com.baeldung.jnosql.diana.document;
import org.jnosql.diana.api.Settings;
import org.jnosql.diana.api.document.*;
import org.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.delete;
import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.select;
public class DocumentApp {
private static final String DB_NAME = "my-db";
private static final String DOCUMENT_COLLECTION = "books";
public static final String KEY_NAME = "_id";
DocumentConfiguration configuration = new MongoDBDocumentConfiguration();
public static void main(String... args) throws Exception {
MongoDbInit.startMongoDb();
DocumentApp app = new DocumentApp();
app.process();
MongoDbInit.stopMongoDb();
}
public void process() {
Map<String, Object> map = new HashMap<>();
map.put("mongodb-server-host-1", "localhost:27017");
try (DocumentCollectionManagerFactory managerFactory = configuration.get(Settings.of(map));
DocumentCollectionManager manager = managerFactory.get(DB_NAME);) {
DocumentEntity documentEntity = DocumentEntity.of(DOCUMENT_COLLECTION);
documentEntity.add(Document.of(KEY_NAME, "100"));
documentEntity.add(Document.of("name", "JNoSQL in Action"));
documentEntity.add(Document.of("pages", 620));
//CREATE
DocumentEntity saved = manager.insert(documentEntity);
//READ
DocumentQuery query = select().from(DOCUMENT_COLLECTION).where(KEY_NAME).eq("100").build();
List<DocumentEntity> entities = manager.select(query);
System.out.println(entities.get(0));
//UPDATE
saved.add(Document.of("author", "baeldung"));
DocumentEntity updated = manager.update(saved);
System.out.println(updated);
//DELETE
DocumentDeleteQuery deleteQuery = delete().from(DOCUMENT_COLLECTION).where(KEY_NAME).eq("100").build();
manager.delete(deleteQuery);
List<DocumentEntity> documentEntityList = manager.select(select().from(DOCUMENT_COLLECTION).build());
System.out.println(documentEntityList);
}
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.jnosql.diana.document;
import de.flapdoodle.embed.mongo.MongodExecutable;
import de.flapdoodle.embed.mongo.MongodProcess;
import de.flapdoodle.embed.mongo.MongodStarter;
import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
import de.flapdoodle.embed.mongo.config.Net;
import de.flapdoodle.embed.mongo.distribution.Version;
import de.flapdoodle.embed.process.runtime.Network;
import java.io.IOException;
public abstract class MongoDbInit {
private static final MongodStarter starter = MongodStarter.getDefaultInstance();
private static MongodExecutable _mongodExe;
private static MongodProcess _mongod;
public static void startMongoDb() throws IOException {
_mongodExe = starter.prepare(new MongodConfigBuilder()
.version(Version.Main.DEVELOPMENT)
.net(new Net("localhost", 27017, Network.localhostIsIPv6()))
.build());
_mongod = _mongodExe.start();
}
public static void stopMongoDb(){
_mongod.stop();
_mongodExe.stop();
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.jnosql.diana.key;
import java.io.Serializable;
public class Book implements Serializable {
private String isbn;
private String name;
private String author;
private int pages;
public Book() {
}
public Book(String isbn, String name, String author, int pages) {
this.isbn = isbn;
this.name = name;
this.author = author;
this.pages = pages;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
@Override
public String toString() {
return "Book{" +
"isbn='" + isbn + '\'' +
", name='" + name + '\'' +
", author='" + author + '\'' +
", pages=" + pages +
'}';
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.jnosql.diana.key;
import com.hazelcast.core.Hazelcast;
import org.jnosql.diana.api.Value;
import org.jnosql.diana.api.key.BucketManager;
import org.jnosql.diana.api.key.BucketManagerFactory;
import org.jnosql.diana.api.key.KeyValueConfiguration;
import org.jnosql.diana.api.key.KeyValueEntity;
import org.jnosql.diana.hazelcast.key.HazelcastKeyValueConfiguration;
import java.util.Optional;
public class KeyValueApp {
private static final String BUCKET_NAME = "books";
public static void main(String... args) throws Exception {
KeyValueConfiguration configuration = new HazelcastKeyValueConfiguration();
try (BucketManagerFactory managerFactory = configuration.get()) {
BucketManager manager = managerFactory.getBucketManager(BUCKET_NAME);
Book book = new Book("12345", "JNoSQL in Action", "baeldung", 420);
KeyValueEntity keyValueEntity = KeyValueEntity.of(book.getIsbn(), book);
manager.put(keyValueEntity);
Optional<Value> optionalValue = manager.get("12345");
Value value = optionalValue.get();
Book savedBook = value.get(Book.class);
System.out.println(savedBook);
}
Hazelcast.shutdownAll();
}
}

View File

@ -0,0 +1,5 @@
cassandra-host-1=localhost
cassandra-port=9142
#cassandra-threads-number=2
cassandra-query-1=CREATE KEYSPACE IF NOT EXISTS myKeySpace WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};
cassandra-query-2=CREATE COLUMNFAMILY IF NOT EXISTS myKeySpace.books (id bigint PRIMARY KEY, name text);

View File

@ -0,0 +1 @@
hazelcast-instanceName=hazelcast

View File

@ -0,0 +1,2 @@
#Define Host and Port
mongodb-server-host-1=localhost:27017

23
jnosql/pom.xml Normal file
View File

@ -0,0 +1,23 @@
<?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>
<groupId>com.baeldung.jnosql</groupId>
<artifactId>jnosql</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<jnosql.version>0.0.5</jnosql.version>
</properties>
<modules>
<module>jnosql-diana</module>
<module>jnosql-artemis</module>
</modules>
</project>

View File

@ -1,2 +0,0 @@
## Relevant articles:
- [The Order of Tests in JUnit](http://www.baeldung.com/junit-5-test-order)

View File

@ -141,6 +141,13 @@
<artifactId>hazelcast</artifactId> <artifactId>hazelcast</artifactId>
<version>${hazelcast.version}</version> <version>${hazelcast.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.googlecode.jmapper-framework</groupId>
<artifactId>jmapper-core</artifactId>
<version>${jmapper.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -275,6 +282,7 @@
<datanucleus-maven-plugin.version>5.0.2</datanucleus-maven-plugin.version> <datanucleus-maven-plugin.version>5.0.2</datanucleus-maven-plugin.version>
<datanucleus-xml.version>5.0.0-release</datanucleus-xml.version> <datanucleus-xml.version>5.0.0-release</datanucleus-xml.version>
<datanucleus-jdo-query.version>5.0.4</datanucleus-jdo-query.version> <datanucleus-jdo-query.version>5.0.4</datanucleus-jdo-query.version>
<jmapper.version>1.6.0.1</jmapper.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,56 @@
package com.baeldung.jmapper;
import java.time.LocalDate;
public class User {
private long id;
private String email;
private LocalDate birthDate;
// constructors
public User() {
super();
}
public User(long id, String email, LocalDate birthDate) {
super();
this.id = id;
this.email = email;
this.birthDate = birthDate;
}
// getters and setters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
@Override
public String toString() {
return "User [id=" + id + ", email=" + email + ", birthDate=" + birthDate + "]";
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.jmapper;
import java.time.LocalDate;
import java.time.Period;
import com.googlecode.jmapper.annotations.JMap;
import com.googlecode.jmapper.annotations.JMapConversion;
public class UserDto {
@JMap
private long id;
@JMap("email")
private String username;
@JMap("birthDate")
private int age;
@JMapConversion(from={"birthDate"}, to={"age"})
public int conversion(LocalDate birthDate){
return Period.between(birthDate, LocalDate.now()).getYears();
}
// constructors
public UserDto() {
super();
}
public UserDto(long id, String username, int age) {
super();
this.id = id;
this.username = username;
this.age = age;
}
// getters and setters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "UserDto [id=" + id + ", username=" + username + ", age=" + age + "]";
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.jmapper;
import com.googlecode.jmapper.annotations.JGlobalMap;
@JGlobalMap
public class UserDto1 {
private long id;
private String email;
// constructors
public UserDto1() {
super();
}
public UserDto1(long id, String email) {
super();
this.id = id;
this.email = email;
}
// getters and setters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "UserDto [id=" + id + ", email=" + email + "]";
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.jmapper.relational;
import com.googlecode.jmapper.annotations.JMap;
public class User {
@JMap(classes = {UserDto1.class, UserDto2.class})
private long id;
@JMap(attributes = {"username", "email"}, classes = {UserDto1.class, UserDto2.class})
private String email;
// constructors
public User() {
super();
}
public User(long id, String email) {
super();
this.id = id;
this.email = email;
}
// getters and setters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User [id=" + id + ", email=" + email + "]";
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.jmapper.relational;
public class UserDto1 {
private long id;
private String username;
// constructors
public UserDto1() {
super();
}
public UserDto1(long id, String username) {
super();
this.id = id;
this.username = username;
}
// getters and setters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return "UserDto [id=" + id + ", username=" + username + "]";
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.jmapper.relational;
public class UserDto2 {
private long id;
private String email;
// constructors
public UserDto2() {
super();
}
public UserDto2(long id, String email) {
super();
this.id = id;
this.email = email;
}
// getters and setters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "UserDto2 [id=" + id + ", email=" + email + "]";
}
}

View File

@ -0,0 +1,10 @@
<jmapper>
<class name="com.baeldung.jmapper.UserDto">
<attribute name="id">
<value name="id"/>
</attribute>
<attribute name="username">
<value name="email"/>
</attribute>
</class>
</jmapper>

View File

@ -0,0 +1,5 @@
<jmapper>
<class name="com.baeldung.jmapper.UserDto1">
<global/>
</class>
</jmapper>

View File

@ -0,0 +1,21 @@
<jmapper>
<class name="com.baeldung.jmapper.relational.User">
<attribute name="id">
<value name="id"/>
<classes>
<class name="com.baeldung.jmapper.relational.UserDto1"/>
<class name="com.baeldung.jmapper.relational.UserDto2"/>
</classes>
</attribute>
<attribute name="email">
<attributes>
<attribute name="username"/>
<attribute name="email"/>
</attributes>
<classes>
<class name="com.baeldung.jmapper.relational.UserDto1"/>
<class name="com.baeldung.jmapper.relational.UserDto2"/>
</classes>
</attribute>
</class>
</jmapper>

View File

@ -0,0 +1,114 @@
package com.baeldung.jmapper;
import static com.googlecode.jmapper.api.JMapperAPI.attribute;
import static com.googlecode.jmapper.api.JMapperAPI.global;
import static com.googlecode.jmapper.api.JMapperAPI.mappedClass;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.time.LocalDate;
import org.junit.Test;
import com.googlecode.jmapper.JMapper;
import com.googlecode.jmapper.api.JMapperAPI;
public class JMapperIntegrationTest {
@Test
public void givenUser_whenUseAnnotation_thenConverted(){
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class);
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
UserDto result = userMapper.getDestination(user);
System.out.println(result);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getUsername());
}
@Test
public void givenUser_whenUseGlobalMapAnnotation_thenConverted(){
JMapper<UserDto1, User> userMapper= new JMapper<>(UserDto1.class, User.class);
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
UserDto1 result = userMapper.getDestination(user);
System.out.println(result);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getEmail());
}
@Test
public void givenUser_whenUseAnnotationExplicitConversion_thenConverted(){
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class);
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
UserDto result = userMapper.getDestination(user);
System.out.println(result);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getUsername());
assertTrue(result.getAge() > 0);
}
//======================= XML
@Test
public void givenUser_whenUseXml_thenConverted(){
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class,"user_jmapper.xml");
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
UserDto result = userMapper.getDestination(user);
System.out.println(result);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getUsername());
}
@Test
public void givenUser_whenUseXmlGlobal_thenConverted(){
JMapper<UserDto1, User> userMapper = new JMapper<>(UserDto1.class, User.class,"user_jmapper1.xml");
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
UserDto1 result = userMapper.getDestination(user);
System.out.println(result);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getEmail());
}
// ===== API
@Test
public void givenUser_whenUseApi_thenConverted(){
JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class)
.add(attribute("id").value("id"))
.add(attribute("username").value("email"))
) ;
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class, jmapperApi);
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
UserDto result = userMapper.getDestination(user);
System.out.println(result);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getUsername());
}
@Test
public void givenUser_whenUseApiGlobal_thenConverted(){
JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class)
.add(global())
) ;
JMapper<UserDto1, User> userMapper1 = new JMapper<>(UserDto1.class, User.class,jmapperApi);
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
UserDto1 result = userMapper1.getDestination(user);
System.out.println(result);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getEmail());
}
}

View File

@ -0,0 +1,76 @@
package com.baeldung.jmapper;
import static com.googlecode.jmapper.api.JMapperAPI.attribute;
import static com.googlecode.jmapper.api.JMapperAPI.mappedClass;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.baeldung.jmapper.relational.User;
import com.baeldung.jmapper.relational.UserDto1;
import com.baeldung.jmapper.relational.UserDto2;
import com.googlecode.jmapper.RelationalJMapper;
import com.googlecode.jmapper.api.JMapperAPI;
public class JMapperRelationalIntegrationTest {
@Test
public void givenUser_whenUseAnnotation_thenConverted(){
RelationalJMapper<User> relationalMapper = new RelationalJMapper<>(User.class);
User user = new User(1L,"john@test.com");
UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user);
UserDto2 result2= relationalMapper.oneToMany(UserDto2.class, user);
System.out.println(result1);
System.out.println(result2);
assertEquals(user.getId(), result1.getId());
assertEquals(user.getEmail(), result1.getUsername());
assertEquals(user.getId(), result2.getId());
assertEquals(user.getEmail(), result2.getEmail());
}
//======================= XML
@Test
public void givenUser_whenUseXml_thenConverted(){
RelationalJMapper<User> relationalMapper = new RelationalJMapper<>(User.class,"user_jmapper2.xml");
User user = new User(1L,"john@test.com");
UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user);
UserDto2 result2 = relationalMapper.oneToMany(UserDto2.class, user);
System.out.println(result1);
System.out.println(result2);
assertEquals(user.getId(), result1.getId());
assertEquals(user.getEmail(), result1.getUsername());
assertEquals(user.getId(), result2.getId());
assertEquals(user.getEmail(), result2.getEmail());
}
// ===== API
@Test
public void givenUser_whenUseApi_thenConverted(){
JMapperAPI jmapperApi = new JMapperAPI()
.add(mappedClass(User.class)
.add(attribute("id").value("id").targetClasses(UserDto1.class,UserDto2.class))
.add(attribute("email").targetAttributes("username","email").targetClasses(UserDto1.class,UserDto2.class)) )
;
RelationalJMapper<User> relationalMapper = new RelationalJMapper<>(User.class,jmapperApi);
User user = new User(1L,"john@test.com");
UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user);
UserDto2 result2 = relationalMapper.oneToMany(UserDto2.class, user);
System.out.println(result1);
System.out.println(result2);
assertEquals(user.getId(), result1.getId());
assertEquals(user.getEmail(), result1.getUsername());
assertEquals(user.getId(), result2.getId());
assertEquals(user.getEmail(), result2.getEmail());
}
}

View File

@ -31,7 +31,7 @@ import org.springframework.web.client.RestTemplate;
import io.specto.hoverfly.junit.core.SimulationSource; import io.specto.hoverfly.junit.core.SimulationSource;
import io.specto.hoverfly.junit.rule.HoverflyRule; import io.specto.hoverfly.junit.rule.HoverflyRule;
public class HoverflyApiIntegrationTest { public class HoverflyApiLiveTest {
private static final SimulationSource source = dsl(service("http://www.baeldung.com").get("/api/courses/1").willReturn(success().body(jsonWithSingleQuotes("{'id':'1','name':'HCI'}"))) private static final SimulationSource source = dsl(service("http://www.baeldung.com").get("/api/courses/1").willReturn(success().body(jsonWithSingleQuotes("{'id':'1','name':'HCI'}")))

View File

@ -5,7 +5,7 @@ import org.junit.Test;
import static org.assertj.core.api.Java6Assertions.assertThat; import static org.assertj.core.api.Java6Assertions.assertThat;
public class HelloWorldServiceIntegrationTest extends AbstractIntegrationTest { public class HelloWorldServiceTemporaryLiveTest extends AbstractIntegrationTest {
@Test @Test
public void whenGetIsCalledTwoTimes_thenTheSecondShouldHitTheCache() { public void whenGetIsCalledTwoTimes_thenTheSecondShouldHitTheCache() {

View File

@ -48,8 +48,10 @@
<exclude>DataTest.java</exclude> <exclude>DataTest.java</exclude>
</excludes> </excludes>
<includes> <includes>
<include>TestFail.java</include>
<include>DataCheck.java</include> <include>DataCheck.java</include>
</includes> </includes>
<testFailureIgnore>true</testFailureIgnore>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>

View File

@ -0,0 +1,15 @@
package testfail;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
public class TestFail {
@Test
public void whenMessageAssigned_thenItIsNotNull() {
String message = "hello there";
message = null;
assertNotNull(message);
}
}

View File

@ -106,5 +106,4 @@ public class MavenWrapperDownloader {
fos.close(); fos.close();
rbc.close(); rbc.close();
} }
} }

Some files were not shown because too many files have changed in this diff Show More