From 84d18e7a828c76151fcc74bd5a28cc11bf34887e Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Wed, 5 Sep 2018 09:09:57 +0530 Subject: [PATCH 1/6] BAEL-8852 Remove extra bin folder from javaxval project - Removed bin folder --- javaxval/bin/.gitignore | 6 ------ javaxval/bin/pom.xml | 44 ----------------------------------------- 2 files changed, 50 deletions(-) delete mode 100644 javaxval/bin/.gitignore delete mode 100644 javaxval/bin/pom.xml diff --git a/javaxval/bin/.gitignore b/javaxval/bin/.gitignore deleted file mode 100644 index 55a6bcf596..0000000000 --- a/javaxval/bin/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -.classpath -.project -.settings/ -target/ - - diff --git a/javaxval/bin/pom.xml b/javaxval/bin/pom.xml deleted file mode 100644 index a16072bb1a..0000000000 --- a/javaxval/bin/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - 4.0.0 - com.baeldung - javaxval - 0.1-SNAPSHOT - - - - - - javax.validation - validation-api - 1.1.0.Final - - - - org.hibernate - hibernate-validator - 5.2.1.Final - - - - org.hibernate - hibernate-validator-annotation-processor - 5.2.1.Final - - - - javax.el - javax.el-api - 2.2.4 - - - - org.glassfish.web - javax.el - 2.2.4 - - - - - - \ No newline at end of file From e899b76d4354c47fddd7d7d45429a80fc356de8c Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Wed, 5 Sep 2018 10:21:18 +0530 Subject: [PATCH 2/6] BAEL-8853 Merge jsonb module into another module - Moved jsonb module resources to json module and deleted jsonb module --- json/README.md | 1 + json/pom.xml | 22 +++- .../com/baeldung/adapter/PersonAdapter.java | 0 .../main/java/com/baeldung/jsonb/Person.java | 0 .../java/com/baeldung/jsonb/JsonbTest.java | 1 + jsonb/.gitignore | 12 --- jsonb/README.md | 4 - jsonb/pom.xml | 101 ------------------ jsonb/src/main/resources/logback.xml | 13 --- 9 files changed, 22 insertions(+), 132 deletions(-) rename {jsonb => json}/src/main/java/com/baeldung/adapter/PersonAdapter.java (100%) rename {jsonb => json}/src/main/java/com/baeldung/jsonb/Person.java (100%) rename {jsonb => json}/src/test/java/com/baeldung/jsonb/JsonbTest.java (99%) delete mode 100644 jsonb/.gitignore delete mode 100644 jsonb/README.md delete mode 100644 jsonb/pom.xml delete mode 100644 jsonb/src/main/resources/logback.xml diff --git a/json/README.md b/json/README.md index 8c2abc3e47..e0679bc60b 100644 --- a/json/README.md +++ b/json/README.md @@ -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) \ No newline at end of file diff --git a/json/pom.xml b/json/pom.xml index fa3fcafa65..b688baec06 100644 --- a/json/pom.xml +++ b/json/pom.xml @@ -33,7 +33,11 @@ json 20171018 - + + javax.json.bind + javax.json.bind-api + ${jsonb-api.version} + junit junit @@ -46,12 +50,26 @@ javax.json 1.1.2 - + + org.eclipse + yasson + ${yasson.version} + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + test + 1.4.1 1.2.21 + 1.0 + 4.1 + 1.0.1 diff --git a/jsonb/src/main/java/com/baeldung/adapter/PersonAdapter.java b/json/src/main/java/com/baeldung/adapter/PersonAdapter.java similarity index 100% rename from jsonb/src/main/java/com/baeldung/adapter/PersonAdapter.java rename to json/src/main/java/com/baeldung/adapter/PersonAdapter.java diff --git a/jsonb/src/main/java/com/baeldung/jsonb/Person.java b/json/src/main/java/com/baeldung/jsonb/Person.java similarity index 100% rename from jsonb/src/main/java/com/baeldung/jsonb/Person.java rename to json/src/main/java/com/baeldung/jsonb/Person.java diff --git a/jsonb/src/test/java/com/baeldung/jsonb/JsonbTest.java b/json/src/test/java/com/baeldung/jsonb/JsonbTest.java similarity index 99% rename from jsonb/src/test/java/com/baeldung/jsonb/JsonbTest.java rename to json/src/test/java/com/baeldung/jsonb/JsonbTest.java index 67beda77e1..cc36af1d1d 100644 --- a/jsonb/src/test/java/com/baeldung/jsonb/JsonbTest.java +++ b/json/src/test/java/com/baeldung/jsonb/JsonbTest.java @@ -18,6 +18,7 @@ import org.apache.commons.collections4.ListUtils; import org.junit.Test; import com.baeldung.adapter.PersonAdapter; +import com.baeldung.jsonb.Person; public class JsonbTest { diff --git a/jsonb/.gitignore b/jsonb/.gitignore deleted file mode 100644 index dec013dfa4..0000000000 --- a/jsonb/.gitignore +++ /dev/null @@ -1,12 +0,0 @@ -#folders# -.idea -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/jsonb/README.md b/jsonb/README.md deleted file mode 100644 index 9293a44808..0000000000 --- a/jsonb/README.md +++ /dev/null @@ -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) diff --git a/jsonb/pom.xml b/jsonb/pom.xml deleted file mode 100644 index 160b9d5df7..0000000000 --- a/jsonb/pom.xml +++ /dev/null @@ -1,101 +0,0 @@ - - - 4.0.0 - com.baeldung - json-b - 0.0.1-SNAPSHOT - jar - json-b - json-b sample project - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - javax.json.bind - javax.json.bind-api - ${jsonb-api.version} - - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - test - - - - org.junit.jupiter - junit-jupiter-api - ${junit.jupiter.version} - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - test - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - - - - - - yasson - - true - - - - - org.eclipse - yasson - ${yasson.version} - - - org.glassfish - javax.json - ${javax.json.version} - - - - - johnzon - - - - org.apache.geronimo.specs - geronimo-json_1.1_spec - ${geronimo-json_1.1_spec.version} - - - org.apache.johnzon - johnzon-jsonb - ${johnzon.version} - - - - - - - 1.8 - 1.8 - 1.0.0 - 1.0 - 1.1.3 - 1.0 - 1.0.1 - 1.1.2 - 4.1 - - - \ No newline at end of file diff --git a/jsonb/src/main/resources/logback.xml b/jsonb/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/jsonb/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file From 0966bd3bb022b9746088a071a47794258241df2f Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Wed, 5 Sep 2018 11:24:34 +0530 Subject: [PATCH 3/6] BAEL-8853 Merge jsonb module into another module - Fixed PMD violation --- .../com/baeldung/jsonb/{JsonbTest.java => JsonbUnitTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename json/src/test/java/com/baeldung/jsonb/{JsonbTest.java => JsonbUnitTest.java} (99%) diff --git a/json/src/test/java/com/baeldung/jsonb/JsonbTest.java b/json/src/test/java/com/baeldung/jsonb/JsonbUnitTest.java similarity index 99% rename from json/src/test/java/com/baeldung/jsonb/JsonbTest.java rename to json/src/test/java/com/baeldung/jsonb/JsonbUnitTest.java index cc36af1d1d..f258700c6b 100644 --- a/json/src/test/java/com/baeldung/jsonb/JsonbTest.java +++ b/json/src/test/java/com/baeldung/jsonb/JsonbUnitTest.java @@ -20,7 +20,7 @@ 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() { From b48458d3fd76f74a347f1ab98ab2b4a37d43b409 Mon Sep 17 00:00:00 2001 From: smokeyrobot Date: Wed, 5 Sep 2018 02:18:57 -0400 Subject: [PATCH 4/6] Bael 801 (#5150) * BAEL-801 A Guide to OptaPlanner * BAEL-801 Optaplanner per Editor Review * BAEL-801 Fixed parent pom merge issue * BAEL-801 Fixed parent pom merge issue * BAEL-801 Added logback to suppress debug logging causing build failures * BAEL-801 Updated per editor review * BAEL-801 Removed static variables * BAEL-801 - Updated per Senior Editor review. Moved classes to Drools module. * BAEL-801 - Updated per Senior Editor review. Moved classes to Drools module. * BAEL-801 - Deleted duplicate class. --- drools/pom.xml | 6 ++ .../drools/optaplanner/CourseSchedule.java | 63 +++++++++++++++++++ .../baeldung/drools/optaplanner/Lecture.java | 30 +++++++++ .../drools/optaplanner/ScoreCalculator.java | 32 ++++++++++ drools/src/main/resources/courseSchedule.drl | 14 +++++ .../courseScheduleSolverConfigDrools.xml | 12 ++++ .../courseScheduleSolverConfiguration.xml | 12 ++++ .../optaplanner/OptaPlannerUnitTest.java | 49 +++++++++++++++ 8 files changed, 218 insertions(+) create mode 100644 drools/src/main/java/com/baeldung/drools/optaplanner/CourseSchedule.java create mode 100644 drools/src/main/java/com/baeldung/drools/optaplanner/Lecture.java create mode 100644 drools/src/main/java/com/baeldung/drools/optaplanner/ScoreCalculator.java create mode 100644 drools/src/main/resources/courseSchedule.drl create mode 100644 drools/src/main/resources/courseScheduleSolverConfigDrools.xml create mode 100644 drools/src/main/resources/courseScheduleSolverConfiguration.xml create mode 100644 drools/src/test/java/com/baeldung/drools/optaplanner/OptaPlannerUnitTest.java diff --git a/drools/pom.xml b/drools/pom.xml index 631bc8c792..009ac8acec 100644 --- a/drools/pom.xml +++ b/drools/pom.xml @@ -48,12 +48,18 @@ poi-ooxml ${apache-poi-version} + + org.optaplanner + optaplanner-core + ${opta-planner-version} + 4.4.6 7.4.1.Final 3.13 + 7.10.0.Final diff --git a/drools/src/main/java/com/baeldung/drools/optaplanner/CourseSchedule.java b/drools/src/main/java/com/baeldung/drools/optaplanner/CourseSchedule.java new file mode 100644 index 0000000000..7b2ba117a1 --- /dev/null +++ b/drools/src/main/java/com/baeldung/drools/optaplanner/CourseSchedule.java @@ -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 roomList; + private List periodList; + private List lectureList; + private HardSoftScore score; + + public CourseSchedule(){ + roomList = new ArrayList<>(); + periodList = new ArrayList<>(); + lectureList = new ArrayList<>(); + } + + @ValueRangeProvider(id = "availableRooms") + @ProblemFactCollectionProperty + public List getRoomList() { + return roomList; + } + + @ValueRangeProvider(id = "availablePeriods") + @ProblemFactCollectionProperty + public List getPeriodList() { + return periodList; + } + + @PlanningEntityCollectionProperty + public List 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)); + } + +} diff --git a/drools/src/main/java/com/baeldung/drools/optaplanner/Lecture.java b/drools/src/main/java/com/baeldung/drools/optaplanner/Lecture.java new file mode 100644 index 0000000000..193cdb08b1 --- /dev/null +++ b/drools/src/main/java/com/baeldung/drools/optaplanner/Lecture.java @@ -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; + } + +} diff --git a/drools/src/main/java/com/baeldung/drools/optaplanner/ScoreCalculator.java b/drools/src/main/java/com/baeldung/drools/optaplanner/ScoreCalculator.java new file mode 100644 index 0000000000..86501cdccd --- /dev/null +++ b/drools/src/main/java/com/baeldung/drools/optaplanner/ScoreCalculator.java @@ -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 { + + @Override + public Score calculateScore(CourseSchedule courseSchedule) { + int hardScore = 0; + int softScore = 0; + + HashSet 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); + } +} diff --git a/drools/src/main/resources/courseSchedule.drl b/drools/src/main/resources/courseSchedule.drl new file mode 100644 index 0000000000..35dd57df84 --- /dev/null +++ b/drools/src/main/resources/courseSchedule.drl @@ -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 \ No newline at end of file diff --git a/drools/src/main/resources/courseScheduleSolverConfigDrools.xml b/drools/src/main/resources/courseScheduleSolverConfigDrools.xml new file mode 100644 index 0000000000..7cf95fdcd3 --- /dev/null +++ b/drools/src/main/resources/courseScheduleSolverConfigDrools.xml @@ -0,0 +1,12 @@ + + + + + + courseSchedule.drl + + + + 10 + + \ No newline at end of file diff --git a/drools/src/main/resources/courseScheduleSolverConfiguration.xml b/drools/src/main/resources/courseScheduleSolverConfiguration.xml new file mode 100644 index 0000000000..dfedb8f2fd --- /dev/null +++ b/drools/src/main/resources/courseScheduleSolverConfiguration.xml @@ -0,0 +1,12 @@ + + + + + + com.baeldung.drools.optaplanner.ScoreCalculator + + + + 10 + + \ No newline at end of file diff --git a/drools/src/test/java/com/baeldung/drools/optaplanner/OptaPlannerUnitTest.java b/drools/src/test/java/com/baeldung/drools/optaplanner/OptaPlannerUnitTest.java new file mode 100644 index 0000000000..1880e30b86 --- /dev/null +++ b/drools/src/test/java/com/baeldung/drools/optaplanner/OptaPlannerUnitTest.java @@ -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 solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfiguration.xml"); + Solver solver = solverFactory.buildSolver(); + CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule); + + Assert.assertNotNull(solvedCourseSchedule.getScore()); + Assert.assertEquals(-4, solvedCourseSchedule.getScore().getHardScore()); + } + + @Test + public void test_whenDroolsSolver() { + + SolverFactory solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfigDrools.xml"); + Solver solver = solverFactory.buildSolver(); + CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule); + + Assert.assertNotNull(solvedCourseSchedule.getScore()); + Assert.assertEquals(0, solvedCourseSchedule.getScore().getHardScore()); + } +} From ad3b0a527fd14723676894edefc536c2208226ac Mon Sep 17 00:00:00 2001 From: Amitabh Mandal Date: Wed, 5 Sep 2018 14:36:48 +0530 Subject: [PATCH 5/6] Renamed Junits to standard (#5147) --- .../com/baeldung/java9/process/ProcessUnderstandingTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java index 2f61846c1c..2c5525b9ed 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java @@ -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); From 717fb11d11b077fc3e00e827096bff92a2f57b32 Mon Sep 17 00:00:00 2001 From: Syed Muhammad Mansoor Date: Wed, 5 Sep 2018 19:21:31 +1000 Subject: [PATCH 6/6] [BAEL-1824] Working with Aamazon Aurora RDS with Java (#4917) * [BAEL-1824] Working with Aamazon Aurora RDS with Java * Fixed error handling * Fixed code as per review comments * Added comment for accesskey usage --- aws/.gitignore | 1 + .../java/com/baeldung/rds/AWSRDSService.java | 184 ++++++++++++++++++ aws/src/main/resources/db.properties | 4 + 3 files changed, 189 insertions(+) create mode 100644 aws/src/main/java/com/baeldung/rds/AWSRDSService.java create mode 100644 aws/src/main/resources/db.properties diff --git a/aws/.gitignore b/aws/.gitignore index b83d22266a..bf11a4cc38 100644 --- a/aws/.gitignore +++ b/aws/.gitignore @@ -1 +1,2 @@ /target/ +.idea/ \ No newline at end of file diff --git a/aws/src/main/java/com/baeldung/rds/AWSRDSService.java b/aws/src/main/java/com/baeldung/rds/AWSRDSService.java new file mode 100644 index 0000000000..d4da92f30f --- /dev/null +++ b/aws/src/main/java/com/baeldung/rds/AWSRDSService.java @@ -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("", + "")); + 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 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); + } +} diff --git a/aws/src/main/resources/db.properties b/aws/src/main/resources/db.properties new file mode 100644 index 0000000000..e934611a2b --- /dev/null +++ b/aws/src/main/resources/db.properties @@ -0,0 +1,4 @@ +db_hostname= +db_username=username +db_password=password +db_database=mydb \ No newline at end of file