This commit is contained in:
Ahmed Tawila 2017-10-13 21:21:15 +02:00
commit d503a53ee0
30 changed files with 1468 additions and 40 deletions

51
asm/pom.xml Normal file
View File

@ -0,0 +1,51 @@
<?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.examples</groupId>
<artifactId>asm</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>5.2</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-util</artifactId>
<version>5.2</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifestEntries>
<Premain-Class>
com.baeldung.examples.asm.instrumentation.Premain
</Premain-Class>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<argLine>-javaagent:"C:\asm-1.0.jar"</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,160 @@
package com.baeldung.examples.asm;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ASM4;
import static org.objectweb.asm.Opcodes.V1_5;
import org.objectweb.asm.Type;
import org.objectweb.asm.util.TraceClassVisitor;
/**
*
* @author baeldung
* @param <String>
*/
public class CustomClassWriter {
ClassReader reader;
ClassWriter writer;
AddFieldAdapter addFieldAdapter;
AddInterfaceAdapter addInterfaceAdapter;
PublicizeMethodAdapter pubMethAdapter;
final static String CLASSNAME = "java.lang.Integer";
final static String CLONEABLE = "java/lang/Cloneable";
public CustomClassWriter() {
try {
reader = new ClassReader(CLASSNAME);
writer = new ClassWriter(reader, 0);
} catch (IOException ex) {
Logger.getLogger(CustomClassWriter.class.getName()).log(Level.SEVERE, null, ex);
}
}
public CustomClassWriter(byte[] contents) {
reader = new ClassReader(contents);
writer = new ClassWriter(reader, 0);
}
public static void main(String[] args) {
CustomClassWriter ccw = new CustomClassWriter();
ccw.publicizeMethod();
}
public byte[] addField() {
addFieldAdapter = new AddFieldAdapter("aNewBooleanField", org.objectweb.asm.Opcodes.ACC_PUBLIC, writer);
reader.accept(addFieldAdapter, 0);
return writer.toByteArray();
}
public byte[] publicizeMethod() {
pubMethAdapter = new PublicizeMethodAdapter(writer);
reader.accept(pubMethAdapter, 0);
return writer.toByteArray();
}
public byte[] addInterface() {
addInterfaceAdapter = new AddInterfaceAdapter(writer);
reader.accept(addInterfaceAdapter, 0);
return writer.toByteArray();
}
public class AddInterfaceAdapter extends ClassVisitor {
public AddInterfaceAdapter(ClassVisitor cv) {
super(ASM4, cv);
}
@Override
public void visit(int version, int access, String name,
String signature, String superName, String[] interfaces) {
String[] holding = new String[interfaces.length + 1];
holding[holding.length - 1] = CLONEABLE;
System.arraycopy(interfaces, 0, holding, 0, interfaces.length);
cv.visit(V1_5, access, name, signature, superName, holding);
}
}
public class PublicizeMethodAdapter extends ClassVisitor {
final Logger logger = Logger.getLogger("PublicizeMethodAdapter");
TraceClassVisitor tracer;
PrintWriter pw = new PrintWriter(System.out);
public PublicizeMethodAdapter(ClassVisitor cv) {
super(ASM4, cv);
this.cv = cv;
tracer = new TraceClassVisitor(cv, pw);
}
@Override
public MethodVisitor visitMethod(int access,
String name,
String desc,
String signature,
String[] exceptions) {
if (name.equals("toUnsignedString0")) {
logger.info("Visiting unsigned method");
return tracer.visitMethod(ACC_PUBLIC + ACC_STATIC, name, desc, signature, exceptions);
}
return tracer.visitMethod(access, name, desc, signature, exceptions);
}
public void visitEnd() {
tracer.visitEnd();
System.out.println(tracer.p.getText());
}
}
public class AddFieldAdapter extends ClassVisitor {
String fieldName;
int access;
boolean isFieldPresent;
public AddFieldAdapter(String fieldName, int access, ClassVisitor cv) {
super(ASM4, cv);
this.cv = cv;
this.access = access;
this.fieldName = fieldName;
}
@Override
public FieldVisitor visitField(int access, String name, String desc,
String signature, Object value) {
if (name.equals(fieldName)) {
isFieldPresent = true;
}
return cv.visitField(access, name, desc, signature, value);
}
@Override
public void visitEnd() {
if (!isFieldPresent) {
FieldVisitor fv = cv.visitField(access, fieldName, Type.BOOLEAN_TYPE.toString(), null, null);
if (fv != null) {
fv.visitEnd();
}
}
cv.visitEnd();
}
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.examples.asm.instrumentation;
import com.baeldung.examples.asm.CustomClassWriter;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
/**
*
* @author baeldung
*/
public class Premain {
public static void premain(String agentArgs, Instrumentation inst) {
inst.addTransformer(new ClassFileTransformer() {
@Override
public byte[] transform(ClassLoader l, String name, Class c,
ProtectionDomain d, byte[] b)
throws IllegalClassFormatException {
if (name.equals("java/lang/Integer")) {
CustomClassWriter cr = new CustomClassWriter(b);
return cr.addField();
}
return b;
}
});
}
}

View File

@ -5,6 +5,7 @@
<artifactId>core-kotlin</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
@ -20,6 +21,24 @@
</repositories>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit4.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
@ -116,16 +135,51 @@
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.19.1</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>junit5</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<includes>
<include>**/*Test5.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<kotlin-maven-plugin.version>1.1.2</kotlin-maven-plugin.version>
<kotlin-test-junit.version>1.1.2</kotlin-test-junit.version>
<kotlin-stdlib.version>1.1.2</kotlin-stdlib.version>
<kotlin-reflect.version>1.1.2</kotlin-reflect.version>
<kotlinx.version>0.15</kotlinx.version>
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
<junit.jupiter.version>5.0.0</junit.jupiter.version>
<junit.platform.version>1.0.0</junit.platform.version>
<junit.vintage.version>4.12.0</junit.vintage.version>
<junit4.version>4.12</junit4.version>
</properties>
</project>
</project>

View File

@ -0,0 +1,17 @@
package com.baeldung.kotlin.junit5
class Calculator {
fun add(a: Int, b: Int) = a + b
fun divide(a: Int, b: Int) = if (b == 0) {
throw DivideByZeroException(a)
} else {
a / b
}
fun square(a: Int) = a * a
fun squareRoot(a: Int) = Math.sqrt(a.toDouble())
fun log(base: Int, value: Int) = Math.log(value.toDouble()) / Math.log(base.toDouble())
}

View File

@ -0,0 +1,82 @@
package com.baeldung.kotlin.junit5
import org.junit.jupiter.api.*
import org.junit.jupiter.api.function.Executable
class CalculatorTest5 {
private val calculator = Calculator()
@Test
fun testAddition() {
Assertions.assertEquals(4, calculator.add(1, 3))
}
@Test
fun testDivideByZero() {
val exception = Assertions.assertThrows(DivideByZeroException::class.java) {
calculator.divide(5, 0)
}
Assertions.assertEquals(5, exception.numerator)
}
@Test
fun testSquares() {
Assertions.assertAll(
Executable { Assertions.assertEquals(1, calculator.square(1)) },
Executable { Assertions.assertEquals(4, calculator.square(2)) },
Executable { Assertions.assertEquals(9, calculator.square(3)) }
)
}
@TestFactory
fun testSquaresFactory() = listOf(
DynamicTest.dynamicTest("1 squared") { Assertions.assertEquals(1,calculator.square(1))},
DynamicTest.dynamicTest("2 squared") { Assertions.assertEquals(4,calculator.square(2))},
DynamicTest.dynamicTest("3 squared") { Assertions.assertEquals(9,calculator.square(3))}
)
@TestFactory
fun testSquaresFactory2() = listOf(
1 to 1,
2 to 4,
3 to 9,
4 to 16,
5 to 25)
.map { (input, expected) ->
DynamicTest.dynamicTest("$input squared") {
Assertions.assertEquals(expected, calculator.square(input))
}
}
private val squaresTestData = listOf(
1 to 1,
2 to 4,
3 to 9,
4 to 16,
5 to 25)
@TestFactory
fun testSquaresFactory3() = squaresTestData
.map { (input, expected) ->
DynamicTest.dynamicTest("$input squared") {
Assertions.assertEquals(expected, calculator.square(input))
}
}
@TestFactory
fun testSquareRootsFactory3() = squaresTestData
.map { (expected, input) ->
DynamicTest.dynamicTest("Square root of $input") {
Assertions.assertEquals(expected.toDouble(), calculator.squareRoot(input))
}
}
@Tags(
Tag("slow"),
Tag("logarithms")
)
@Test
fun testLogarithms() {
Assertions.assertEquals(3.0, calculator.log(2, 8))
}
}

View File

@ -0,0 +1,3 @@
package com.baeldung.kotlin.junit5
class DivideByZeroException(val numerator: Int) : Exception()

View File

@ -0,0 +1,21 @@
package com.baeldung.kotlin.junit5
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
class SimpleTest5 {
@Test
fun testEmpty() {
val list = listOf<String>()
Assertions.assertTrue(list::isEmpty)
}
@Test
@Disabled
fun testMessage() {
Assertions.assertEquals(3, 4) {
"Three does not equal four"
}
}
}

View File

@ -36,6 +36,11 @@
<artifactId>reladomo-test-util</artifactId>
<version>${reladomo.version}</version>
</dependency>
<dependency>
<groupId>com.j256.ormlite</groupId>
<artifactId>ormlite-jdbc</artifactId>
<version>${ormlite.version}</version>
</dependency>
</dependencies>
<build>
@ -144,5 +149,6 @@
<reladomo.version>16.5.1</reladomo.version>
<junit.version>4.12</junit.version>
<maven-compiler-plugin.version>3.6.2</maven-compiler-plugin.version>
<ormlite.version>5.0</ormlite.version>
</properties>
</project>

View File

@ -0,0 +1,37 @@
package com.baeldung.ormlite;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "addresses")
public class Address {
@DatabaseField(generatedId = true)
private long addressId;
@DatabaseField(canBeNull = false)
private String addressLine;
public Address() {
}
public Address(String addressLine) {
this.addressLine = addressLine;
}
public long getAddressId() {
return addressId;
}
public void setAddressId(long addressId) {
this.addressId = addressId;
}
public String getAddressLine() {
return addressLine;
}
public void setAddressLine(String addressLine) {
this.addressLine = addressLine;
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.ormlite;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable
public class Book {
@DatabaseField(generatedId = true)
private long bookId;
@DatabaseField
private String title;
@DatabaseField(foreign = true, foreignAutoRefresh = true, foreignAutoCreate = true)
private Library library;
public Book() {
}
public Book(String title) {
this.title = title;
}
public long getBookId() {
return bookId;
}
public void setBookId(long bookId) {
this.bookId = bookId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Library getLibrary() {
return library;
}
public void setLibrary(Library library) {
this.library = library;
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.ormlite;
import com.j256.ormlite.dao.ForeignCollection;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "libraries", daoClass = LibraryDaoImpl.class)
public class Library {
@DatabaseField(generatedId = true)
private long libraryId;
@DatabaseField(canBeNull = false)
private String name;
@DatabaseField(foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true)
private Address address;
@ForeignCollectionField(eager = false)
private ForeignCollection<Book> books;
public Library() {
}
public long getLibraryId() {
return libraryId;
}
public void setLibraryId(long libraryId) {
this.libraryId = libraryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public ForeignCollection<Book> getBooks() {
return books;
}
public void setBooks(ForeignCollection<Book> books) {
this.books = books;
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.ormlite;
import java.sql.SQLException;
import java.util.List;
import com.j256.ormlite.dao.Dao;
public interface LibraryDao extends Dao<Library, Long> {
public List<Library> findByName(String name) throws SQLException;
}

View File

@ -0,0 +1,21 @@
package com.baeldung.ormlite;
import java.sql.SQLException;
import java.util.List;
import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.support.ConnectionSource;
public class LibraryDaoImpl extends BaseDaoImpl<Library, Long> implements LibraryDao {
public LibraryDaoImpl(ConnectionSource connectionSource) throws SQLException {
super(connectionSource, Library.class);
}
@Override
public List<Library> findByName(String name) throws SQLException {
return super.queryForEq("name", name);
}
}

View File

@ -0,0 +1,168 @@
package com.baeldung.ormlite;
import static org.junit.Assert.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.j256.ormlite.dao.CloseableWrappedIterable;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.jdbc.JdbcPooledConnectionSource;
import com.j256.ormlite.table.TableUtils;
public class ORMLiteTest {
private static JdbcPooledConnectionSource connectionSource;
private static Dao<Library, Long> libraryDao;
private static Dao<Book, Long> bookDao;
@BeforeClass
public static void setup() throws SQLException {
connectionSource = new JdbcPooledConnectionSource("jdbc:h2:mem:myDb");
TableUtils.createTableIfNotExists(connectionSource, Library.class);
TableUtils.createTableIfNotExists(connectionSource, Address.class);
TableUtils.createTableIfNotExists(connectionSource, Book.class);
libraryDao = DaoManager.createDao(connectionSource, Library.class);
bookDao = DaoManager.createDao(connectionSource, Book.class);
}
@Test
public void givenDAO_whenCRUD_thenOk() throws SQLException {
Library library = new Library();
library.setName("My Library");
libraryDao.create(library);
Library result = libraryDao.queryForId(library.getLibraryId());
assertEquals("My Library", result.getName());
library.setName("My Other Library");
libraryDao.update(library);
libraryDao.delete(library);
}
@Test
public void whenLoopDao_thenOk() throws SQLException {
Library library1 = new Library();
library1.setName("My Library");
libraryDao.create(library1);
Library library2 = new Library();
library2.setName("My Other Library");
libraryDao.create(library2);
libraryDao.forEach(lib -> {
System.out.println(lib.getName());
});
}
@Test
public void givenIterator_whenLoop_thenOk() throws SQLException, IOException {
Library library1 = new Library();
library1.setName("My Library");
libraryDao.create(library1);
Library library2 = new Library();
library2.setName("My Other Library");
libraryDao.create(library2);
try (CloseableWrappedIterable<Library> wrappedIterable = libraryDao.getWrappedIterable()) {
wrappedIterable.forEach(lib -> {
System.out.println(lib.getName());
});
}
}
@Test
public void givenCustomDao_whenSave_thenOk() throws SQLException, IOException {
Library library = new Library();
library.setName("My Library");
LibraryDao customLibraryDao = DaoManager.createDao(connectionSource, Library.class);
customLibraryDao.create(library);
assertEquals(1, customLibraryDao.findByName("My Library")
.size());
}
@Test
public void whenSaveForeignField_thenOk() throws SQLException, IOException {
Library library = new Library();
library.setName("My Library");
library.setAddress(new Address("Main Street nr 20"));
libraryDao.create(library);
Dao<Address, Long> addressDao = DaoManager.createDao(connectionSource, Address.class);
assertEquals(1, addressDao.queryForEq("addressLine", "Main Street nr 20")
.size());
}
@Test
public void whenSaveForeignCollection_thenOk() throws SQLException, IOException {
Library library = new Library();
library.setName("My Library");
libraryDao.create(library);
libraryDao.refresh(library);
library.getBooks()
.add(new Book("1984"));
Book book = new Book("It");
book.setLibrary(library);
bookDao.create(book);
assertEquals(2, bookDao.queryForEq("library_id", library)
.size());
}
@Test
public void whenGetLibrariesWithMoreThanOneBook_thenOk() throws SQLException, IOException {
Library library = new Library();
library.setName("My Library");
libraryDao.create(library);
Library library2 = new Library();
library2.setName("My Other Library");
libraryDao.create(library2);
libraryDao.refresh(library);
libraryDao.refresh(library2);
library.getBooks()
.add(new Book("Book1"));
library2.getBooks()
.add(new Book("Book2"));
library2.getBooks()
.add(new Book("Book3"));
List<Library> libraries = libraryDao.queryBuilder()
.where()
.in("libraryId", bookDao.queryBuilder()
.selectColumns("library_id")
.groupBy("library_id")
.having("count(*) > 1"))
.query();
assertEquals(1, libraries.size());
}
@After
public void clear() throws SQLException {
TableUtils.clearTable(connectionSource, Library.class);
TableUtils.clearTable(connectionSource, Book.class);
TableUtils.clearTable(connectionSource, Address.class);
}
@AfterClass
public static void tearDown() throws SQLException, IOException {
connectionSource.close();
}
}

View File

@ -41,6 +41,7 @@
- [Introduction to NoException](http://www.baeldung.com/no-exception)
- [Introduction to FunctionalJava](http://www.baeldung.com/functional-java)
- [Apache Commons IO](http://www.baeldung.com/apache-commons-io)
- [Introduction to Conflict-Free Replicated Data Types](http://www.baeldung.com/java-conflict-free-replicated-data-types)
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.

View File

@ -575,22 +575,6 @@
<artifactId>hazelcast</artifactId>
<version>${hazelcast.version}</version>
</dependency>
<dependency>
<groupId>com.atlassian.jira</groupId>
<artifactId>jira-rest-java-client-core</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.atlassian.fugue</groupId>
<artifactId>fugue</artifactId>
<version>2.6.1</version>
</dependency>
<!-- Uncomment this in order to use the jira-rest-java-client-core API -->
<!-- <dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency> -->
<dependency>
<groupId>org.jgrapht</groupId>
<artifactId>jgrapht-core</artifactId>
@ -606,11 +590,16 @@
<artifactId>docx4j</artifactId>
<version>3.3.5</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>${caffeine.version}</version>
</dependency>
</dependencies>
<repositories>
<repository>
@ -626,10 +615,6 @@
<name>bintray</name>
<url>http://dl.bintray.com/cuba-platform/main</url>
</repository>
<repository>
<id>atlassian-public</id>
<url>https://packages.atlassian.com/maven/repository/public</url>
</repository>
</repositories>
<properties>
<crdt.version>0.1.0</crdt.version>
@ -686,5 +671,6 @@
<unit-ri.version>1.0.3</unit-ri.version>
<cache.version>1.0.0</cache.version>
<hazelcast.version>3.8.4</hazelcast.version>
<caffeine.version>2.5.5</caffeine.version>
</properties>
</project>

View File

@ -0,0 +1,28 @@
package com.baeldung.caffeine;
final class DataObject {
private final String data;
private static int objectCounter = 0;
private DataObject(String data) {
this.data = data;
}
public String getData() {
return data;
}
@Override
public String toString() {
return "DataObject{" +
"data='" + data + '\'' +
'}';
}
public static DataObject get(String data) {
objectCounter++;
System.out.println(String.format("Initializing DataObject#%d with data '%s'", objectCounter, data));
return new DataObject(data);
}
}

View File

@ -0,0 +1,174 @@
package com.baeldung.caffeine;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnull;
import org.junit.Test;
import com.github.benmanes.caffeine.cache.*;
public class CaffeineUnitTest {
@Test
public void givenCache_whenPopulate_thenValueStored() {
Cache<String, DataObject> cache = Caffeine.newBuilder()
.expireAfterWrite(1, TimeUnit.MINUTES)
.maximumSize(100)
.build();
String key = "A";
DataObject dataObject = cache.getIfPresent(key);
assertNull(dataObject);
dataObject = cache.get(key, k -> DataObject.get("Data for A"));
assertNotNull(dataObject);
assertEquals("Data for A", dataObject.getData());
cache.put(key, dataObject);
dataObject = cache.getIfPresent(key);
assertNotNull(dataObject);
cache.invalidate(key);
dataObject = cache.getIfPresent(key);
assertNull(dataObject);
}
@Test
public void givenLoadingCache_whenGet_thenValuePopulated() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder()
.maximumSize(100)
.expireAfterWrite(1, TimeUnit.MINUTES)
.build(k -> DataObject.get("Data for " + k));
String key = "A";
DataObject dataObject = cache.get(key);
assertNotNull(dataObject);
assertEquals("Data for " + key, dataObject.getData());
Map<String, DataObject> dataObjectMap = cache.getAll(Arrays.asList("A", "B", "C"));
assertEquals(3, dataObjectMap.size());
}
@Test
public void givenAsyncLoadingCache_whenGet_thenValuePopulated() {
AsyncLoadingCache<String, DataObject> cache = Caffeine.newBuilder()
.maximumSize(100)
.expireAfterWrite(1, TimeUnit.MINUTES)
.buildAsync(k -> DataObject.get("Data for " + k));
String key = "A";
cache.get(key).thenAccept(dataObject -> {
assertNotNull(dataObject);
assertEquals("Data for " + key, dataObject.getData());
});
cache.getAll(Arrays.asList("A", "B", "C"))
.thenAccept(dataObjectMap -> assertEquals(3, dataObjectMap.size()));
}
@Test
public void givenLoadingCacheWithSmallSize_whenPut_thenSizeIsConstant() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder()
.maximumSize(1)
.refreshAfterWrite(10, TimeUnit.MINUTES)
.build(k -> DataObject.get("Data for " + k));
assertEquals(0, cache.estimatedSize());
cache.get("A");
assertEquals(1, cache.estimatedSize());
cache.get("B");
cache.cleanUp();
assertEquals(1, cache.estimatedSize());
}
@Test
public void givenLoadingCacheWithWeigher_whenPut_thenSizeIsConstant() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder()
.maximumWeight(10)
.weigher((k,v) -> 5)
.build(k -> DataObject.get("Data for " + k));
assertEquals(0, cache.estimatedSize());
cache.get("A");
assertEquals(1, cache.estimatedSize());
cache.get("B");
assertEquals(2, cache.estimatedSize());
cache.get("C");
cache.cleanUp();
assertEquals(2, cache.estimatedSize());
}
@Test
public void givenTimeEvictionCache_whenTimeLeft_thenValueEvicted() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder()
.expireAfterAccess(5, TimeUnit.MINUTES)
.build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.SECONDS)
.weakKeys()
.weakValues()
.build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.SECONDS)
.softValues()
.build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder().expireAfter(new Expiry<String, DataObject>() {
@Override
public long expireAfterCreate(@Nonnull String key, @Nonnull DataObject value, long currentTime) {
return value.getData().length() * 1000;
}
@Override
public long expireAfterUpdate(@Nonnull String key, @Nonnull DataObject value, long currentTime, long currentDuration) {
return currentDuration;
}
@Override
public long expireAfterRead(@Nonnull String key, @Nonnull DataObject value, long currentTime, long currentDuration) {
return currentDuration;
}
}).build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder()
.refreshAfterWrite(1, TimeUnit.MINUTES)
.build(k -> DataObject.get("Data for " + k));
}
@Test
public void givenCache_whenStatsEnabled_thenStatsRecorded() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder()
.maximumSize(100)
.recordStats()
.build(k -> DataObject.get("Data for " + k));
cache.get("A");
cache.get("A");
assertEquals(1, cache.stats().hitCount());
assertEquals(1, cache.stats().missCount());
}
}

View File

@ -10,3 +10,4 @@
- [Mockito @Mock, @Spy, @Captor and @InjectMocks](http://www.baeldung.com/mockito-annotations)
- [Mockitos Mock Methods](http://www.baeldung.com/mockito-mock-methods)
- [Introduction to PowerMock](http://www.baeldung.com/intro-to-powermock)
- [Mocking Exception Throwing using Mockito](http://www.baeldung.com/mockito-exceptions)

View File

@ -28,6 +28,7 @@
</properties>
<modules>
<module>asm</module>
<module>atomix</module>
<module>apache-cayenne</module>
<module>aws</module>
@ -248,6 +249,7 @@
<module>mockserver</module>
<module>undertow</module>
<module>vertx-and-rxjava</module>
<module>saas</module>
<module>deeplearning4j</module>
</modules>

View File

@ -25,6 +25,12 @@
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>io.reactivex</groupId>
<artifactId>rxjava-math</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>

View File

@ -0,0 +1,210 @@
package com.baeldung.rxjava.operators;
import org.junit.Test;
import rx.Observable;
import rx.observers.TestSubscriber;
import java.util.*;
public class RxAggregateOperatorsTest {
@Test
public void givenTwoObservable_whenConcatenatingThem_thenSuccessfull() {
// given
List<Integer> listOne = Arrays.asList(1, 2, 3, 4);
Observable<Integer> observableOne = Observable.from(listOne);
List<Integer> listTwo = Arrays.asList(5, 6, 7, 8);
Observable<Integer> observableTwo = Observable.from(listTwo);
TestSubscriber<Integer> subscriber = TestSubscriber.create();
// when
Observable<Integer> concatObservable = observableOne.concatWith(observableTwo);
concatObservable.subscribe(subscriber);
// then
subscriber.assertCompleted();
subscriber.assertNoErrors();
subscriber.assertValueCount(8);
subscriber.assertValues(1, 2, 3, 4, 5, 6, 7, 8);
}
@Test
public void givenObservable_whenCounting_thenObtainingNumberOfElements() {
// given
List<String> lettersList = Arrays.asList("A", "B", "C", "D", "E", "F", "G");
TestSubscriber<Integer> subscriber = TestSubscriber.create();
// when
Observable<Integer> sourceObservable = Observable.from(lettersList)
.count();
sourceObservable.subscribe(subscriber);
// then
subscriber.assertCompleted();
subscriber.assertNoErrors();
subscriber.assertValueCount(1);
subscriber.assertValue(7);
}
@Test
public void givenObservable_whenReducing_thenObtainingInvertedConcatenatedString() {
// given
List<String> list = Arrays.asList("A", "B", "C", "D", "E", "F", "G");
TestSubscriber<String> subscriber = TestSubscriber.create();
// when
Observable<String> reduceObservable = Observable.from(list)
.reduce((letter1, letter2) -> letter2 + letter1);
reduceObservable.subscribe(subscriber);
// then
subscriber.assertCompleted();
subscriber.assertNoErrors();
subscriber.assertValueCount(1);
subscriber.assertValue("GFEDCBA");
}
@Test
public void givenObservable_whenCollecting_thenObtainingASet() {
// given
List<String> list = Arrays.asList("A", "B", "C", "B", "B", "A", "D");
TestSubscriber<HashSet> subscriber = TestSubscriber.create();
// when
Observable<HashSet> reduceListObservable = Observable.from(list)
.collect(() -> new HashSet(), (set, item) -> set.add(item));
reduceListObservable.subscribe(subscriber);
// then
subscriber.assertCompleted();
subscriber.assertNoErrors();
subscriber.assertValueCount(1);
subscriber.assertValues(new HashSet(list));
}
@Test
public void givenObservable_whenUsingToList_thenObtainedAList() {
// given
Observable<Integer> sourceObservable = Observable.range(1, 5);
TestSubscriber<List> subscriber = TestSubscriber.create();
// when
Observable<List<Integer>> listObservable = sourceObservable.toList();
listObservable.subscribe(subscriber);
// then
subscriber.assertCompleted();
subscriber.assertNoErrors();
subscriber.assertValueCount(1);
subscriber.assertValue(Arrays.asList(1, 2, 3, 4, 5));
}
@Test
public void givenObservable_whenUsingToSortedList_thenObtainedASortedList() {
// given
Observable<Integer> sourceObservable = Observable.range(10, 5);
TestSubscriber<List> subscriber = TestSubscriber.create();
// when
Observable<List<Integer>> listObservable = sourceObservable.toSortedList();
listObservable.subscribe(subscriber);
// then
subscriber.assertCompleted();
subscriber.assertNoErrors();
subscriber.assertValueCount(1);
subscriber.assertValue(Arrays.asList(10, 11, 12, 13, 14));
}
@Test
public void givenObservable_whenUsingToSortedListWithComparator_thenObtainedAnInverseSortedList() {
// given
Observable<Integer> sourceObservable = Observable.range(10, 5);
TestSubscriber<List> subscriber = TestSubscriber.create();
// when
Observable<List<Integer>> listObservable = sourceObservable.toSortedList((int1, int2) -> int2 - int1);
listObservable.subscribe(subscriber);
// then
subscriber.assertCompleted();
subscriber.assertNoErrors();
subscriber.assertValueCount(1);
subscriber.assertValue(Arrays.asList(14, 13, 12, 11, 10));
}
@Test
public void givenObservable_whenUsingToMap_thenObtainedAMap() {
// given
Observable<Book> bookObservable = Observable.just(new Book("The North Water", 2016), new Book("Origin", 2017), new Book("Sleeping Beauties", 2017));
TestSubscriber<Map> subscriber = TestSubscriber.create();
// when
Observable<Map<String, Integer>> mapObservable = bookObservable.toMap(Book::getTitle, Book::getYear, HashMap::new);
mapObservable.subscribe(subscriber);
// then
subscriber.assertCompleted();
subscriber.assertNoErrors();
subscriber.assertValueCount(1);
subscriber.assertValue(new HashMap() {
{
put("The North Water", 2016);
put("Origin", 2017);
put("Sleeping Beauties", 2017);
}
});
}
@Test
public void givenObservable_whenUsingToMultiMap_thenObtainedAMultiMap() {
// given
Observable<Book> bookObservable = Observable.just(new Book("The North Water", 2016), new Book("Origin", 2017), new Book("Sleeping Beauties", 2017));
TestSubscriber<Map> subscriber = TestSubscriber.create();
// when
Observable multiMapObservable = bookObservable.toMultimap(Book::getYear, Book::getTitle, () -> new HashMap(), (key) -> new ArrayList());
multiMapObservable.subscribe(subscriber);
// then
subscriber.assertCompleted();
subscriber.assertNoErrors();
subscriber.assertValueCount(1);
subscriber.assertValue(new HashMap() {
{
put(2016, Arrays.asList("The North Water"));
put(2017, Arrays.asList("Origin", "Sleeping Beauties"));
}
});
}
class Book {
private String title;
private Integer year;
public Book(String title, Integer year) {
this.title = title;
this.year = year;
}
public String getTitle() {
return title;
}
public Integer getYear() {
return year;
}
}
}

View File

@ -0,0 +1,139 @@
package com.baeldung.rxjava.operators;
import org.junit.Test;
import rx.Observable;
import rx.observables.MathObservable;
import rx.observers.TestSubscriber;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class RxMathematicalOperatorsTest {
@Test
public void givenRangeNumericObservable_whenCalculatingAverage_ThenSuccessfull() {
// given
Observable<Integer> sourceObservable = Observable.range(1, 20);
TestSubscriber<Integer> subscriber = TestSubscriber.create();
// when
MathObservable.averageInteger(sourceObservable)
.subscribe(subscriber);
// then
subscriber.assertCompleted();
subscriber.assertNoErrors();
subscriber.assertValueCount(1);
subscriber.assertValue(10);
}
@Test
public void givenRangeNumericObservable_whenCalculatingSum_ThenSuccessfull() {
// given
Observable<Integer> sourceObservable = Observable.range(1, 20);
TestSubscriber<Integer> subscriber = TestSubscriber.create();
// when
MathObservable.sumInteger(sourceObservable)
.subscribe(subscriber);
// then
subscriber.assertCompleted();
subscriber.assertNoErrors();
subscriber.assertValueCount(1);
subscriber.assertValue(210);
}
@Test
public void givenRangeNumericObservable_whenCalculatingMax_ThenSuccessfullObtainingMaxValue() {
// given
Observable<Integer> sourceObservable = Observable.range(1, 20);
TestSubscriber<Integer> subscriber = TestSubscriber.create();
// when
MathObservable.max(sourceObservable)
.subscribe(subscriber);
// then
subscriber.assertCompleted();
subscriber.assertNoErrors();
subscriber.assertValueCount(1);
subscriber.assertValue(20);
}
@Test
public void givenRangeNumericObservable_whenCalculatingMin_ThenSuccessfullObtainingMinValue() {
// given
Observable<Integer> sourceObservable = Observable.range(1, 20);
TestSubscriber<Integer> subscriber = TestSubscriber.create();
// when
MathObservable.min(sourceObservable)
.subscribe(subscriber);
// then
subscriber.assertCompleted();
subscriber.assertNoErrors();
subscriber.assertValueCount(1);
subscriber.assertValue(1);
}
@Test
public void givenItemObservable_whenCalculatingMaxWithComparator_ThenSuccessfullObtainingMaxItem() {
// given
Item five = new Item(5);
List<Item> list = Arrays.asList(new Item(1), new Item(2), new Item(3), new Item(4), five);
Observable<Item> itemObservable = Observable.from(list);
TestSubscriber<Item> subscriber = TestSubscriber.create();
// when
MathObservable.from(itemObservable)
.max(Comparator.comparing(Item::getId))
.subscribe(subscriber);
// then
subscriber.assertCompleted();
subscriber.assertNoErrors();
subscriber.assertValueCount(1);
subscriber.assertValue(five);
}
@Test
public void givenItemObservable_whenCalculatingMinWithComparator_ThenSuccessfullObtainingMinItem() {
// given
Item one = new Item(1);
List<Item> list = Arrays.asList(one, new Item(2), new Item(3), new Item(4), new Item(5));
TestSubscriber<Item> subscriber = TestSubscriber.create();
Observable<Item> itemObservable = Observable.from(list);
// when
MathObservable.from(itemObservable)
.min(Comparator.comparing(Item::getId))
.subscribe(subscriber);
// then
subscriber.assertCompleted();
subscriber.assertNoErrors();
subscriber.assertValueCount(1);
subscriber.assertValue(one);
}
class Item {
private Integer id;
public Item(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
}

26
saas/.gitignore vendored Normal file
View File

@ -0,0 +1,26 @@
*.class
0.*
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
.resourceCache
# Packaged files #
*.jar
*.war
*.ear
# Files generated by integration tests
*.txt
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea/
*.iml

84
saas/pom.xml Normal file
View File

@ -0,0 +1,84 @@
<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>saas</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>saas</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.atlassian.jira</groupId>
<artifactId>jira-rest-java-client-core</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.atlassian.fugue</groupId>
<artifactId>fugue</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
</dependencies>
<build>
<finalName>saas</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<configuration>
<executable>java</executable>
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
<arguments>
<argument>-Xmx300m</argument>
<argument>-XX:+UseParallelGC</argument>
<argument>-classpath</argument>
<classpath />
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>atlassian-public</id>
<url>https://packages.atlassian.com/maven/repository/public</url>
</repository>
</repositories>
<properties>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties>
</project>

View File

@ -1,4 +1,4 @@
package com.baeldung.jira;
package com.baeldung.saas.jira;
import com.atlassian.jira.rest.client.api.IssueRestClient;
import com.atlassian.jira.rest.client.api.JiraRestClient;

View File

@ -195,7 +195,11 @@
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
</dependencyManagement>
@ -280,4 +284,4 @@
</properties>
</project>
</project>

View File

@ -0,0 +1,9 @@
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Title</title>
</head>
<body>
<div>Web Application. Passed parameter : th:text="${message}"</div>
</body>
</html>

View File

@ -1,11 +0,0 @@
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<div style="padding: 10px; border-radius: 10px; font-size: 30px; text-align: center;">
Web Application. Passed parameter : ${message}
</div>
</body>
</html>