merge from upstream

This commit is contained in:
Jon Cook 2018-09-09 11:55:42 +02:00
commit 410ce3d144
449 changed files with 5842 additions and 3482 deletions

View File

@ -3,10 +3,11 @@
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>JGitSnippets</artifactId>
<artifactId>JGit</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<name>JGit</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -0,0 +1,38 @@
package com.baeldung.algorithms.distancebetweenpoints;
import java.awt.geom.Point2D;
public class DistanceBetweenPointsService {
public double calculateDistanceBetweenPoints(
double x1,
double y1,
double x2,
double y2) {
return Math.sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1));
}
public double calculateDistanceBetweenPointsWithHypot(
double x1,
double y1,
double x2,
double y2) {
double ac = Math.abs(y2 - y1);
double cb = Math.abs(x2 - x1);
return Math.hypot(ac, cb);
}
public double calculateDistanceBetweenPointsWithPoint2D(
double x1,
double y1,
double x2,
double y2) {
return Point2D.distance(x1, y1, x2, y2);
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.algorithms.rectanglesoverlap;
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.algorithms.rectanglesoverlap;
public class Rectangle {
private Point bottomLeft;
private Point topRight;
public Rectangle(Point bottomLeft, Point topRight) {
this.bottomLeft = bottomLeft;
this.topRight = topRight;
}
public Point getBottomLeft() {
return bottomLeft;
}
public void setBottomLeft(Point bottomLeft) {
this.bottomLeft = bottomLeft;
}
public Point getTopRight() {
return topRight;
}
public void setTopRight(Point topRight) {
this.topRight = topRight;
}
public boolean isOverlapping(Rectangle other) {
// one rectangle is to the top of the other
if (this.topRight.getY() < other.bottomLeft.getY() || this.bottomLeft.getY() > other.topRight.getY()) {
return false;
}
// one rectangle is to the left of the other
if (this.topRight.getX() < other.bottomLeft.getX() || this.bottomLeft.getX() > other.topRight.getX()) {
return false;
}
return true;
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.algorithms.distancebetweenpoints;
import org.junit.Test;
import com.baeldung.algorithms.distancebetweenpoints.DistanceBetweenPointsService;
import static org.junit.Assert.assertEquals;
public class DistanceBetweenPointsServiceUnitTest {
private DistanceBetweenPointsService service = new DistanceBetweenPointsService();
@Test
public void givenTwoPoints_whenCalculateDistanceByFormula_thenCorrect() {
double x1 = 3;
double y1 = 4;
double x2 = 7;
double y2 = 1;
double distance = service.calculateDistanceBetweenPoints(x1, y1, x2, y2);
assertEquals(distance, 5, 0.001);
}
@Test
public void givenTwoPoints_whenCalculateDistanceWithHypot_thenCorrect() {
double x1 = 3;
double y1 = 4;
double x2 = 7;
double y2 = 1;
double distance = service.calculateDistanceBetweenPointsWithHypot(x1, y1, x2, y2);
assertEquals(distance, 5, 0.001);
}
@Test
public void givenTwoPoints_whenCalculateDistanceWithPoint2D_thenCorrect() {
double x1 = 3;
double y1 = 4;
double x2 = 7;
double y2 = 1;
double distance = service.calculateDistanceBetweenPointsWithPoint2D(x1, y1, x2, y2);
assertEquals(distance, 5, 0.001);
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.algorithms.rectanglesoverlap;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import org.junit.Test;
import com.baeldung.algorithms.rectanglesoverlap.Point;
import com.baeldung.algorithms.rectanglesoverlap.Rectangle;
public class RectangleUnitTest {
@Test
public void givenTwoOverlappingRectangles_whenisOverlappingCalled_shouldReturnTrue() {
Rectangle rectangle1 = new Rectangle(new Point(2, 1), new Point(4, 3));
Rectangle rectangle2 = new Rectangle(new Point(1, 1), new Point(6, 4));
assertTrue(rectangle1.isOverlapping(rectangle2));
rectangle1 = new Rectangle(new Point(-5, -2), new Point(2, 3));
rectangle2 = new Rectangle(new Point(-2, -1), new Point(5, 2));
assertTrue(rectangle1.isOverlapping(rectangle2));
rectangle1 = new Rectangle(new Point(-5, 1), new Point(2, 4));
rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, 5));
assertTrue(rectangle1.isOverlapping(rectangle2));
}
@Test
public void givenTwoNonOverlappingRectangles_whenisOverlappingCalled_shouldReturnFalse() {
Rectangle rectangle1 = new Rectangle(new Point(-5, 1), new Point(-3, 4));
Rectangle rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, 5));
assertFalse(rectangle1.isOverlapping(rectangle2));
rectangle1 = new Rectangle(new Point(-5, 1), new Point(3, 4));
rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, -1));
assertFalse(rectangle1.isOverlapping(rectangle2));
rectangle1 = new Rectangle(new Point(-2, 1), new Point(0, 3));
rectangle2 = new Rectangle(new Point(3, 1), new Point(5, 4));
assertFalse(rectangle1.isOverlapping(rectangle2));
}
}

View File

@ -4,8 +4,9 @@
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>
<artifactId>apache-avro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Apache Avro</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

View File

@ -3,3 +3,4 @@
- [Apache CXF Support for RESTful Web Services](http://www.baeldung.com/apache-cxf-rest-api)
- [A Guide to Apache CXF with Spring](http://www.baeldung.com/apache-cxf-with-spring)
- [Introduction to Apache CXF](http://www.baeldung.com/introduction-to-apache-cxf)
- [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse)

View File

@ -20,7 +20,7 @@
</properties>
<build>
<finalName>${artifactId}</finalName>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>net.wasdev.wlp.maven.plugins</groupId>

1
aws/.gitignore vendored
View File

@ -1 +1,2 @@
/target/
.idea/

View File

@ -0,0 +1,184 @@
package com.baeldung.rds;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.rds.AmazonRDS;
import com.amazonaws.services.rds.AmazonRDSClientBuilder;
import com.amazonaws.services.rds.model.*;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import java.util.logging.Logger;
public class AWSRDSService {
final static Logger logger = Logger.getLogger(AWSRDSService.class.getName());
private AWSCredentialsProvider credentials;
private AmazonRDS amazonRDS;
private String db_username;
private String db_password;
private String db_database;
private String db_hostname;
/*
* User access key and secret key must be set before execute any operation.
* Follow the link on how to get the user access and secret key
* https://aws.amazon.com/blogs/security/wheres-my-secret-access-key/
* **/
public AWSRDSService() throws IOException {
//Init RDS client with credentials and region.
credentials = new
AWSStaticCredentialsProvider(new
BasicAWSCredentials("<ACCESS_KEY>",
"<SECRET_KEY>"));
amazonRDS = AmazonRDSClientBuilder.standard().withCredentials(credentials)
.withRegion(Regions.AP_SOUTHEAST_2).build();
Properties prop = new Properties();
InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties");
prop.load(input);
db_username = prop.getProperty("db_username");
db_password = prop.getProperty("db_password");
db_database = prop.getProperty("db_database");
}
public AWSRDSService(AmazonRDS amazonRDS){
this.amazonRDS = amazonRDS;
}
/**
* create the RDS instance.
* After instance creation, update the db_hostname with endpoint in db.properties.
* */
public String launchInstance() {
String identifier = "";
CreateDBInstanceRequest request = new CreateDBInstanceRequest();
// RDS instance name
request.setDBInstanceIdentifier("Sydney");
request.setEngine("postgres");
request.setMultiAZ(false);
request.setMasterUsername(db_username);
request.setMasterUserPassword(db_password);
request.setDBName(db_database);
request.setStorageType("gp2");
request.setAllocatedStorage(10);
DBInstance instance = amazonRDS.createDBInstance(request);
// Information about the new RDS instance
identifier = instance.getDBInstanceIdentifier();
String status = instance.getDBInstanceStatus();
Endpoint endpoint = instance.getEndpoint();
String endpoint_url = "Endpoint URL not available yet.";
if (endpoint != null) {
endpoint_url = endpoint.toString();
}
logger.info(identifier + "\t" + status);
logger.info(endpoint_url);
return identifier;
}
// Describe DB instances
public void listInstances() {
DescribeDBInstancesResult result = amazonRDS.describeDBInstances();
List<DBInstance> instances = result.getDBInstances();
for (DBInstance instance : instances) {
// Information about each RDS instance
String identifier = instance.getDBInstanceIdentifier();
String engine = instance.getEngine();
String status = instance.getDBInstanceStatus();
Endpoint endpoint = instance.getEndpoint();
String endpoint_url = "Endpoint URL not available yet.";
if (endpoint != null) {
endpoint_url = endpoint.toString();
}
logger.info(identifier + "\t" + engine + "\t" + status);
logger.info("\t" + endpoint_url);
}
}
//Delete RDS instance
public void terminateInstance(String identifier) {
DeleteDBInstanceRequest request = new DeleteDBInstanceRequest();
request.setDBInstanceIdentifier(identifier);
request.setSkipFinalSnapshot(true);
// Delete the RDS instance
DBInstance instance = amazonRDS.deleteDBInstance(request);
// Information about the RDS instance being deleted
String status = instance.getDBInstanceStatus();
Endpoint endpoint = instance.getEndpoint();
String endpoint_url = "Endpoint URL not available yet.";
if (endpoint != null) {
endpoint_url = endpoint.toString();
}
logger.info(identifier + "\t" + status);
logger.info(endpoint_url);
}
public void runJdbcTests() throws SQLException, IOException {
// Getting database properties from db.properties
Properties prop = new Properties();
InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties");
prop.load(input);
db_hostname = prop.getProperty("db_hostname");
String jdbc_url = "jdbc:postgresql://" + db_hostname + ":5432/" + db_database;
// Create a connection using the JDBC driver
try (Connection conn = DriverManager.getConnection(jdbc_url, db_username, db_password)) {
// Create the test table if not exists
Statement statement = conn.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS jdbc_test (id SERIAL PRIMARY KEY, content VARCHAR(80))";
statement.executeUpdate(sql);
// Do some INSERT
PreparedStatement preparedStatement = conn.prepareStatement("INSERT INTO jdbc_test (content) VALUES (?)");
String content = "" + UUID.randomUUID();
preparedStatement.setString(1, content);
preparedStatement.executeUpdate();
logger.info("INSERT: " + content);
// Do some SELECT
sql = "SELECT * FROM jdbc_test";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
String count = resultSet.getString("content");
logger.info("Total Records: " + count);
}
}
}
public static void main(String[] args) throws IOException, SQLException {
AWSRDSService awsrdsService = new AWSRDSService();
String instanceName = awsrdsService.launchInstance();
//Add some wait for instance creation.
awsrdsService.listInstances();
awsrdsService.runJdbcTests();
awsrdsService.terminateInstance(instanceName);
}
}

View File

@ -0,0 +1,4 @@
db_hostname=<RDS EndPoint>
db_username=username
db_password=password
db_database=mydb

View File

@ -29,3 +29,6 @@
- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic)
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
- [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time)
- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone)
- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance)
- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects)

