Skip to content

Commit f3afeaa

Browse files
committed
Merge branch 'master' of https://github.com/eugenp/tutorials into task/BAEL-8841
2 parents 381908a + 717fb11 commit f3afeaa

23 files changed

Lines changed: 432 additions & 185 deletions

File tree

‎aws/.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
/target/
2+
.idea/
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
package com.baeldung.rds;
2+
3+
import com.amazonaws.auth.AWSCredentialsProvider;
4+
import com.amazonaws.auth.AWSStaticCredentialsProvider;
5+
import com.amazonaws.auth.BasicAWSCredentials;
6+
import com.amazonaws.regions.Regions;
7+
import com.amazonaws.services.rds.AmazonRDS;
8+
import com.amazonaws.services.rds.AmazonRDSClientBuilder;
9+
import com.amazonaws.services.rds.model.*;
10+
11+
import java.io.IOException;
12+
import java.io.InputStream;
13+
import java.sql.*;
14+
import java.util.List;
15+
import java.util.Properties;
16+
import java.util.UUID;
17+
import java.util.logging.Logger;
18+
19+
public class AWSRDSService {
20+
21+
22+
final static Logger logger = Logger.getLogger(AWSRDSService.class.getName());
23+
private AWSCredentialsProvider credentials;
24+
private AmazonRDS amazonRDS;
25+
private String db_username;
26+
private String db_password;
27+
private String db_database;
28+
private String db_hostname;
29+
30+
/*
31+
* User access key and secret key must be set before execute any operation.
32+
* Follow the link on how to get the user access and secret key
33+
* https://aws.amazon.com/blogs/security/wheres-my-secret-access-key/
34+
* **/
35+
public AWSRDSService() throws IOException {
36+
//Init RDS client with credentials and region.
37+
credentials = new
38+
AWSStaticCredentialsProvider(new
39+
BasicAWSCredentials("<ACCESS_KEY>",
40+
"<SECRET_KEY>"));
41+
amazonRDS = AmazonRDSClientBuilder.standard().withCredentials(credentials)
42+
.withRegion(Regions.AP_SOUTHEAST_2).build();
43+
Properties prop = new Properties();
44+
InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties");
45+
prop.load(input);
46+
db_username = prop.getProperty("db_username");
47+
db_password = prop.getProperty("db_password");
48+
db_database = prop.getProperty("db_database");
49+
}
50+
51+
public AWSRDSService(AmazonRDS amazonRDS){
52+
this.amazonRDS = amazonRDS;
53+
}
54+
55+
/**
56+
* create the RDS instance.
57+
* After instance creation, update the db_hostname with endpoint in db.properties.
58+
* */
59+
60+
public String launchInstance() {
61+
62+
String identifier = "";
63+
CreateDBInstanceRequest request = new CreateDBInstanceRequest();
64+
// RDS instance name
65+
request.setDBInstanceIdentifier("Sydney");
66+
request.setEngine("postgres");
67+
request.setMultiAZ(false);
68+
request.setMasterUsername(db_username);
69+
request.setMasterUserPassword(db_password);
70+
request.setDBName(db_database);
71+
request.setStorageType("gp2");
72+
request.setAllocatedStorage(10);
73+
74+
DBInstance instance = amazonRDS.createDBInstance(request);
75+
76+
// Information about the new RDS instance
77+
identifier = instance.getDBInstanceIdentifier();
78+
String status = instance.getDBInstanceStatus();
79+
Endpoint endpoint = instance.getEndpoint();
80+
String endpoint_url = "Endpoint URL not available yet.";
81+
if (endpoint != null) {
82+
endpoint_url = endpoint.toString();
83+
}
84+
logger.info(identifier + "\t" + status);
85+
logger.info(endpoint_url);
86+
87+
return identifier;
88+
89+
}
90+
91+
// Describe DB instances
92+
public void listInstances() {
93+
DescribeDBInstancesResult result = amazonRDS.describeDBInstances();
94+
List<DBInstance> instances = result.getDBInstances();
95+
for (DBInstance instance : instances) {
96+
// Information about each RDS instance
97+
String identifier = instance.getDBInstanceIdentifier();
98+
String engine = instance.getEngine();
99+
String status = instance.getDBInstanceStatus();
100+
Endpoint endpoint = instance.getEndpoint();
101+
String endpoint_url = "Endpoint URL not available yet.";
102+
if (endpoint != null) {
103+
endpoint_url = endpoint.toString();
104+
}
105+
logger.info(identifier + "\t" + engine + "\t" + status);
106+
logger.info("\t" + endpoint_url);
107+
}
108+
109+
}
110+
111+
//Delete RDS instance
112+
public void terminateInstance(String identifier) {
113+
114+
DeleteDBInstanceRequest request = new DeleteDBInstanceRequest();
115+
request.setDBInstanceIdentifier(identifier);
116+
request.setSkipFinalSnapshot(true);
117+
118+
// Delete the RDS instance
119+
DBInstance instance = amazonRDS.deleteDBInstance(request);
120+
121+
// Information about the RDS instance being deleted
122+
String status = instance.getDBInstanceStatus();
123+
Endpoint endpoint = instance.getEndpoint();
124+
String endpoint_url = "Endpoint URL not available yet.";
125+
if (endpoint != null) {
126+
endpoint_url = endpoint.toString();
127+
}
128+
129+
logger.info(identifier + "\t" + status);
130+
logger.info(endpoint_url);
131+
132+
}
133+
134+
135+
public void runJdbcTests() throws SQLException, IOException {
136+
137+
// Getting database properties from db.properties
138+
Properties prop = new Properties();
139+
InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties");
140+
prop.load(input);
141+
db_hostname = prop.getProperty("db_hostname");
142+
String jdbc_url = "jdbc:postgresql://" + db_hostname + ":5432/" + db_database;
143+
144+
// Create a connection using the JDBC driver
145+
try (Connection conn = DriverManager.getConnection(jdbc_url, db_username, db_password)) {
146+
147+
// Create the test table if not exists
148+
Statement statement = conn.createStatement();
149+
String sql = "CREATE TABLE IF NOT EXISTS jdbc_test (id SERIAL PRIMARY KEY, content VARCHAR(80))";
150+
statement.executeUpdate(sql);
151+
152+
// Do some INSERT
153+
PreparedStatement preparedStatement = conn.prepareStatement("INSERT INTO jdbc_test (content) VALUES (?)");
154+
String content = "" + UUID.randomUUID();
155+
preparedStatement.setString(1, content);
156+
preparedStatement.executeUpdate();
157+
logger.info("INSERT: " + content);
158+
159+
// Do some SELECT
160+
sql = "SELECT * FROM jdbc_test";
161+
ResultSet resultSet = statement.executeQuery(sql);
162+
while (resultSet.next()) {
163+
String count = resultSet.getString("content");
164+
logger.info("Total Records: " + count);
165+
}
166+
}
167+
168+
169+
}
170+
171+
public static void main(String[] args) throws IOException, SQLException {
172+
AWSRDSService awsrdsService = new AWSRDSService();
173+
174+
String instanceName = awsrdsService.launchInstance();
175+
176+
//Add some wait for instance creation.
177+
178+
awsrdsService.listInstances();
179+
180+
awsrdsService.runJdbcTests();
181+
182+
awsrdsService.terminateInstance(instanceName);
183+
}
184+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
db_hostname=<RDS EndPoint>
2+
db_username=username
3+
db_password=password
4+
db_database=mydb

‎core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ public void givenSubProcess_whenEncounteringError_thenErrorStreamNotNull() throw
4848
}
4949

