Merge branch 'master' of https://github.com/eugenp/tutorials into task/BAEL-8841

This commit is contained in:
Dhawal Kapil 2018-09-06 00:33:44 +05:30
commit f3afeaa638
23 changed files with 432 additions and 185 deletions

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

@ -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

@ -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

@ -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

@ -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>

View File

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