View File

@ -24,3 +24,5 @@
- [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional)
- [Java 9 java.lang.Module API](http://www.baeldung.com/java-9-module-api)
- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)

View File

@ -48,7 +48,7 @@ class ProcessUnderstandingTest {
}
//@Test - windows specific
public void givenSubProcess_thenStartSuccessIsAlive() throws IOException {
public void givenSubProcess_whenStarted_thenStartSuccessIsAlive() throws IOException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
assertTrue(builder.start().isAlive());
}
@ -75,7 +75,7 @@ class ProcessUnderstandingTest {
}
//@Test - windows specific
public void givenSubProcess_checkAlive() throws IOException, InterruptedException {
public void givenSubProcess_whenDestroyed_thenCheckIfAlive() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
Thread.sleep(10000);

View File

@ -43,3 +43,9 @@
- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections)
- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list)
- [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe)
- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [](https://www.baeldung.com/java-hashset-arraylist-contains-performance)

View File

@ -0,0 +1,77 @@
package com.baeldung.performance;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.*;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 10)
public class ArrayListBenchmark {
@State(Scope.Thread)
public static class MyState {
List<Employee> employeeList = new ArrayList<>();
//LinkedList<Employee> employeeList = new LinkedList<>();
long iterations = 100000;
Employee employee = new Employee(100L, "Harry");
int employeeIndex = -1;
@Setup(Level.Trial)
public void setUp() {
for (long i = 0; i < iterations; i++) {
employeeList.add(new Employee(i, "John"));
}
employeeList.add(employee);
employeeIndex = employeeList.indexOf(employee);
}
}
@Benchmark
public void testAddAt(ArrayListBenchmark.MyState state) {
state.employeeList.add((int) (state.iterations), new Employee(state.iterations, "John"));
}
@Benchmark
public boolean testContains(ArrayListBenchmark.MyState state) {
return state.employeeList.contains(state.employee);
}
@Benchmark
public int testIndexOf(ArrayListBenchmark.MyState state) {
return state.employeeList.indexOf(state.employee);
}
@Benchmark
public Employee testGet(ArrayListBenchmark.MyState state) {
return state.employeeList.get(state.employeeIndex);
}
@Benchmark
public boolean testRemove(ArrayListBenchmark.MyState state) {
return state.employeeList.remove(state.employee);
}
// @Benchmark
// public void testAdd(ArrayListBenchmark.MyState state) {
// state.employeeList.add(new Employee(state.iterations + 1, "John"));
// }
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(ArrayListBenchmark.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@ -0,0 +1,78 @@
package com.baeldung.performance;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 10)
public class CopyOnWriteBenchmark {
@State(Scope.Thread)
public static class MyState {
CopyOnWriteArrayList<Employee> employeeList = new CopyOnWriteArrayList<>();
long iterations = 100000;
Employee employee = new Employee(100L, "Harry");
int employeeIndex = -1;
@Setup(Level.Trial)
public void setUp() {
for (long i = 0; i < iterations; i++) {
employeeList.add(new Employee(i, "John"));
}
employeeList.add(employee);
employeeIndex = employeeList.indexOf(employee);
}
}
@Benchmark
public void testAdd(CopyOnWriteBenchmark.MyState state) {
state.employeeList.add(new Employee(state.iterations + 1, "John"));
}
@Benchmark
public void testAddAt(CopyOnWriteBenchmark.MyState state) {
state.employeeList.add((int) (state.iterations), new Employee(state.iterations, "John"));
}
@Benchmark
public boolean testContains(CopyOnWriteBenchmark.MyState state) {
return state.employeeList.contains(state.employee);
}
@Benchmark
public int testIndexOf(CopyOnWriteBenchmark.MyState state) {
return state.employeeList.indexOf(state.employee);
}
@Benchmark
public Employee testGet(CopyOnWriteBenchmark.MyState state) {
return state.employeeList.get(state.employeeIndex);
}
@Benchmark
public boolean testRemove(CopyOnWriteBenchmark.MyState state) {
return state.employeeList.remove(state.employee);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(CopyOnWriteBenchmark.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@ -10,6 +10,22 @@ public class Employee {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;

View File

@ -0,0 +1,73 @@
package com.baeldung.performance;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.*;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 10)
public class HashMapBenchmark {
@State(Scope.Thread)
public static class MyState {
Map<Long, Employee> employeeMap = new HashMap<>();
//LinkedHashMap<Long, Employee> employeeMap = new LinkedHashMap<>();
//IdentityHashMap<Long, Employee> employeeMap = new IdentityHashMap<>();
//WeakHashMap<Long, Employee> employeeMap = new WeakHashMap<>();
//ConcurrentHashMap<Long, Employee> employeeMap = new ConcurrentHashMap<>();
//ConcurrentSkipListMap<Long, Employee> employeeMap = new ConcurrentSkipListMap <>();
// TreeMap
long iterations = 100000;
Employee employee = new Employee(100L, "Harry");
int employeeIndex = -1;
@Setup(Level.Trial)
public void setUp() {
for (long i = 0; i < iterations; i++) {
employeeMap.put(i, new Employee(i, "John"));
}
//employeeMap.put(iterations, employee);
}
}
@Benchmark
public Employee testGet(HashMapBenchmark.MyState state) {
return state.employeeMap.get(state.iterations);
}
@Benchmark
public Employee testRemove(HashMapBenchmark.MyState state) {
return state.employeeMap.remove(state.iterations);
}
@Benchmark
public Employee testPut(HashMapBenchmark.MyState state) {
return state.employeeMap.put(state.employee.getId(), state.employee);
}
@Benchmark
public Boolean testContainsKey(HashMapBenchmark.MyState state) {
return state.employeeMap.containsKey(state.employee.getId());
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(HashMapBenchmark.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@ -0,0 +1,66 @@
package com.baeldung.performance;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 10)
public class SetBenchMark {
@State(Scope.Thread)
public static class MyState {
//Set<Employee> employeeSet = new HashSet<>();
LinkedHashSet<Employee> employeeSet = new LinkedHashSet<>();
//ConcurrentSkipListSet<Employee> employeeSet = new ConcurrentSkipListSet <>();
// TreeSet 
long iterations = 1000;
Employee employee = new Employee(100L, "Harry");
@Setup(Level.Trial)
public void setUp() {
for (long i = 0; i < iterations; i++) {
employeeSet.add(new Employee(i, "John"));
}
//employeeSet.add(employee);
}
}
@Benchmark
public boolean testAdd(SetBenchMark.MyState state) {
return state.employeeSet.add(state.employee);
}
@Benchmark
public Boolean testContains(SetBenchMark.MyState state) {
return state.employeeSet.contains(state.employee);
}
@Benchmark
public boolean testRemove(SetBenchMark.MyState state) {
return state.employeeSet.remove(state.employee);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(SetBenchMark.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@ -30,3 +30,4 @@
- [Download a File From an URL in Java](http://www.baeldung.com/java-download-file)
- [Create a Symbolic Link with Java](http://www.baeldung.com/java-symlink)
- [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)

View File

@ -5,4 +5,5 @@
### Relevant Articles:
- [Introduction to JDBC](http://www.baeldung.com/java-jdbc)
- [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing)
- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset)
- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset)
- [A Simple Guide to Connection Pooling in Java](https://www.baeldung.com/java-connection-pooling)

View File

@ -145,3 +145,9 @@
- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions)
- [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods)
- [Differences Between Final, Finally and Finalize in Java](https://www.baeldung.com/java-final-finally-finalize)
- [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding)
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
- [Difference Between Throw and Throws in Java](https://www.baeldung.com/java-throw-throws)
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)

View File

@ -0,0 +1,23 @@
package com.baeldung.synthetic;
import java.util.Comparator;
/**
* Class which contains a synthetic bridge method.
*
* @author Donato Rimenti
*
*/
public class BridgeMethodDemo implements Comparator<Integer> {
/*
* (non-Javadoc)
*
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Integer o1, Integer o2) {
return 0;
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.synthetic;
/**
* Wrapper for a class which contains a synthetic constructor.
*
* @author Donato Rimenti
*
*/
public class SyntheticConstructorDemo {
/**
* We need to instantiate the {@link NestedClass} using a private
* constructor from the enclosing instance in order to generate a synthetic
* constructor.
*/
private NestedClass nestedClass = new NestedClass();
/**
* Class which contains a synthetic constructor.
*
* @author Donato Rimenti
*
*/
class NestedClass {
/**
* In order to generate a synthetic constructor, this class must have a
* private constructor.
*/
private NestedClass() {
}
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.synthetic;
/**
* Wrapper for a class which contains a synthetic field reference to the outer
* class.
*
* @author Donato Rimenti
*
*/
public class SyntheticFieldDemo {
/**
* Class which contains a synthetic field reference to the outer class.
*
* @author Donato Rimenti
*
*/
class NestedClass {
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.synthetic;
/**
* Wrapper for a class which contains two synthetic methods accessors to a
* private field.
*
* @author Donato Rimenti
*
*/
public class SyntheticMethodDemo {
/**
* Class which contains two synthetic methods accessors to a private field.
*
* @author Donato Rimenti
*
*/
class NestedClass {
/**
* Field for which will be generated synthetic methods accessors. It's
* important that this field is private for this purpose.
*/
private String nestedField;
}
/**
* Gets the private nested field. We need to read the nested field in order
* to generate the synthetic getter.
*
* @return the {@link NestedClass#nestedField}
*/
public String getNestedField() {
return new NestedClass().nestedField;
}
/**
* Sets the private nested field. We need to write the nested field in order
* to generate the synthetic setter.
*
* @param nestedField
* the {@link NestedClass#nestedField}
*/
public void setNestedField(String nestedField) {
new NestedClass().nestedField = nestedField;
}
}

View File

@ -0,0 +1,99 @@
package com.baeldung.synthetic;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit test for {@link SyntheticFieldDemo}, {@link SyntheticMethodDemo},
* {@link SyntheticConstructorDemo} and {@link BridgeMethodDemo} classes.
*
* @author Donato Rimenti
*
*/
public class SyntheticUnitTest {
/**
* Tests that the {@link SyntheticMethodDemo.NestedClass} contains two synthetic
* methods.
*/
@Test
public void givenSyntheticMethod_whenIsSinthetic_thenTrue() {
// Checks that the nested class contains exactly two synthetic methods.
Method[] methods = SyntheticMethodDemo.NestedClass.class.getDeclaredMethods();
Assert.assertEquals("This class should contain only two methods", 2, methods.length);
for (Method m : methods) {
System.out.println("Method: " + m.getName() + ", isSynthetic: " + m.isSynthetic());
Assert.assertTrue("All the methods of this class should be synthetic", m.isSynthetic());
}
}
/**
* Tests that {@link SyntheticConstructorDemo.NestedClass} contains a synthetic
* constructor.
*/
@Test
public void givenSyntheticConstructor_whenIsSinthetic_thenTrue() {
// Checks that the nested class contains exactly a synthetic
// constructor.
int syntheticConstructors = 0;
Constructor<?>[] constructors = SyntheticConstructorDemo.NestedClass.class.getDeclaredConstructors();
Assert.assertEquals("This class should contain only two constructors", 2, constructors.length);
for (Constructor<?> c : constructors) {
System.out.println("Constructor: " + c.getName() + ", isSynthetic: " + c.isSynthetic());
// Counts the synthetic constructors.
if (c.isSynthetic()) {
syntheticConstructors++;
}
}
// Checks that there's exactly one synthetic constructor.
Assert.assertEquals(1, syntheticConstructors);
}
/**
* Tests that {@link SyntheticFieldDemo.NestedClass} contains a synthetic field.
*/
@Test
public void givenSyntheticField_whenIsSinthetic_thenTrue() {
// This class should contain exactly one synthetic field.
Field[] fields = SyntheticFieldDemo.NestedClass.class.getDeclaredFields();
Assert.assertEquals("This class should contain only one field", 1, fields.length);
for (Field f : fields) {
System.out.println("Field: " + f.getName() + ", isSynthetic: " + f.isSynthetic());
Assert.assertTrue("All the fields of this class should be synthetic", f.isSynthetic());
}
}
/**
* Tests that {@link BridgeMethodDemo} contains a synthetic bridge method.
*/
@Test
public void givenBridgeMethod_whenIsBridge_thenTrue() {
// This class should contain exactly one synthetic bridge method.
int syntheticMethods = 0;
Method[] methods = BridgeMethodDemo.class.getDeclaredMethods();
for (Method m : methods) {
System.out.println(
"Method: " + m.getName() + ", isSynthetic: " + m.isSynthetic() + ", isBridge: " + m.isBridge());
// Counts the synthetic methods and checks that they are also bridge
// methods.
if (m.isSynthetic()) {
syntheticMethods++;
Assert.assertTrue("The synthetic method in this class should also be a bridge method", m.isBridge());
}
}
// Checks that there's exactly one synthetic bridge method.
Assert.assertEquals("There should be exactly 1 synthetic bridge method in this class", 1, syntheticMethods);
}
}

View File

@ -38,3 +38,7 @@
- [Reflection with Kotlin](http://www.baeldung.com/kotlin-reflection)
- [Get a Random Number in Kotlin](http://www.baeldung.com/kotlin-random-number)
- [Idiomatic Logging in Kotlin](http://www.baeldung.com/kotlin-logging)
- [Kotlin Constructors](https://www.baeldung.com/kotlin-constructors)
- [Creational Design Patterns in Kotlin: Builder](https://www.baeldung.com/kotlin-builder-pattern)
- [Kotlin Nested and Inner Classes](https://www.baeldung.com/kotlin-inner-classes)
- [Guide to the Kotlin Exposed Framework](https://www.baeldung.com/kotlin-exposed-persistence)

View File

@ -87,6 +87,26 @@
<artifactId>h2</artifactId>
<version>${h2database.version}</version>
</dependency>
<dependency>
<groupId>com.github.kittinunf.fuel</groupId>
<artifactId>fuel</artifactId>
<version>${fuel.version}</version>
</dependency>
<dependency>
<groupId>com.github.kittinunf.fuel</groupId>
<artifactId>fuel-gson</artifactId>
<version>${fuel.version}</version>
</dependency>
<dependency>
<groupId>com.github.kittinunf.fuel</groupId>
<artifactId>fuel-rxjava</artifactId>
<version>${fuel.version}</version>
</dependency>
<dependency>
<groupId>com.github.kittinunf.fuel</groupId>
<artifactId>fuel-coroutines</artifactId>
<version>${fuel.version}</version>
</dependency>
</dependencies>
<properties>
@ -100,6 +120,7 @@
<assertj.version>3.10.0</assertj.version>
<h2database.version>1.4.197</h2database.version>
<exposed.version>0.10.4</exposed.version>
<fuel.version>1.15.0</fuel.version>
</properties>
</project>
</project>

View File

@ -0,0 +1,11 @@
package com.baeldung.fuel
import com.github.kittinunf.fuel.core.Request
fun tokenInterceptor() = {
next: (Request) -> Request ->
{ req: Request ->
req.header(mapOf("Authorization" to "Bearer AbCdEf123456"))
next(req)
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.fuel
import com.github.kittinunf.fuel.core.ResponseDeserializable
import com.google.gson.Gson
data class Post(var userId:Int,
var id:Int,
var title:String,
var body:String){
class Deserializer : ResponseDeserializable<Array<Post>> {
override fun deserialize(content: String): Array<Post> = Gson().fromJson(content, Array<Post>::class.java)
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.fuel
import com.github.kittinunf.fuel.core.Method
import com.github.kittinunf.fuel.util.FuelRouting
sealed class PostRoutingAPI : FuelRouting {
override val basePath = "https://jsonplaceholder.typicode.com"
class posts(val id: String, override val body: String?): PostRoutingAPI()
class comments(val postId: String, override val body: String?): PostRoutingAPI()
override val method: Method
get() {
return when(this) {
is PostRoutingAPI.posts -> Method.GET
is PostRoutingAPI.comments -> Method.GET
}
}
override val path: String
get() {
return when(this) {
is PostRoutingAPI.posts -> "/posts"
is PostRoutingAPI.comments -> "/comments"
}
}
override val params: List<Pair<String, Any?>>?
get() {
return when(this) {
is PostRoutingAPI.posts -> listOf("id" to this.id)
is PostRoutingAPI.comments -> listOf("postId" to this.postId)
}
}
override val headers: Map<String, String>?
get() {
return null
}
}

View File

@ -93,6 +93,7 @@ internal class BuilderPatternUnitTest {
Assertions.assertNull(foodOrder.fish)
}
@Test
fun whenBuildingFoodOrderApplySettingValues_thenFieldsNotNull() {

View File

@ -0,0 +1,286 @@
package com.baeldung.fuel
import awaitObjectResult
import awaitStringResponse
import com.github.kittinunf.fuel.Fuel
import com.github.kittinunf.fuel.core.FuelManager
import com.github.kittinunf.fuel.core.Request
import com.github.kittinunf.fuel.core.interceptors.cUrlLoggingRequestInterceptor
import com.github.kittinunf.fuel.gson.responseObject
import com.github.kittinunf.fuel.httpGet
import com.github.kittinunf.fuel.rx.rx_object
import com.google.gson.Gson
import kotlinx.coroutines.experimental.runBlocking
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import java.io.File
import java.util.concurrent.CountDownLatch
internal class FuelHttpUnitTest {
@Test
fun whenMakingAsyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
val latch = CountDownLatch(1)
"http://httpbin.org/get".httpGet().response{
request, response, result ->
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
latch.countDown()
}
latch.await()
}
@Test
fun whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
val (request, response, result) = "http://httpbin.org/get".httpGet().response()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
@Test
fun whenMakingSyncHttpGetURLEncodedRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
val (request, response, result) =
"https://jsonplaceholder.typicode.com/posts"
.httpGet(listOf("id" to "1")).response()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
@Test
fun whenMakingAsyncHttpPostRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
val latch = CountDownLatch(1)
Fuel.post("http://httpbin.org/post").response{
request, response, result ->
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
latch.countDown()
}
latch.await()
}
@Test
fun whenMakingSyncHttpPostRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
val (request, response, result) = Fuel.post("http://httpbin.org/post").response()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
@Test
fun whenMakingSyncHttpPostRequestwithBody_thenResponseNotNullAndErrorNullAndStatusCode200() {
val (request, response, result) = Fuel.post("https://jsonplaceholder.typicode.com/posts")
.body("{ \"title\" : \"foo\",\"body\" : \"bar\",\"id\" : \"1\"}")
.response()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(201,response.statusCode)
}
@Test
fun givenFuelInstance_whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
FuelManager.instance.basePath = "http://httpbin.org"
FuelManager.instance.baseHeaders = mapOf("OS" to "macOS High Sierra")
FuelManager.instance.addRequestInterceptor(cUrlLoggingRequestInterceptor())
FuelManager.instance.addRequestInterceptor(tokenInterceptor())
val (request, response, result) = "/get"
.httpGet().response()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
@Test
fun givenInterceptors_whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
FuelManager.instance.basePath = "http://httpbin.org"
FuelManager.instance.addRequestInterceptor(cUrlLoggingRequestInterceptor())
FuelManager.instance.addRequestInterceptor(tokenInterceptor())
val (request, response, result) = "/get"
.httpGet().response()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
@Test
fun whenDownloadFile_thenCreateFileResponseNotNullAndErrorNullAndStatusCode200() {
Fuel.download("http://httpbin.org/bytes/32768").destination { response, url ->
File.createTempFile("temp", ".tmp")
}.response{
request, response, result ->
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
}
@Test
fun whenDownloadFilewithProgressHandler_thenCreateFileResponseNotNullAndErrorNullAndStatusCode200() {
val (request, response, result) = Fuel.download("http://httpbin.org/bytes/327680")
.destination { response, url -> File.createTempFile("temp", ".tmp")
}.progress { readBytes, totalBytes ->
val progress = readBytes.toFloat() / totalBytes.toFloat()
}.response ()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
@Test
fun whenMakeGetRequest_thenDeserializePostwithGson() {
val latch = CountDownLatch(1)
"https://jsonplaceholder.typicode.com/posts/1".httpGet().responseObject<Post> { _,_, result ->
val post = result.component1()
Assertions.assertEquals(1, post?.userId)
latch.countDown()
}
latch.await()
}
@Test
fun whenMakePOSTRequest_thenSerializePostwithGson() {
val post = Post(1,1, "Lorem", "Lorem Ipse dolor sit amet")
val (request, response, result) = Fuel.post("https://jsonplaceholder.typicode.com/posts")
.header("Content-Type" to "application/json")
.body(Gson().toJson(post).toString())
.response()
Assertions.assertEquals(201,response.statusCode)
}
@Test
fun whenMakeGETRequestWithRxJava_thenDeserializePostwithGson() {
val latch = CountDownLatch(1)
"https://jsonplaceholder.typicode.com/posts?id=1"
.httpGet().rx_object(Post.Deserializer()).subscribe{
res, throwable ->
val post = res.component1()
Assertions.assertEquals(1, post?.get(0)?.userId)
latch.countDown()
}
latch.await()
}
@Test
fun whenMakeGETRequestUsingCoroutines_thenResponseStatusCode200() {
runBlocking {
val (request, response, result) = Fuel.get("http://httpbin.org/get").awaitStringResponse()
result.fold({ data ->
Assertions.assertEquals(200, response.statusCode)
}, { error -> })
}
}
@Test
fun whenMakeGETRequestUsingCoroutines_thenDeserializeResponse() {
runBlocking {
Fuel.get("https://jsonplaceholder.typicode.com/posts?id=1").awaitObjectResult(Post.Deserializer())
.fold({ data ->
Assertions.assertEquals(1, data.get(0).userId)
}, { error -> })
}
}
@Test
fun whenMakeGETPostRequestUsingRoutingAPI_thenDeserializeResponse() {
val latch = CountDownLatch(1)
Fuel.request(PostRoutingAPI.posts("1",null))
.responseObject(Post.Deserializer()) {
request, response, result ->
Assertions.assertEquals(1, result.component1()?.get(0)?.userId)
latch.countDown()
}
latch.await()
}
@Test
fun whenMakeGETCommentRequestUsingRoutingAPI_thenResponseStausCode200() {
val latch = CountDownLatch(1)
Fuel.request(PostRoutingAPI.comments("1",null))
.responseString { request, response, result ->
Assertions.assertEquals(200, response.statusCode)
latch.countDown()
}
latch.await()
}
}

View File

@ -3,11 +3,11 @@
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>couchbase-sdk</artifactId>
<artifactId>couchbase</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>couchbase</name>
<description>Couchbase SDK Tutorials</description>
<description>Couchbase Tutorials</description>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -48,12 +48,18 @@
<artifactId>poi-ooxml</artifactId>
<version>${apache-poi-version}</version>
</dependency>
<dependency>
<groupId>org.optaplanner</groupId>
<artifactId>optaplanner-core</artifactId>
<version>${opta-planner-version}</version>
</dependency>
</dependencies>
<properties>
<http-component-version>4.4.6</http-component-version>
<drools-version>7.4.1.Final</drools-version>
<apache-poi-version>3.13</apache-poi-version>
<opta-planner-version>7.10.0.Final</opta-planner-version>
</properties>
</project>

View File

@ -0,0 +1,63 @@
package com.baeldung.drools.optaplanner;
import java.util.ArrayList;
import java.util.List;
import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty;
import org.optaplanner.core.api.domain.solution.PlanningScore;
import org.optaplanner.core.api.domain.solution.PlanningSolution;
import org.optaplanner.core.api.domain.solution.drools.ProblemFactCollectionProperty;
import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@PlanningSolution
public class CourseSchedule {
Logger logger = LoggerFactory.getLogger("CourseSchedule");
private List<Integer> roomList;
private List<Integer> periodList;
private List<Lecture> lectureList;
private HardSoftScore score;
public CourseSchedule(){
roomList = new ArrayList<>();
periodList = new ArrayList<>();
lectureList = new ArrayList<>();
}
@ValueRangeProvider(id = "availableRooms")
@ProblemFactCollectionProperty
public List<Integer> getRoomList() {
return roomList;
}
@ValueRangeProvider(id = "availablePeriods")
@ProblemFactCollectionProperty
public List<Integer> getPeriodList() {
return periodList;
}
@PlanningEntityCollectionProperty
public List<Lecture> getLectureList() {
return lectureList;
}
@PlanningScore
public HardSoftScore getScore() {
return score;
}
public void setScore(HardSoftScore score) {
this.score = score;
}
public void printCourseSchedule() {
lectureList.stream()
.map(c -> "Lecture in Room " + c.getRoomNumber().toString() + " during Period " + c.getPeriod().toString())
.forEach(k -> logger.info(k));
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.drools.optaplanner;
import org.optaplanner.core.api.domain.entity.PlanningEntity;
import org.optaplanner.core.api.domain.variable.PlanningVariable;
@PlanningEntity
public class Lecture {
private Integer roomNumber;
private Integer period;
@PlanningVariable(valueRangeProviderRefs = {"availablePeriods"})
public Integer getPeriod() {
return period;
}
@PlanningVariable(valueRangeProviderRefs = {"availableRooms"})
public Integer getRoomNumber() {
return roomNumber;
}
public void setPeriod(Integer period) {
this.period = period;
}
public void setRoomNumber(Integer roomNumber) {
this.roomNumber = roomNumber;
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.drools.optaplanner;
import java.util.HashSet;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
import org.optaplanner.core.impl.score.director.easy.EasyScoreCalculator;
public class ScoreCalculator implements EasyScoreCalculator<CourseSchedule> {
@Override
public Score calculateScore(CourseSchedule courseSchedule) {
int hardScore = 0;
int softScore = 0;
HashSet<String> occupiedRooms = new HashSet<>();
for (Lecture lecture : courseSchedule.getLectureList()) {
if(lecture.getPeriod() != null && lecture.getRoomNumber() != null) {
String roomInUse = lecture.getPeriod().toString() + ":" + lecture.getRoomNumber().toString();
if (occupiedRooms.contains(roomInUse)) {
hardScore += -1;
} else {
occupiedRooms.add(roomInUse);
}
} else {
hardScore += -1;
}
}
return HardSoftScore.valueOf(hardScore, softScore);
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.drools.optaplanner
import com.baeldung.drools.optaplanner.Lecture;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScoreHolder;
global HardSoftScoreHolder scoreHolder;
rule "noNullRoomPeriod"
when
Lecture( roomNumber == null );
Lecture( period == null );
then
scoreHolder.addHardConstraintMatch(kcontext, -1);
end

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<solver>
<scanAnnotatedClasses/>
<scoreDirectorFactory>
<scoreDrl>courseSchedule.drl</scoreDrl>
</scoreDirectorFactory>
<termination>
<secondsSpentLimit>10</secondsSpentLimit>
</termination>
</solver>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<solver>
<scanAnnotatedClasses/>
<scoreDirectorFactory>
<easyScoreCalculatorClass>com.baeldung.drools.optaplanner.ScoreCalculator</easyScoreCalculatorClass>
</scoreDirectorFactory>
<termination>
<secondsSpentLimit>10</secondsSpentLimit>
</termination>
</solver>

View File

@ -0,0 +1,49 @@
package com.baeldung.drools.optaplanner;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.optaplanner.core.api.solver.Solver;
import org.optaplanner.core.api.solver.SolverFactory;
public class OptaPlannerUnitTest {
static CourseSchedule unsolvedCourseSchedule;
@BeforeAll
public static void setUp() {
unsolvedCourseSchedule = new CourseSchedule();
for(int i = 0; i < 10; i++){
unsolvedCourseSchedule.getLectureList().add(new Lecture());
}
unsolvedCourseSchedule.getPeriodList().addAll(Arrays.asList(new Integer[] { 1, 2, 3 }));
unsolvedCourseSchedule.getRoomList().addAll(Arrays.asList(new Integer[] { 1, 2 }));
}
@Test
public void test_whenCustomJavaSolver() {
SolverFactory<CourseSchedule> solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfiguration.xml");
Solver<CourseSchedule> solver = solverFactory.buildSolver();
CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule);
Assert.assertNotNull(solvedCourseSchedule.getScore());
Assert.assertEquals(-4, solvedCourseSchedule.getScore().getHardScore());
}
@Test
public void test_whenDroolsSolver() {
SolverFactory<CourseSchedule> solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfigDrools.xml");
Solver<CourseSchedule> solver = solverFactory.buildSolver();
CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule);
Assert.assertNotNull(solvedCourseSchedule.getScore());
Assert.assertEquals(0, solvedCourseSchedule.getScore().getHardScore());
}
}

View File

@ -16,7 +16,6 @@
<groupId>org.wildfly</groupId>
<artifactId>wildfly-ejb-client-bom</artifactId>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.baeldung.ejb</groupId>

View File

@ -17,7 +17,6 @@
<modules>
<module>ejb-remote</module>
<module>ejb-client</module>
<module>ejb-session-beans</module>
</modules>

View File

@ -2,9 +2,10 @@
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.wildfly</groupId>
<artifactId>wildfly-example</artifactId>
<artifactId>wildfly</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>wildfly</name>
<parent>
<groupId>com.baeldung.ejb</groupId>

View File

@ -1,8 +1,9 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>widlfly-mdb</artifactId>
<artifactId>wildfly-mdb</artifactId>
<name>wildfly-mdb</name>
<parent>
<groupId>com.baeldung.wildfly</groupId>
<artifactId>wildfly-example</artifactId>

View File

@ -1 +0,0 @@
## Relevant articles:

View File

@ -1,25 +0,0 @@
package com.baeldung.enterprise.patterns.front.controller.filters;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class AuditFilter extends BaseFilter {
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain
) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpSession session = httpServletRequest.getSession(false);
if (session != null && session.getAttribute("username") != null) {
request.setAttribute("username", session.getAttribute("username"));
}
chain.doFilter(request, response);
}
}

View File

@ -1,23 +0,0 @@
package com.baeldung.enterprise.patterns.front.controller.filters;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(servletNames = "front-controller")
public class VisitorCounterFilter extends BaseFilter {
private int counter;
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain
) throws IOException, ServletException {
request.setAttribute("counter", ++counter);
chain.doFilter(request, response);
}
}

View File

@ -1,19 +0,0 @@
<?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.enterprise.patterns</groupId>
<artifactId>enterprise-patterns-parent</artifactId>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modules>
<module>spring-dispatcher-servlet</module>
</modules>
</project>

View File

@ -3,7 +3,8 @@
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.feign</groupId>
<artifactId>feign-client</artifactId>
<artifactId>feign</artifactId>
<name>feign</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -6,10 +6,11 @@
<!-- POM file generated with GWT webAppCreator -->
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>google_web_toolkit</artifactId>
<artifactId>google-web-toolkit</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>google-web-toolkit</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>

View File

@ -1,11 +1,11 @@
<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>grpc</groupId>
<artifactId>grpc-demo</artifactId>
<artifactId>grpc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>grpc</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>

View File

@ -7,3 +7,4 @@
- [Gson Deserialization Cookbook](http://www.baeldung.com/gson-deserialization-guide)
- [Jackson vs Gson](http://www.baeldung.com/jackson-vs-gson)
- [Exclude Fields from Serialization in Gson](http://www.baeldung.com/gson-exclude-fields-serialization)
- [Save Data to a JSON File with Gson](https://www.baeldung.com/gson-save-file)

View File

@ -33,3 +33,4 @@
- [Using Guava CountingOutputStream](http://www.baeldung.com/guava-counting-outputstream)
- [Hamcrest Text Matchers](http://www.baeldung.com/hamcrest-text-matchers)
- [Quick Guide to the Guava RateLimiter](http://www.baeldung.com/guava-rate-limiter)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)

View File

@ -3,9 +3,10 @@
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.stackify</groupId>
<artifactId>java-remote-debugging</artifactId>
<artifactId>remote-debugging</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>remote-debugging</name>
<parent>
<groupId>org.springframework.boot</groupId>

View File

@ -1,2 +1,3 @@
### Relevant Articles:
- [Guide to Hazelcast with Java](http://www.baeldung.com/java-hazelcast)
- [Introduction to Hazelcast Jet](https://www.baeldung.com/hazelcast-jet)

View File

@ -13,3 +13,4 @@
- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking)
- [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa)
- [Optimistic Locking in JPA](http://www.baeldung.com/jpa-optimistic-locking)
- [Hibernate Entity Lifecycle](https://www.baeldung.com/hibernate-entity-lifecycle)

3
intelliJ/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Writing IntelliJ IDEA Plugins](https://www.baeldung.com/intellij-new-custom-plugin)

View File

@ -12,3 +12,4 @@
- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream)
- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices)
- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams)
- [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering)

View File

@ -24,4 +24,5 @@
- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number)
- [Why Use char[] Array Over a String for Storing Passwords in Java?](http://www.baeldung.com/java-storing-passwords)
- [Convert a String to Title Case](http://www.baeldung.com/java-string-title-case)
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
- [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex)

View File

@ -1,8 +1,6 @@
package com.baeldung.string;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertEquals;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -12,35 +10,28 @@ import org.junit.Test;
import com.vdurmont.emoji.EmojiParser;
public class RemovingEmojiFromStringUnitTest {
String text = "la conférence, commencera à 10 heures 😅";
String text = "la conférence, commencera à 10 heures 😅";
String regex = "[^\\p{L}\\p{N}\\p{P}\\p{Z}]";
@Test
public void whenRemoveEmojiUsingLibrary_thenSuccess() {
String result = EmojiParser.removeAllEmojis(text);
System.out.println(result);
assertThat(result, not(containsString("😅")));
assertThat(result, containsString("à"));
assertThat(result, containsString("la"));
assertThat(result, containsString("10"));
assertEquals(result, "la conférence, commencera à 10 heures ");
}
@Test
public void whenReplaceEmojiUsingLibrary_thenSuccess() {
String result = EmojiParser.parseToAliases(text);
System.out.println(result);
assertThat(result, not(containsString("😅")));
assertThat(result, containsString("sweat_smile"));
assertEquals(result, "la conférence, commencera à 10 heures :sweat_smile:");
}
@Test
public void whenRemoveEmojiUsingRegex_thenSuccess() {
String result = text.replaceAll(regex, "");
System.out.println(result);
assertThat(result, not(containsString("😅")));
assertThat(result, containsString("à"));
assertThat(result, containsString("la"));
assertThat(result, containsString("10"));
assertEquals(result, "la conférence, commencera à 10 heures ");
}
@Test
@ -50,29 +41,20 @@ public class RemovingEmojiFromStringUnitTest {
String result = matcher.replaceAll("");
System.out.println(result);
assertThat(result, not(containsString("😅")));
assertThat(result, containsString("à"));
assertThat(result, containsString("la"));
assertThat(result, containsString("10"));
assertEquals(result, "la conférence, commencera à 10 heures ");
}
@Test
public void whenRemoveEmojiUsingCodepoints_thenSuccess() {
String result = text.replaceAll("[\\x{0001f300}-\\x{0001f64f}]|[\\x{0001f680}-\\x{0001f6ff}]", "");
System.out.println(result);
assertThat(result, not(containsString("😅")));
assertThat(result, containsString("à"));
assertThat(result, containsString("la"));
assertThat(result, containsString("10"));
assertEquals(result, "la conférence, commencera à 10 heures ");
}
@Test
public void whenRemoveEmojiUsingUnicode_thenSuccess() {
String result = text.replaceAll("[\ud83c\udf00-\ud83d\ude4f]|[\ud83d\ude80-\ud83d\udeff]", "");
System.out.println(result);
assertThat(result, not(containsString("😅")));
assertThat(result, containsString("à"));
assertThat(result, containsString("la"));
assertThat(result, containsString("10"));
assertEquals(result, "la conférence, commencera à 10 heures ");
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.string;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
public class SubstringUnitTest {
String text = "Julia Evans was born on 25-09-1984. She is currently living in the USA (United States of America).";
@Test
public void givenAString_whenUsedStringUtils_ShouldReturnProperSubstring() {
Assert.assertEquals("United States of America", StringUtils.substringBetween(text, "(", ")"));
Assert.assertEquals("the USA (United States of America).", StringUtils.substringAfter(text, "living in "));
Assert.assertEquals("Julia Evans", StringUtils.substringBefore(text, " was born"));
}
@Test
public void givenAString_whenUsedScanner_ShouldReturnProperSubstring() {
try (Scanner scanner = new Scanner(text)) {
scanner.useDelimiter("\\.");
Assert.assertEquals("Julia Evans was born on 25-09-1984", scanner.next());
}
}
@Test
public void givenAString_whenUsedSplit_ShouldReturnProperSubstring() {
String[] sentences = text.split("\\.");
Assert.assertEquals("Julia Evans was born on 25-09-1984", sentences[0]);
}
@Test
public void givenAString_whenUsedRegex_ShouldReturnProperSubstring() {
Pattern pattern = Pattern.compile("\\d{2}\\-\\d{2}-\\d{4}");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
Assert.assertEquals("25-09-1984", matcher.group());
}
}
@Test
public void givenAString_whenUsedSubSequence_ShouldReturnProperSubstring() {
Assert.assertEquals("USA (United States of America)", text.subSequence(67, text.length() - 1));
}
@Test
public void givenAString_whenUsedSubstring_ShouldReturnProperSubstring() {
Assert.assertEquals("USA (United States of America).", text.substring(67));
Assert.assertEquals("USA (United States of America)", text.substring(67, text.length() - 1));
}
@Test
public void givenAString_whenUsedSubstringWithIndexOf_ShouldReturnProperSubstring() {
Assert.assertEquals("United States of America", text.substring(text.indexOf('(') + 1, text.indexOf(')')));
}
}

View File

@ -1,6 +0,0 @@
.classpath
.project
.settings/
target/

View File

@ -1,44 +0,0 @@
<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>javaxval</artifactId>
<version>0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>5.2.1.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
</dependencies>
</project>

View File

@ -384,10 +384,6 @@
</profile>
</profiles>
<prerequisites>
<maven>${maven.min.version}</maven>
</prerequisites>
<repositories>
<repository>
<id>bintray-mvc-spec-maven</id>

View File

@ -1 +1,2 @@
- [Jersey Filters and Interceptors] (http://www.baeldung.com/jersey-filters-interceptors)
- [Jersey Filters and Interceptors](http://www.baeldung.com/jersey-filters-interceptors)
- [Jersey MVC Support](https://www.baeldung.com/jersey-mvc)

View File

@ -10,10 +10,10 @@
<relativePath>../../../parent-boot-1</relativePath>
</parent>
<groupId>com.car.app</groupId>
<artifactId>carapp</artifactId>
<artifactId>car-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Carapp</name>
<name>car-app</name>
<prerequisites>
<maven>${maven.version}</maven>

View File

@ -3,10 +3,10 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dealer.app</groupId>
<artifactId>dealerapp</artifactId>
<artifactId>dealer-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Dealerapp</name>
<name>dealer-app</name>
<parent>
<artifactId>parent-boot-1</artifactId>

View File

@ -3,10 +3,10 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gateway</groupId>
<artifactId>gateway</artifactId>
<artifactId>gateway-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Gateway</name>
<name>gateway-app</name>
<parent>
<artifactId>parent-boot-1</artifactId>

View File

@ -412,6 +412,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>${maven-eclipse-plugin.version}</version>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
@ -879,10 +880,6 @@
</profile>
</profiles>
<prerequisites>
<maven>${maven.version}</maven>
</prerequisites>
<properties>
<argLine>-Djava.security.egd=file:/dev/./urandom -Xmx256m</argLine>
<assertj.version>3.6.2</assertj.version>
@ -909,6 +906,7 @@
<mapstruct.version>1.1.0.Final</mapstruct.version>
<maven-enforcer-plugin.version>1.4.1</maven-enforcer-plugin.version>
<maven-resources-plugin.version>3.0.1</maven-resources-plugin.version>
<maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version>
<maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
<maven.version>3.0.0</maven.version>
<metrics-spring.version>3.1.3</metrics-spring.version>

View File

@ -3,10 +3,10 @@
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>io.jsonwebtoken</groupId>
<artifactId>jjwtfun</artifactId>
<artifactId>jjwt</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>jjwtfun</name>
<name>jjwt</name>
<description>Exercising the JJWT</description>
<parent>

View File

@ -19,7 +19,7 @@
</properties>
<build>
<finalName>${artifactId}</finalName>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>net.wasdev.wlp.maven.plugins</groupId>

View File

@ -36,11 +36,6 @@
<version>${jstl.version}</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>

View File

@ -9,3 +9,4 @@
- [Introduction to JsonPath](http://www.baeldung.com/guide-to-jayway-jsonpath)
- [Introduction to JSON-Java (org.json)](http://www.baeldung.com/java-org-json)
- [Overview of JSON Pointer](https://www.baeldung.com/json-pointer)
- [Introduction to the JSON Binding API (JSR 367) in Java](http://www.baeldung.com/java-json-binding-api)

View File

@ -33,7 +33,11 @@
<artifactId>json</artifactId>
<version>20171018</version>
</dependency>
<dependency>
<groupId>javax.json.bind</groupId>
<artifactId>javax.json.bind-api</artifactId>
<version>${jsonb-api.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
@ -46,12 +50,26 @@
<artifactId>javax.json</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.eclipse</groupId>
<artifactId>yasson</artifactId>
<version>${yasson.version}</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<everit.json.schema.version>1.4.1</everit.json.schema.version>
<fastjson.version>1.2.21</fastjson.version>
<jsonb-api.version>1.0</jsonb-api.version>
<commons-collections4.version>4.1</commons-collections4.version>
<yasson.version>1.0.1</yasson.version>
</properties>
</project>

View File

@ -18,8 +18,9 @@ import org.apache.commons.collections4.ListUtils;
import org.junit.Test;
import com.baeldung.adapter.PersonAdapter;
import com.baeldung.jsonb.Person;
public class JsonbTest {
public class JsonbUnitTest {
@Test
public void givenPersonList_whenSerializeWithJsonb_thenGetPersonJsonArray() {

12
jsonb/.gitignore vendored
View File

@ -1,12 +0,0 @@
#folders#
.idea
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -1,4 +0,0 @@
## JSON B
## Relevant articles:
- [Introduction to the JSON Binding API (JSR 367) in Java](http://www.baeldung.com/java-json-binding-api)

View File

@ -1,101 +0,0 @@
<?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>json-b</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>json-b</name>
<description>json-b sample project</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>javax.json.bind</groupId>
<artifactId>javax.json.bind-api</artifactId>
<version>${jsonb-api.version}</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.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>
</dependencies>
<profiles>
<profile>
<id>yasson</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<dependencies>
<!-- Dependencies for Yasson -->
<dependency>
<groupId>org.eclipse</groupId>
<artifactId>yasson</artifactId>
<version>${yasson.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>${javax.json.version}</version>
</dependency>
</dependencies>
</profile>
<profile>
<id>johnzon</id>
<dependencies>
<!-- Dependencies for Johnzon -->
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-json_1.1_spec</artifactId>
<version>${geronimo-json_1.1_spec.version}</version>
</dependency>
<dependency>
<groupId>org.apache.johnzon</groupId>
<artifactId>johnzon-jsonb</artifactId>
<version>${johnzon.version}</version>
</dependency>
</dependencies>
</profile>
</profiles>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.platform.version>1.0.0</junit.platform.version>
<jsonb-api.version>1.0</jsonb-api.version>
<johnzon.version>1.1.3</johnzon.version>
<geronimo-json_1.1_spec.version>1.0</geronimo-json_1.1_spec.version>
<yasson.version>1.0.1</yasson.version>
<javax.json.version>1.1.2</javax.json.version>
<commons-collections4.version>4.1</commons-collections4.version>
</properties>
</project>

88
jta/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>jta-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<description>JEE JTA demo</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jta-bitronix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.4.1</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>autoconfiguration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*IntTest.java</exclude>
</excludes>
<includes>
<include>**/AutoconfigurationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -0,0 +1,48 @@
package com.baeldung.jtademo;
import org.hsqldb.jdbc.pool.JDBCXADataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.jta.bitronix.BitronixXADataSourceWrapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
@EnableAutoConfiguration
@EnableTransactionManagement
@Configuration
@ComponentScan
public class JtaDemoApplication {
@Bean("dataSourceAccount")
public DataSource dataSource() throws Exception {
return createHsqlXADatasource("jdbc:hsqldb:mem:accountDb");
}
@Bean("dataSourceAudit")
public DataSource dataSourceAudit() throws Exception {
return createHsqlXADatasource("jdbc:hsqldb:mem:auditDb");
}
private DataSource createHsqlXADatasource(String connectionUrl) throws Exception {
JDBCXADataSource dataSource = new JDBCXADataSource();
dataSource.setUrl(connectionUrl);
dataSource.setUser("sa");
BitronixXADataSourceWrapper wrapper = new BitronixXADataSourceWrapper();
return wrapper.wrapDataSource(dataSource);
}
@Bean("jdbcTemplateAccount")
public JdbcTemplate jdbcTemplate(@Qualifier("dataSourceAccount") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean("jdbcTemplateAudit")
public JdbcTemplate jdbcTemplateAudit(@Qualifier("dataSourceAudit") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.jtademo.dto;
import java.math.BigDecimal;
public class TransferLog {
private String fromAccountId;
private String toAccountId;
private BigDecimal amount;
public TransferLog(String fromAccountId, String toAccountId, BigDecimal amount) {
this.fromAccountId = fromAccountId;
this.toAccountId = toAccountId;
this.amount = amount;
}
public String getFromAccountId() {
return fromAccountId;
}
public String getToAccountId() {
return toAccountId;
}
public BigDecimal getAmount() {
return amount;
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.jtademo.services;
import com.baeldung.jtademo.dto.TransferLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@Service
public class AuditService {
final JdbcTemplate jdbcTemplate;
@Autowired
public AuditService(@Qualifier("jdbcTemplateAudit") JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void log(String fromAccount, String toAccount, BigDecimal amount) {
jdbcTemplate.update("insert into AUDIT_LOG(FROM_ACCOUNT, TO_ACCOUNT, AMOUNT) values ?,?,?", fromAccount, toAccount, amount);
}
public TransferLog lastTransferLog() {
return jdbcTemplate.query("select FROM_ACCOUNT,TO_ACCOUNT,AMOUNT from AUDIT_LOG order by ID desc", (ResultSetExtractor<TransferLog>) (rs) -> {
if (!rs.next())
return null;
return new TransferLog(rs.getString(1), rs.getString(2), BigDecimal.valueOf(rs.getDouble(3)));
});
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.jtademo.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@Service
public class BankAccountService {
final JdbcTemplate jdbcTemplate;
@Autowired
public BankAccountService(@Qualifier("jdbcTemplateAccount") JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void transfer(String fromAccountId, String toAccountId, BigDecimal amount) {
jdbcTemplate.update("update ACCOUNT set BALANCE=BALANCE-? where ID=?", amount, fromAccountId);
jdbcTemplate.update("update ACCOUNT set BALANCE=BALANCE+? where ID=?", amount, toAccountId);
}
public BigDecimal balanceOf(String accountId) {
return jdbcTemplate.query("select BALANCE from ACCOUNT where ID=?", new Object[] { accountId }, (ResultSetExtractor<BigDecimal>) (rs) -> {
rs.next();
return new BigDecimal(rs.getDouble(1));
});
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.jtademo.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import javax.transaction.UserTransaction;
import java.math.BigDecimal;
@Service
public class TellerService {
private final BankAccountService bankAccountService;
private final AuditService auditService;
private final UserTransaction userTransaction;
@Autowired
public TellerService(BankAccountService bankAccountService, AuditService auditService, UserTransaction userTransaction) {
this.bankAccountService = bankAccountService;
this.auditService = auditService;
this.userTransaction = userTransaction;
}
@Transactional
public void executeTransfer(String fromAccontId, String toAccountId, BigDecimal amount) {
bankAccountService.transfer(fromAccontId, toAccountId, amount);
auditService.log(fromAccontId, toAccountId, amount);
BigDecimal balance = bankAccountService.balanceOf(fromAccontId);
if (balance.compareTo(BigDecimal.ZERO) <= 0) {
throw new RuntimeException("Insufficient fund.");
}
}
public void executeTransferProgrammaticTx(String fromAccontId, String toAccountId, BigDecimal amount) throws Exception {
userTransaction.begin();
bankAccountService.transfer(fromAccontId, toAccountId, amount);
auditService.log(fromAccontId, toAccountId, amount);
BigDecimal balance = bankAccountService.balanceOf(fromAccontId);
if (balance.compareTo(BigDecimal.ZERO) <= 0) {
userTransaction.rollback();
throw new RuntimeException("Insufficient fund.");
} else {
userTransaction.commit();
}
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.jtademo.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@Component
public class TestHelper {
final JdbcTemplate jdbcTemplateAccount;
final JdbcTemplate jdbcTemplateAudit;
@Autowired
public TestHelper(@Qualifier("jdbcTemplateAccount") JdbcTemplate jdbcTemplateAccount, @Qualifier("jdbcTemplateAudit") JdbcTemplate jdbcTemplateAudit) {
this.jdbcTemplateAccount = jdbcTemplateAccount;
this.jdbcTemplateAudit = jdbcTemplateAudit;
}
public void runAccountDbInit() throws SQLException {
runScript("account.sql", jdbcTemplateAccount.getDataSource());
}
public void runAuditDbInit() throws SQLException {
runScript("audit.sql", jdbcTemplateAudit.getDataSource());
}
private void runScript(String scriptName, DataSource dataSouorce) throws SQLException {
DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
Resource script = resourceLoader.getResource(scriptName);
try (Connection con = dataSouorce.getConnection()) {
ScriptUtils.executeSqlScript(con, script);
}
}
}

View File

@ -0,0 +1,9 @@
DROP SCHEMA PUBLIC CASCADE;
create table ACCOUNT (
ID char(8) PRIMARY KEY,
BALANCE NUMERIC(28,10)
);
insert into ACCOUNT(ID, BALANCE) values ('a0000001', 1000);
insert into ACCOUNT(ID, BALANCE) values ('a0000002', 2000);

View File

@ -0,0 +1,8 @@
DROP SCHEMA PUBLIC CASCADE;
create table AUDIT_LOG (
ID INTEGER IDENTITY PRIMARY KEY,
FROM_ACCOUNT varchar(8),
TO_ACCOUNT varchar(8),
AMOUNT numeric(28,10)
);

View File

@ -0,0 +1,91 @@
package com.baeldung.jtademo;
import com.baeldung.jtademo.dto.TransferLog;
import com.baeldung.jtademo.services.AuditService;
import com.baeldung.jtademo.services.BankAccountService;
import com.baeldung.jtademo.services.TellerService;
import com.baeldung.jtademo.services.TestHelper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.math.BigDecimal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = JtaDemoApplication.class)
public class JtaDemoUnitTest {
@Autowired
TestHelper testHelper;
@Autowired
TellerService tellerService;
@Autowired
BankAccountService accountService;
@Autowired
AuditService auditService;
@Before
public void beforeTest() throws Exception {
testHelper.runAuditDbInit();
testHelper.runAccountDbInit();
}
@Test
public void givenAnnotationTx_whenNoException_thenAllCommitted() throws Exception {
tellerService.executeTransfer("a0000001", "a0000002", BigDecimal.valueOf(500));
assertThat(accountService.balanceOf("a0000001")).isEqualByComparingTo(BigDecimal.valueOf(500));
assertThat(accountService.balanceOf("a0000002")).isEqualByComparingTo(BigDecimal.valueOf(2500));
TransferLog lastTransferLog = auditService.lastTransferLog();
assertThat(lastTransferLog).isNotNull();
assertThat(lastTransferLog.getFromAccountId()).isEqualTo("a0000001");
assertThat(lastTransferLog.getToAccountId()).isEqualTo("a0000002");
assertThat(lastTransferLog.getAmount()).isEqualByComparingTo(BigDecimal.valueOf(500));
}
@Test
public void givenAnnotationTx_whenException_thenAllRolledBack() throws Exception {
assertThatThrownBy(() -> {
tellerService.executeTransfer("a0000002", "a0000001", BigDecimal.valueOf(100000));
}).hasMessage("Insufficient fund.");
assertThat(accountService.balanceOf("a0000001")).isEqualByComparingTo(BigDecimal.valueOf(1000));
assertThat(accountService.balanceOf("a0000002")).isEqualByComparingTo(BigDecimal.valueOf(2000));
assertThat(auditService.lastTransferLog()).isNull();
}
@Test
public void givenProgrammaticTx_whenCommit_thenAllCommitted() throws Exception {
tellerService.executeTransferProgrammaticTx("a0000001", "a0000002", BigDecimal.valueOf(500));
BigDecimal result = accountService.balanceOf("a0000001");
assertThat(accountService.balanceOf("a0000001")).isEqualByComparingTo(BigDecimal.valueOf(500));
assertThat(accountService.balanceOf("a0000002")).isEqualByComparingTo(BigDecimal.valueOf(2500));
TransferLog lastTransferLog = auditService.lastTransferLog();
assertThat(lastTransferLog).isNotNull();
assertThat(lastTransferLog.getFromAccountId()).isEqualTo("a0000001");
assertThat(lastTransferLog.getToAccountId()).isEqualTo("a0000002");
assertThat(lastTransferLog.getAmount()).isEqualByComparingTo(BigDecimal.valueOf(500));
}
@Test
public void givenProgrammaticTx_whenRollback_thenAllRolledBack() throws Exception {
assertThatThrownBy(() -> {
tellerService.executeTransferProgrammaticTx("a0000002", "a0000001", BigDecimal.valueOf(100000));
}).hasMessage("Insufficient fund.");
assertThat(accountService.balanceOf("a0000001")).isEqualByComparingTo(BigDecimal.valueOf(1000));
assertThat(accountService.balanceOf("a0000002")).isEqualByComparingTo(BigDecimal.valueOf(2000));
assertThat(auditService.lastTransferLog()).isNull();
}
}

View File

@ -13,20 +13,23 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<repositories>
<repository>
<id>OpenNMS Repository</id>
<url>http://repo.opennms.org/maven2/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>javax.jnlp</groupId>
<groupId>javax.samples.jnlp</groupId>
<artifactId>jnlp-servlet</artifactId>
<version>${jnlp-servlet.version}</version>
<scope>system</scope>
<systemPath>${project.basedir}/java-core-samples-lib/jnlp-servlet.jar</systemPath>
</dependency>
<dependency>
<groupId>javax.jnlp</groupId>
<artifactId>jardiff</artifactId>
<version>${jardiff.version}</version>
<scope>system</scope>
<systemPath>${project.basedir}/java-core-samples-lib/jardiff.jar</systemPath>
<groupId>javax.samples.jnlp</groupId>
<artifactId>jnlp-jardiff</artifactId>
<version>${jnlp-jardiff.version}</version>
</dependency>
</dependencies>
@ -81,8 +84,8 @@
<properties>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
<maven-war-plugin.version>3.0.0</maven-war-plugin.version>
<jardiff.version>7.0</jardiff.version>
<jnlp-servlet.version>7.0</jnlp-servlet.version>
<jnlp-jardiff.version>1.6.0</jnlp-jardiff.version>
<jnlp-servlet.version>1.6.0</jnlp-servlet.version>
</properties>
</project>

View File

@ -10,4 +10,4 @@
- [A Guide to Apache Ignite](http://www.baeldung.com/apache-ignite)
- [Apache Ignite with Spring Data](http://www.baeldung.com/apache-ignite-spring-data)
- [Guide to JMapper](https://www.baeldung.com/jmapper)
- [A Guide to Apache Crunch](https://www.baeldung.com/crunch)
- [A Guide to Apache Crunch](https://www.baeldung.com/apache-crunch)

View File

@ -6,4 +6,4 @@
- [Programatically Create, Configure, and Run a Tomcat Server](http://www.baeldung.com/tomcat-programmatic-setup)
- [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic)
- [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel)
- [MQTT Client in Java](https://www.baeldung.com/java-mqtt-client)

View File

@ -154,6 +154,17 @@
<artifactId>commons-dbutils</artifactId>
<version>${commons.dbutils.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-connector-kafka-0.11_2.11</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-streaming-java_2.11</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-core</artifactId>
@ -178,7 +189,7 @@
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-test-utils_2.10</artifactId>
<artifactId>flink-test-utils_2.11</artifactId>
<version>${flink.version}</version>
<scope>test</scope>
</dependency>
@ -228,6 +239,11 @@
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- JDO -->
<dependency>
<groupId>org.datanucleus</groupId>
@ -700,11 +716,6 @@
<artifactId>resilience4j-timelimiter</artifactId>
<version>${resilience4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${common-math3-version}</version>
</dependency>
<dependency>
<groupId>org.knowm.xchart</groupId>
<artifactId>xchart</artifactId>
@ -902,7 +913,7 @@
<httpclient.version>4.5.3</httpclient.version>
<commons.io.version>2.5</commons.io.version>
<flink.version>1.2.0</flink.version>
<flink.version>1.5.0</flink.version>
<jackson.version>2.8.5</jackson.version>
<neuroph.version>2.92</neuroph.version>
<serenity.version>1.9.26</serenity.version>
@ -948,7 +959,6 @@
<jctools.version>2.1.2</jctools.version>
<typesafe-akka.version>2.5.11</typesafe-akka.version>
<resilience4j.version>0.12.1</resilience4j.version>
<common-math3-version>3.6.1</common-math3-version>
<xchart-version>3.5.2</xchart-version>
<commons-net.version>3.6</commons-net.version>
<mockftpserver.version>2.7.1</mockftpserver.version>

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