5050
//@Test - windows specific
51-
public void givenSubProcess_thenStartSuccessIsAlive() throws IOException {
51+
public void givenSubProcess_whenStarted_thenStartSuccessIsAlive() throws IOException {
5252
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
5353
assertTrue(builder.start().isAlive());
5454
}
@@ -75,7 +75,7 @@ public void givenSubProcess_whenAlive_thenDestroyForcibly() throws IOException,
7575
}
7676

7777
//@Test - windows specific
78-
public void givenSubProcess_checkAlive() throws IOException, InterruptedException {
78+
public void givenSubProcess_whenDestroyed_thenCheckIfAlive() throws IOException, InterruptedException {
7979
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
8080
Process process = builder.start();
8181
Thread.sleep(10000);

‎drools/pom.xml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,18 @@
4848
<artifactId>poi-ooxml</artifactId>
4949
<version>${apache-poi-version}</version>
5050
</dependency>
51+
<dependency>
52+
<groupId>org.optaplanner</groupId>
53+
<artifactId>optaplanner-core</artifactId>
54+
<version>${opta-planner-version}</version>
55+
</dependency>
5156
</dependencies>
5257

5358
<properties>
5459
<http-component-version>4.4.6</http-component-version>
5560
<drools-version>7.4.1.Final</drools-version>
5661
<apache-poi-version>3.13</apache-poi-version>
62+
<opta-planner-version>7.10.0.Final</opta-planner-version>
5763
</properties>
5864

5965
</project>
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.baeldung.drools.optaplanner;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty;
7+
import org.optaplanner.core.api.domain.solution.PlanningScore;
8+
import org.optaplanner.core.api.domain.solution.PlanningSolution;
9+
import org.optaplanner.core.api.domain.solution.drools.ProblemFactCollectionProperty;
10+
import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider;
11+
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
12+
import org.slf4j.Logger;
13+
import org.slf4j.LoggerFactory;
14+
15+
@PlanningSolution
16+
public class CourseSchedule {
17+
18+
Logger logger = LoggerFactory.getLogger("CourseSchedule");
19+
20+
private List<Integer> roomList;
21+
private List<Integer> periodList;
22+
private List<Lecture> lectureList;
23+
private HardSoftScore score;
24+
25+
public CourseSchedule(){
26+
roomList = new ArrayList<>();
27+
periodList = new ArrayList<>();
28+
lectureList = new ArrayList<>();
29+
}
30+
31+
@ValueRangeProvider(id = "availableRooms")
32+
@ProblemFactCollectionProperty
33+
public List<Integer> getRoomList() {
34+
return roomList;
35+
}
36+
37+
@ValueRangeProvider(id = "availablePeriods")
38+
@ProblemFactCollectionProperty
39+
public List<Integer> getPeriodList() {
40+
return periodList;
41+
}
42+
43+
@PlanningEntityCollectionProperty
44+
public List<Lecture> getLectureList() {
45+
return lectureList;
46+
}
47+
48+
@PlanningScore
49+
public HardSoftScore getScore() {
50+
return score;
51+
}
52+
53+
public void setScore(HardSoftScore score) {
54+
this.score = score;
55+
}
56+
57+
public void printCourseSchedule() {
58+
lectureList.stream()
59+
.map(c -> "Lecture in Room " + c.getRoomNumber().toString() + " during Period " + c.getPeriod().toString())
60+
.forEach(k -> logger.info(k));
61+
}
62+
63+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.baeldung.drools.optaplanner;
2+
3+
import org.optaplanner.core.api.domain.entity.PlanningEntity;
4+
import org.optaplanner.core.api.domain.variable.PlanningVariable;
5+
6+
@PlanningEntity
7+
public class Lecture {
8+
9+
private Integer roomNumber;
10+
private Integer period;
11+
12+
@PlanningVariable(valueRangeProviderRefs = {"availablePeriods"})
13+
public Integer getPeriod() {
14+
return period;
15+
}
16+
17+
@PlanningVariable(valueRangeProviderRefs = {"availableRooms"})
18+
public Integer getRoomNumber() {
19+
return roomNumber;
20+
}
21+
22+
public void setPeriod(Integer period) {
23+
this.period = period;
24+
}
25+
26+
public void setRoomNumber(Integer roomNumber) {
27+
this.roomNumber = roomNumber;
28+
}
29+
30+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.baeldung.drools.optaplanner;
2+
3+
import java.util.HashSet;
4+
5+
import org.optaplanner.core.api.score.Score;
6+
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
7+
import org.optaplanner.core.impl.score.director.easy.EasyScoreCalculator;
8+
9+
public class ScoreCalculator implements EasyScoreCalculator<CourseSchedule> {
10+
11+
@Override
12+
public Score calculateScore(CourseSchedule courseSchedule) {
13+
int hardScore = 0;
14+
int softScore = 0;
15+
16+
HashSet<String> occupiedRooms = new HashSet<>();
17+
for (Lecture lecture : courseSchedule.getLectureList()) {
18+
if(lecture.getPeriod() != null && lecture.getRoomNumber() != null) {
19+
String roomInUse = lecture.getPeriod().toString() + ":" + lecture.getRoomNumber().toString();
20+
if (occupiedRooms.contains(roomInUse)) {
21+
hardScore += -1;
22+
} else {
23+
occupiedRooms.add(roomInUse);
24+
}
25+
} else {
26+
hardScore += -1;
27+
}
28+
}
29+
30+
return HardSoftScore.valueOf(hardScore, softScore);
31+
}
32+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.baeldung.drools.optaplanner
2+
3+
import com.baeldung.drools.optaplanner.Lecture;
4+
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScoreHolder;
5+
6+
global HardSoftScoreHolder scoreHolder;
7+
8+
rule "noNullRoomPeriod"
9+
when
10+
Lecture( roomNumber == null );
11+
Lecture( period == null );
12+
then
13+
scoreHolder.addHardConstraintMatch(kcontext, -1);
14+
end
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<solver>
3+
<scanAnnotatedClasses/>
4+
5+
<scoreDirectorFactory>
6+
<scoreDrl>courseSchedule.drl</scoreDrl>
7+
</scoreDirectorFactory>
8+
9+
<termination>
10+
<secondsSpentLimit>10</secondsSpentLimit>
11+
</termination>
12+
</solver>

0 commit comments

Comments
 (0)