commit
04c255c887
@ -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>
|
||||
|
@ -2,7 +2,7 @@
|
||||
The "REST with Spring" Classes
|
||||
==============================
|
||||
|
||||
After 5 months of work, here's the Master Class of REST With Spring: <br/>
|
||||
Here's the Master Class of REST With Spring (price changes permanently next Friday): <br/>
|
||||
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||
|
||||
And here's the Master Class of Learn Spring Security: <br/>
|
||||
|
@ -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);
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.baeldung.algorithms.linesintersection;
|
||||
|
||||
import java.awt.Point;
|
||||
import java.util.Optional;
|
||||
|
||||
public class LinesIntersectionService {
|
||||
|
||||
public Optional<Point> calculateIntersectionPoint(double m1, double b1, double m2, double b2) {
|
||||
|
||||
if (m1 == m2) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
double x = (b2 - b1) / (m1 - m2);
|
||||
double y = m1 * x + b1;
|
||||
|
||||
Point point = new Point();
|
||||
point.setLocation(x, y);
|
||||
return Optional.of(point);
|
||||
}
|
||||
}
|
@ -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);
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
package com.baeldung.algorithms.linesintersection;
|
||||
|
||||
import java.awt.Point;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class LinesIntersectionServiceUnitTest {
|
||||
private LinesIntersectionService service = new LinesIntersectionService();
|
||||
|
||||
@Test
|
||||
public void givenNotParallelLines_whenCalculatePoint_thenPresent() {
|
||||
|
||||
double m1 = 0;
|
||||
double b1 = 0;
|
||||
double m2 = 1;
|
||||
double b2 = -1;
|
||||
|
||||
Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2);
|
||||
|
||||
assertTrue(point.isPresent());
|
||||
assertEquals(point.get().getX(), 1, 0.001);
|
||||
assertEquals(point.get().getY(), 0, 0.001);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParallelLines_whenCalculatePoint_thenEmpty() {
|
||||
double m1 = 1;
|
||||
double b1 = 0;
|
||||
double m2 = 1;
|
||||
double b2 = -1;
|
||||
|
||||
Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2);
|
||||
|
||||
assertFalse(point.isPresent());
|
||||
}
|
||||
}
|
@ -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>
|
||||
|
@ -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
1
aws/.gitignore
vendored
@ -1 +1,2 @@
|
||||
/target/
|
||||
.idea/
|
184
aws/src/main/java/com/baeldung/rds/AWSRDSService.java
Normal file
184
aws/src/main/java/com/baeldung/rds/AWSRDSService.java
Normal 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);
|
||||
}
|
||||
}
|
4
aws/src/main/resources/db.properties
Normal file
4
aws/src/main/resources/db.properties
Normal file
@ -0,0 +1,4 @@
|
||||
db_hostname=<RDS EndPoint>
|
||||
db_username=username
|
||||
db_password=password
|
||||
db_database=mydb
|
@ -1,70 +1,91 @@
|
||||
package com.baeldung.test.dependencyinjection;
|
||||
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.GifFileEditor;
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.JpgFileEditor;
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor;
|
||||
import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor;
|
||||
import com.baeldung.dependencyinjection.loggers.TimeLogger;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.within;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.time.LocalTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
import org.jboss.weld.environment.se.Weld;
|
||||
import org.jboss.weld.environment.se.WeldContainer;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor;
|
||||
import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor;
|
||||
import com.baeldung.dependencyinjection.loggers.TimeLogger;
|
||||
|
||||
public class ImageProcessorUnitTest {
|
||||
|
||||
|
||||
private static ImageFileProcessor imageFileProcessor;
|
||||
private static SimpleDateFormat dateFormat;
|
||||
private static Calendar calendar;
|
||||
|
||||
|
||||
|
||||
@BeforeClass
|
||||
public static void setImageProcessorInstance() {
|
||||
Weld weld = new Weld();
|
||||
WeldContainer container = weld.initialize();
|
||||
imageFileProcessor = container.select(ImageFileProcessor.class).get();
|
||||
imageFileProcessor = container.select(ImageFileProcessor.class)
|
||||
.get();
|
||||
container.shutdown();
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setSimpleDateFormatInstance() {
|
||||
dateFormat = new SimpleDateFormat("HH:mm");
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setCalendarInstance() {
|
||||
calendar = Calendar.getInstance();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenInjectedPngFileEditorandTimeLoggerInstances_thenTwoAssertions() {
|
||||
assertThat(imageFileProcessor.getImageFileditor()).isInstanceOf(PngFileEditor.class);
|
||||
assertThat(imageFileProcessor.getTimeLogger()).isInstanceOf(TimeLogger.class);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() {
|
||||
String currentTime = dateFormat.format(calendar.getTime());
|
||||
assertThat(imageFileProcessor.openFile("file1.png")).isEqualTo("Opening PNG file file1.png at: " + currentTime);
|
||||
public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() throws ParseException {
|
||||
LocalTime currentTime = LocalTime.now();
|
||||
|
||||
String openFileLog = imageFileProcessor.openFile("file1.png");
|
||||
assertThat(openFileLog).contains("Opening PNG file file1.png at: ");
|
||||
|
||||
LocalTime loggedTime = getLoggedTime(openFileLog);
|
||||
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() {
|
||||
String currentTime = dateFormat.format(calendar.getTime());
|
||||
assertThat(imageFileProcessor.editFile("file1.png")).isEqualTo("Editing PNG file file1.png at: " + currentTime);
|
||||
public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() throws ParseException {
|
||||
LocalTime currentTime = LocalTime.now();
|
||||
|
||||
String editFileLog = imageFileProcessor.editFile("file1.png");
|
||||
assertThat(editFileLog).contains("Editing PNG file file1.png at: ");
|
||||
|
||||
LocalTime loggedTime = getLoggedTime(editFileLog);
|
||||
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() {
|
||||
String currentTime = dateFormat.format(calendar.getTime());
|
||||
assertThat(imageFileProcessor.writeFile("file1.png")).isEqualTo("Writing PNG file file1.png at: " + currentTime);
|
||||
public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() throws ParseException {
|
||||
LocalTime currentTime = LocalTime.now();
|
||||
|
||||
String writeFileLog = imageFileProcessor.writeFile("file1.png");
|
||||
assertThat(writeFileLog).contains("Writing PNG file file1.png at: ");
|
||||
|
||||
LocalTime loggedTime = getLoggedTime(writeFileLog);
|
||||
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() {
|
||||
String currentTime = dateFormat.format(calendar.getTime());
|
||||
assertThat(imageFileProcessor.saveFile("file1.png")).isEqualTo("Saving PNG file file1.png at: " + currentTime);
|
||||
public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() throws ParseException {
|
||||
LocalTime currentTime = LocalTime.now();
|
||||
|
||||
String saveFileLog = imageFileProcessor.saveFile("file1.png");
|
||||
assertThat(saveFileLog).contains("Saving PNG file file1.png at: ");
|
||||
|
||||
LocalTime loggedTime = getLoggedTime(saveFileLog);
|
||||
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
|
||||
}
|
||||
|
||||
private LocalTime getLoggedTime(String log) throws ParseException {
|
||||
String logTimeString = log.split("at: ")[1];
|
||||
|
||||
int hour = Integer.valueOf(logTimeString.split(":")[0]);
|
||||
int minutes = Integer.valueOf(logTimeString.split(":")[1]);
|
||||
|
||||
LocalTime loggedTime = LocalTime.of(hour, minutes);
|
||||
return loggedTime;
|
||||
}
|
||||
}
|
@ -15,24 +15,17 @@
|
||||
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
|
||||
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)
|
||||
- [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java)
|
||||
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
|
||||
- [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode)
|
||||
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
|
||||
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
|
||||
- [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods)
|
||||
- [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency)
|
||||
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
|
||||
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
|
||||
- [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator)
|
||||
- [Java 8 Math New Methods](http://www.baeldung.com/java-8-math)
|
||||
- [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations)
|
||||
- [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max)
|
||||
- [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization)
|
||||
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
|
||||
- [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get)
|
||||
- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
|
||||
- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection)
|
||||
- [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)
|
||||
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
|
||||
- [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time)
|
||||
|
@ -0,0 +1,9 @@
|
||||
package com.baeldung.optional;
|
||||
|
||||
public class PersonRepository {
|
||||
|
||||
public String findNameById(String id) {
|
||||
return id == null ? null : "Name";
|
||||
}
|
||||
|
||||
}
|
@ -5,25 +5,22 @@
|
||||
*/
|
||||
package com.baeldung.nullsafecollectionstreams;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Kwaje Anthony <kwajeanthony@gmail.com>
|
||||
*/
|
||||
public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest {
|
||||
|
||||
private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance =
|
||||
new NullSafeCollectionStreamsUsingJava8OptionalContainer();
|
||||
|
||||
private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = new NullSafeCollectionStreamsUsingJava8OptionalContainer();
|
||||
|
||||
@Test
|
||||
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
|
||||
@ -49,5 +46,5 @@ public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest {
|
||||
assertEquals(iter1.next(), iter2.next());
|
||||
assert !iter1.hasNext() && !iter2.hasNext();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
@ -1,11 +1,11 @@
|
||||
package com.baeldung.throwsexception;
|
||||
package com.baeldung.optional;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
public class PersonRepositoryUnitTest {
|
||||
@ -13,29 +13,29 @@ public class PersonRepositoryUnitTest {
|
||||
PersonRepository personRepository = new PersonRepository();
|
||||
|
||||
@Test
|
||||
public void whenIdIsNull_thenExceptionIsThrown() throws Exception {
|
||||
assertThrows(Exception.class,
|
||||
public void whenIdIsNull_thenExceptionIsThrown() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() ->
|
||||
Optional
|
||||
.ofNullable(personRepository.findNameById(null))
|
||||
.orElseThrow(Exception::new));
|
||||
.orElseThrow(IllegalArgumentException::new));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIdIsNonNull_thenNoExceptionIsThrown() throws Exception {
|
||||
public void whenIdIsNonNull_thenNoExceptionIsThrown() {
|
||||
assertAll(
|
||||
() ->
|
||||
Optional
|
||||
.ofNullable(personRepository.findNameById("id"))
|
||||
.orElseThrow(Exception::new));
|
||||
.orElseThrow(RuntimeException::new));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIdIsNonNull_thenShouldReturnNameUpperCase() throws Exception {
|
||||
public void whenIdNonNull_thenReturnsNameUpperCase() {
|
||||
String name = Optional
|
||||
.ofNullable(personRepository.findNameById("id"))
|
||||
.map(String::toUpperCase)
|
||||
.orElseThrow(Exception::new);
|
||||
.orElseThrow(RuntimeException::new);
|
||||
|
||||
assertEquals("NAME", name);
|
||||
}
|
@ -1,7 +1,6 @@
|
||||
package com.baeldung.util;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
@ -10,8 +9,6 @@ import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.temporal.ChronoField;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.DateTimeUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CurrentDateTimeUnitTest {
|
||||
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.java9.process;
|
||||
|
||||
import java.util.Scanner;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class ChildProcess {
|
||||
|
||||
public static void main(String[] args) {
|
||||
@SuppressWarnings("resource")
|
||||
Scanner input = new Scanner(System.in);
|
||||
Logger log = Logger.getLogger(ChildProcess.class.getName());
|
||||
log.log(Level.INFO, input.nextLine());
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
package com.baeldung.java9.process;
|
||||
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class OutputStreamExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Logger log = Logger.getLogger(OutputStreamExample.class.getName());
|
||||
log.log(Level.INFO, Integer.toString(sum(1,2)));
|
||||
}
|
||||
|
||||
public static int sum(int a, int b) {
|
||||
return a + b;
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package com.baeldung.java9.process;
|
||||
|
||||
public class ProcessCompilationError {
|
||||
//This method has been written to generate error to display
|
||||
//how process errorStream() can consume error
|
||||
public static void();
|
||||
}
|
@ -0,0 +1,110 @@
|
||||
package com.baeldung.java9.process;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.Writer;
|
||||
import java.util.Optional;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class ProcessUnderstanding {
|
||||
|
||||
public static int compileAndRunJavaProgram() throws IOException {
|
||||
Process process = Runtime.getRuntime()
|
||||
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
|
||||
process = Runtime.getRuntime()
|
||||
.exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
|
||||
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
||||
int value = Integer.parseInt(output.readLine());
|
||||
return value;
|
||||
}
|
||||
|
||||
public static String getErrorStreamExample() throws IOException {
|
||||
Process process = Runtime.getRuntime()
|
||||
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java");
|
||||
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
|
||||
String errorString = error.readLine();
|
||||
return errorString;
|
||||
}
|
||||
|
||||
public static void creatingNewProcess() throws IOException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
}
|
||||
|
||||
public static int filterProcessWithStreamsInSpecificRangeReturnCount() {
|
||||
return (int) ProcessHandle.allProcesses()
|
||||
.filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000))
|
||||
.count();
|
||||
}
|
||||
|
||||
public static void destroyingProcessCreatedBySameProcess() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
Thread.sleep(10000);
|
||||
process.destroy();
|
||||
}
|
||||
|
||||
public static void destroyingProcessCreatedByDifferentProcess() {
|
||||
// find out the process id of current running task by checking
|
||||
// task manager in windows and enter the integer value
|
||||
Optional<ProcessHandle> optionalProcessHandle = ProcessHandle.of(5232);
|
||||
ProcessHandle processHandle = optionalProcessHandle.get();
|
||||
processHandle.destroy();
|
||||
}
|
||||
|
||||
public static int waitForExample() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
return process.waitFor();
|
||||
}
|
||||
|
||||
public static int exitValueExample() throws IOException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
process.destroy();
|
||||
return process.exitValue();
|
||||
}
|
||||
|
||||
public static void destroyExample() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
Thread.sleep(10000);
|
||||
process.destroy();
|
||||
}
|
||||
|
||||
public static void destroyForciblyExample() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
Thread.sleep(10000);
|
||||
process.destroy();
|
||||
if (process.isAlive()) {
|
||||
process.destroyForcibly();
|
||||
}
|
||||
}
|
||||
|
||||
public static void outputStreamDemo() throws IOException, InterruptedException {
|
||||
Logger log = Logger.getLogger(ProcessUnderstanding.class.getName());
|
||||
Process pr = Runtime.getRuntime()
|
||||
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ChildProcess.java");
|
||||
final Process process = Runtime.getRuntime()
|
||||
.exec("java -cp src/main/java com.baeldung.java9.process.ChildProcess");
|
||||
try (Writer w = new OutputStreamWriter(process.getOutputStream(), "UTF-8")) {
|
||||
w.write("send to child\n");
|
||||
}
|
||||
new Thread(() -> {
|
||||
try {
|
||||
int c;
|
||||
while ((c = process.getInputStream()
|
||||
.read()) != -1)
|
||||
System.out.write((byte) c);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}).start();
|
||||
// send to child
|
||||
log.log(Level.INFO, "rc=" + process.waitFor());
|
||||
}
|
||||
}
|
@ -0,0 +1,121 @@
|
||||
package com.baeldung.java9.process;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.lang.String;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.lang.Integer;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ProcessUnderstandingTest {
|
||||
|
||||
@Test
|
||||
public void givenSourceProgram_whenExecutedFromAnotherProgram_thenSourceProgramOutput3() throws IOException {
|
||||
Process process = Runtime.getRuntime()
|
||||
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
|
||||
process = Runtime.getRuntime()
|
||||
.exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
|
||||
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
||||
int value = Integer.parseInt(output.readLine());
|
||||
assertEquals(3, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSourceProgram_whenReadingInputStream_thenFirstLineEquals3() throws IOException {
|
||||
Process process = Runtime.getRuntime()
|
||||
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
|
||||
process = Runtime.getRuntime()
|
||||
.exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
|
||||
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
||||
int value = Integer.parseInt(output.readLine());
|
||||
assertEquals(3, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSubProcess_whenEncounteringError_thenErrorStreamNotNull() throws IOException {
|
||||
Process process = Runtime.getRuntime()
|
||||
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java");
|
||||
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
|
||||
String errorString = error.readLine();
|
||||
assertNotNull(errorString);
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_whenStarted_thenStartSuccessIsAlive() throws IOException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
assertTrue(builder.start().isAlive());
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_whenDestroying_thenProcessNotAlive() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
Thread.sleep(10000);
|
||||
process.destroy();
|
||||
assertFalse(process.isAlive());
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_whenAlive_thenDestroyForcibly() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
Thread.sleep(10000);
|
||||
process.destroy();
|
||||
if (process.isAlive()) {
|
||||
process.destroyForcibly();
|
||||
}
|
||||
assertFalse(process.isAlive());
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_whenDestroyed_thenCheckIfAlive() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
Thread.sleep(10000);
|
||||
process.destroy();
|
||||
assertFalse(process.isAlive());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenProcessNotCreated_fromWithinJavaApplicationDestroying_thenProcessNotAlive() {
|
||||
Optional<ProcessHandle> optionalProcessHandle = ProcessHandle.of(5232);
|
||||
ProcessHandle processHandle = optionalProcessHandle.get();
|
||||
processHandle.destroy();
|
||||
assertFalse(processHandle.isAlive());
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_whenCurrentThreadWaitsIndefinitelyuntilSubProcessEnds_thenProcessWaitForReturnsGrt0() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
assertThat(process.waitFor() >= 0);
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_whenCurrentThreadWaitsAndSubProcessNotTerminated_thenProcessWaitForReturnsFalse() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
assertFalse(process.waitFor(1, TimeUnit.SECONDS));
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_whenCurrentThreadWillNotWaitIndefinitelyforSubProcessToEnd_thenProcessExitValueReturnsGrt0() throws IOException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
assertThat(process.exitValue() >= 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRunningProcesses_whenFilterOnProcessIdRange_thenGetSelectedProcessPid() {
|
||||
assertThat(((int) ProcessHandle.allProcesses()
|
||||
.filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000))
|
||||
.count()) > 0);
|
||||
}
|
||||
}
|
@ -37,3 +37,9 @@
|
||||
- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map)
|
||||
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
|
||||
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
|
||||
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
|
||||
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
|
||||
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
|
||||
- [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)
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.list;
|
||||
package com.baeldung.java.list;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
@ -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();
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -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;
|
||||
|
@ -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();
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -2,6 +2,7 @@ package com.baeldung.collection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Assert;
|
||||
@ -35,8 +36,9 @@ public class StreamOperateAndRemoveUnitTest {
|
||||
@Test
|
||||
public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveIf_thenListContains5Items() {
|
||||
|
||||
itemList.stream().filter(item -> item.isQualified()).forEach(item -> item.operate());
|
||||
itemList.removeIf(item -> item.isQualified());
|
||||
final Predicate<Item> isQualified = item -> item.isQualified();
|
||||
itemList.stream().filter(isQualified).forEach(item -> item.operate());
|
||||
itemList.removeIf(isQualified);
|
||||
|
||||
Assert.assertEquals(5, itemList.size());
|
||||
}
|
||||
|
@ -1,13 +1,17 @@
|
||||
package com.baeldung.list;
|
||||
package com.baeldung.java.list;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CopyListServiceUnitTest {
|
||||
|
@ -1,10 +1,12 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.SequenceInputStream;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
@ -74,6 +76,28 @@ public class JavaXToInputStreamUnitTest {
|
||||
IOUtils.closeQuietly(targetStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingPlainJava_whenConvertingFileToDataInputStream_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/test/resources/sample.txt");
|
||||
final InputStream targetStream = new DataInputStream(new FileInputStream(initialFile));
|
||||
|
||||
IOUtils.closeQuietly(targetStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingPlainJava_whenConvertingFileToSequenceInputStream_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/test/resources/sample.txt");
|
||||
final File anotherFile = new File("src/test/resources/anothersample.txt");
|
||||
final InputStream targetStream = new FileInputStream(initialFile);
|
||||
final InputStream anotherTargetStream = new FileInputStream(anotherFile);
|
||||
|
||||
InputStream sequenceTargetStream = new SequenceInputStream(targetStream, anotherTargetStream);
|
||||
|
||||
IOUtils.closeQuietly(targetStream);
|
||||
IOUtils.closeQuietly(anotherTargetStream);
|
||||
IOUtils.closeQuietly(sequenceTargetStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenConvertingFileToInputStream_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/test/resources/sample.txt");
|
||||
|
1
core-java-io/src/test/resources/anothersample.txt
Normal file
1
core-java-io/src/test/resources/anothersample.txt
Normal file
@ -0,0 +1 @@
|
||||
...Continues
|
@ -0,0 +1,45 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.string;
|
||||
|
||||
/**
|
||||
* @author swpraman
|
||||
*
|
||||
*/
|
||||
public class AppendCharAtPositionX {
|
||||
|
||||
public String addCharUsingCharArray(String str, char ch, int position) {
|
||||
validate(str, position);
|
||||
int len = str.length();
|
||||
char[] updatedArr = new char[len + 1];
|
||||
str.getChars(0, position, updatedArr, 0);
|
||||
updatedArr[position] = ch;
|
||||
str.getChars(position, len, updatedArr, position + 1);
|
||||
return new String(updatedArr);
|
||||
}
|
||||
|
||||
public String addCharUsingSubstring(String str, char ch, int position) {
|
||||
validate(str, position);
|
||||
return str.substring(0, position) + ch + str.substring(position);
|
||||
}
|
||||
|
||||
public String addCharUsingStringBuilder(String str, char ch, int position) {
|
||||
validate(str, position);
|
||||
StringBuilder sb = new StringBuilder(str);
|
||||
sb.insert(position, ch);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void validate(String str, int position) {
|
||||
if (str == null) {
|
||||
throw new IllegalArgumentException("Str should not be null");
|
||||
}
|
||||
int len = str.length();
|
||||
if (position < 0 || position > len) {
|
||||
throw new IllegalArgumentException("position[" + position + "] should be "
|
||||
+ "in the range 0.." + len + " for string " + str);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -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() {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -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 {
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -1,16 +1,10 @@
|
||||
package com.baeldung.throwsexception;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
public class PersonRepository {
|
||||
|
||||
@Nullable
|
||||
public String findNameById(String id) {
|
||||
return id == null ? null : "Name";
|
||||
}
|
||||
|
||||
public List<String> findAll() throws SQLException {
|
||||
throw new SQLException();
|
||||
}
|
||||
|
@ -0,0 +1,110 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.string;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* @author swpraman
|
||||
*
|
||||
*/
|
||||
public class AppendCharAtPositionXUnitTest {
|
||||
|
||||
private AppendCharAtPositionX appendCharAtPosition = new AppendCharAtPositionX();
|
||||
private String word = "Titanc";
|
||||
private char letter = 'i';
|
||||
|
||||
@Test
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtBeginning_shouldAddCharacter() {
|
||||
assertEquals("iTitanc", appendCharAtPosition.addCharUsingCharArray(word, letter, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSubstringAndCharacterAddedAtBeginning_shouldAddCharacter() {
|
||||
assertEquals("iTitanc", appendCharAtPosition.addCharUsingSubstring(word, letter, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtBeginning_shouldAddCharacter() {
|
||||
assertEquals("iTitanc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtMiddle_shouldAddCharacter() {
|
||||
assertEquals("Titianc", appendCharAtPosition.addCharUsingCharArray(word, letter, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSubstringAndCharacterAddedAtMiddle_shouldAddCharacter() {
|
||||
assertEquals("Titianc", appendCharAtPosition.addCharUsingSubstring(word, letter, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtMiddle_shouldAddCharacter() {
|
||||
assertEquals("Titianc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtEnd_shouldAddCharacter() {
|
||||
assertEquals("Titanci", appendCharAtPosition.addCharUsingCharArray(word, letter, word.length()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSubstringAndCharacterAddedAtEnd_shouldAddCharacter() {
|
||||
assertEquals("Titanci", appendCharAtPosition.addCharUsingSubstring(word, letter, word.length()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtEnd_shouldAddCharacter() {
|
||||
assertEquals("Titanci", appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length()));
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtNegativePosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingSubstringAndCharacterAddedAtNegativePosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtNegativePosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtInvalidPosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingSubstringAndCharacterAddedAtInvalidPosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtInvalidPosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingSubstringAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
|
||||
}
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
@ -1,85 +1,126 @@
|
||||
<?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>
|
||||
<artifactId>core-kotlin</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
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>core-kotlin</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-kotlin</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../parent-kotlin</relativePath>
|
||||
</parent>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-kotlin</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../parent-kotlin</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.spek</groupId>
|
||||
<artifactId>spek-api</artifactId>
|
||||
<version>1.1.5</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.spek</groupId>
|
||||
<artifactId>spek-subject-extension</artifactId>
|
||||
<version>1.1.5</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.spek</groupId>
|
||||
<artifactId>spek-junit-platform-engine</artifactId>
|
||||
<version>1.1.5</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>khttp</groupId>
|
||||
<artifactId>khttp</artifactId>
|
||||
<version>${khttp.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.nhaarman</groupId>
|
||||
<artifactId>mockito-kotlin</artifactId>
|
||||
<version>${mockito-kotlin.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.salomonbrys.kodein</groupId>
|
||||
<artifactId>kodein</artifactId>
|
||||
<version>${kodein.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.beust</groupId>
|
||||
<artifactId>klaxon</artifactId>
|
||||
<version>${klaxon.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>exposed</id>
|
||||
<name>exposed</name>
|
||||
<url>https://dl.bintray.com/kotlin/exposed</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<properties>
|
||||
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
|
||||
<kodein.version>4.1.0</kodein.version>
|
||||
<klaxon.version>3.0.4</klaxon.version>
|
||||
<khttp.version>0.1.0</khttp.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<junit.platform.version>1.1.1</junit.platform.version>
|
||||
<junit.vintage.version>5.2.0</junit.vintage.version>
|
||||
<assertj.version>3.10.0</assertj.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.spek</groupId>
|
||||
<artifactId>spek-api</artifactId>
|
||||
<version>1.1.5</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.spek</groupId>
|
||||
<artifactId>spek-subject-extension</artifactId>
|
||||
<version>1.1.5</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.spek</groupId>
|
||||
<artifactId>spek-junit-platform-engine</artifactId>
|
||||
<version>1.1.5</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>khttp</groupId>
|
||||
<artifactId>khttp</artifactId>
|
||||
<version>${khttp.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.nhaarman</groupId>
|
||||
<artifactId>mockito-kotlin</artifactId>
|
||||
<version>${mockito-kotlin.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.salomonbrys.kodein</groupId>
|
||||
<artifactId>kodein</artifactId>
|
||||
<version>${kodein.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.beust</groupId>
|
||||
<artifactId>klaxon</artifactId>
|
||||
<version>${klaxon.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.exposed</groupId>
|
||||
<artifactId>exposed</artifactId>
|
||||
<version>${exposed.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<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>
|
||||
|
||||
</project>
|
||||
<properties>
|
||||
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
|
||||
<kodein.version>4.1.0</kodein.version>
|
||||
<klaxon.version>3.0.4</klaxon.version>
|
||||
<khttp.version>0.1.0</khttp.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<junit.platform.version>1.1.1</junit.platform.version>
|
||||
<junit.vintage.version>5.2.0</junit.vintage.version>
|
||||
<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>
|
||||
|
@ -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)
|
||||
}
|
||||
}
|
15
core-kotlin/src/main/kotlin/com/baeldung/fuel/Post.kt
Normal file
15
core-kotlin/src/main/kotlin/com/baeldung/fuel/Post.kt
Normal 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)
|
||||
}
|
||||
}
|
@ -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
|
||||
}
|
||||
}
|
@ -93,6 +93,7 @@ internal class BuilderPatternUnitTest {
|
||||
Assertions.assertNull(foodOrder.fish)
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
fun whenBuildingFoodOrderApplySettingValues_thenFieldsNotNull() {
|
||||
|
||||
|
@ -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()
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,333 @@
|
||||
package com.baeldung.kotlin.exposed
|
||||
|
||||
import org.jetbrains.exposed.dao.*
|
||||
import org.jetbrains.exposed.sql.*
|
||||
import org.jetbrains.exposed.sql.transactions.TransactionManager
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
import org.junit.Test
|
||||
import java.sql.DriverManager
|
||||
import kotlin.test.*
|
||||
|
||||
class ExposedTest {
|
||||
|
||||
@Test
|
||||
fun whenH2Database_thenConnectionSuccessful() {
|
||||
val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
|
||||
transaction {
|
||||
assertEquals(1.4.toBigDecimal(), database.version)
|
||||
assertEquals("h2", database.vendor)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenH2DatabaseWithCredentials_thenConnectionSuccessful() {
|
||||
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver", user = "myself", password = "secret")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenH2DatabaseWithManualConnection_thenConnectionSuccessful() {
|
||||
var connected = false
|
||||
Database.connect({ connected = true; DriverManager.getConnection("jdbc:h2:mem:test;MODE=MySQL") })
|
||||
assertEquals(false, connected)
|
||||
transaction {
|
||||
addLogger(StdOutSqlLogger)
|
||||
assertEquals(false, connected)
|
||||
SchemaUtils.create(Cities)
|
||||
assertEquals(true, connected)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenManualCommit_thenOk() {
|
||||
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
|
||||
transaction {
|
||||
assertTrue(this is Transaction)
|
||||
commit()
|
||||
commit()
|
||||
commit()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenInsert_thenGeneratedKeys() {
|
||||
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
|
||||
transaction {
|
||||
SchemaUtils.create(StarWarsFilms)
|
||||
val id = StarWarsFilms.insertAndGetId {
|
||||
it[name] = "The Last Jedi"
|
||||
it[sequelId] = 8
|
||||
it[director] = "Rian Johnson"
|
||||
}
|
||||
assertEquals(1, id.value)
|
||||
val insert = StarWarsFilms.insert {
|
||||
it[name] = "The Force Awakens"
|
||||
it[sequelId] = 7
|
||||
it[director] = "J.J. Abrams"
|
||||
}
|
||||
assertEquals(2, insert[StarWarsFilms.id]?.value)
|
||||
val selectAll = StarWarsFilms.selectAll()
|
||||
selectAll.forEach {
|
||||
assertTrue { it[StarWarsFilms.sequelId] >= 7 }
|
||||
}
|
||||
StarWarsFilms.slice(StarWarsFilms.name, StarWarsFilms.director).selectAll()
|
||||
.forEach {
|
||||
assertTrue { it[StarWarsFilms.name].startsWith("The") }
|
||||
}
|
||||
val select = StarWarsFilms.select { (StarWarsFilms.director like "J.J.%") and (StarWarsFilms.sequelId eq 7) }
|
||||
assertEquals(1, select.count())
|
||||
StarWarsFilms.update ({ StarWarsFilms.sequelId eq 8 }) {
|
||||
it[name] = "Episode VIII – The Last Jedi"
|
||||
with(SqlExpressionBuilder) {
|
||||
it.update(StarWarsFilms.sequelId, StarWarsFilms.sequelId + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenForeignKey_thenAutoJoin() {
|
||||
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
|
||||
transaction {
|
||||
addLogger(StdOutSqlLogger)
|
||||
SchemaUtils.create(StarWarsFilms, Players)
|
||||
StarWarsFilms.insert {
|
||||
it[name] = "The Last Jedi"
|
||||
it[sequelId] = 8
|
||||
it[director] = "Rian Johnson"
|
||||
}
|
||||
StarWarsFilms.insert {
|
||||
it[name] = "The Force Awakens"
|
||||
it[sequelId] = 7
|
||||
it[director] = "J.J. Abrams"
|
||||
}
|
||||
Players.insert {
|
||||
it[name] = "Mark Hamill"
|
||||
it[sequelId] = 7
|
||||
}
|
||||
Players.insert {
|
||||
it[name] = "Mark Hamill"
|
||||
it[sequelId] = 8
|
||||
}
|
||||
val simpleInnerJoin = (StarWarsFilms innerJoin Players).selectAll()
|
||||
assertEquals(2, simpleInnerJoin.count())
|
||||
simpleInnerJoin.forEach {
|
||||
assertNotNull(it[StarWarsFilms.name])
|
||||
assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId])
|
||||
assertEquals("Mark Hamill", it[Players.name])
|
||||
}
|
||||
val innerJoinWithCondition = (StarWarsFilms innerJoin Players)
|
||||
.select { StarWarsFilms.sequelId eq Players.sequelId }
|
||||
assertEquals(2, innerJoinWithCondition.count())
|
||||
innerJoinWithCondition.forEach {
|
||||
assertNotNull(it[StarWarsFilms.name])
|
||||
assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId])
|
||||
assertEquals("Mark Hamill", it[Players.name])
|
||||
}
|
||||
val complexInnerJoin = Join(StarWarsFilms, Players, joinType = JoinType.INNER, onColumn = StarWarsFilms.sequelId, otherColumn = Players.sequelId, additionalConstraint = {
|
||||
StarWarsFilms.sequelId eq 8
|
||||
}).selectAll()
|
||||
assertEquals(1, complexInnerJoin.count())
|
||||
complexInnerJoin.forEach {
|
||||
assertNotNull(it[StarWarsFilms.name])
|
||||
assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId])
|
||||
assertEquals("Mark Hamill", it[Players.name])
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenJoinWithAlias_thenFun() {
|
||||
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
|
||||
transaction {
|
||||
addLogger(StdOutSqlLogger)
|
||||
SchemaUtils.create(StarWarsFilms, Players)
|
||||
StarWarsFilms.insert {
|
||||
it[name] = "The Last Jedi"
|
||||
it[sequelId] = 8
|
||||
it[director] = "Rian Johnson"
|
||||
}
|
||||
StarWarsFilms.insert {
|
||||
it[name] = "The Force Awakens"
|
||||
it[sequelId] = 7
|
||||
it[director] = "J.J. Abrams"
|
||||
}
|
||||
val sequel = StarWarsFilms.alias("sequel")
|
||||
Join(StarWarsFilms, sequel,
|
||||
additionalConstraint = { sequel[StarWarsFilms.sequelId] eq StarWarsFilms.sequelId + 1 })
|
||||
.selectAll().forEach {
|
||||
assertEquals(it[sequel[StarWarsFilms.sequelId]], it[StarWarsFilms.sequelId] + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenEntity_thenDAO() {
|
||||
val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
|
||||
val connection = database.connector.invoke() //Keep a connection open so the DB is not destroyed after the first transaction
|
||||
val inserted = transaction {
|
||||
addLogger(StdOutSqlLogger)
|
||||
SchemaUtils.create(StarWarsFilms, Players)
|
||||
val theLastJedi = StarWarsFilm.new {
|
||||
name = "The Last Jedi"
|
||||
sequelId = 8
|
||||
director = "Rian Johnson"
|
||||
}
|
||||
assertFalse(TransactionManager.current().entityCache.inserts.isEmpty())
|
||||
assertEquals(1, theLastJedi.id.value) //Reading this causes a flush
|
||||
assertTrue(TransactionManager.current().entityCache.inserts.isEmpty())
|
||||
theLastJedi
|
||||
}
|
||||
transaction {
|
||||
val theLastJedi = StarWarsFilm.findById(1)
|
||||
assertNotNull(theLastJedi)
|
||||
assertEquals(inserted.id, theLastJedi?.id)
|
||||
}
|
||||
connection.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenManyToOne_thenNavigation() {
|
||||
val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
|
||||
val connection = database.connector.invoke()
|
||||
transaction {
|
||||
addLogger(StdOutSqlLogger)
|
||||
SchemaUtils.create(StarWarsFilms, Players, Users, UserRatings)
|
||||
val theLastJedi = StarWarsFilm.new {
|
||||
name = "The Last Jedi"
|
||||
sequelId = 8
|
||||
director = "Rian Johnson"
|
||||
}
|
||||
val someUser = User.new {
|
||||
name = "Some User"
|
||||
}
|
||||
val rating = UserRating.new {
|
||||
value = 9
|
||||
user = someUser
|
||||
film = theLastJedi
|
||||
}
|
||||
assertEquals(theLastJedi, rating.film)
|
||||
assertEquals(someUser, rating.user)
|
||||
assertEquals(rating, theLastJedi.ratings.first())
|
||||
}
|
||||
transaction {
|
||||
val theLastJedi = StarWarsFilm.find { StarWarsFilms.sequelId eq 8 }.first()
|
||||
val ratings = UserRating.find { UserRatings.film eq theLastJedi.id }
|
||||
assertEquals(1, ratings.count())
|
||||
val rating = ratings.first()
|
||||
assertEquals("Some User", rating.user.name)
|
||||
assertEquals(rating, theLastJedi.ratings.first())
|
||||
UserRating.new {
|
||||
value = 8
|
||||
user = rating.user
|
||||
film = theLastJedi
|
||||
}
|
||||
assertEquals(2, theLastJedi.ratings.count())
|
||||
}
|
||||
connection.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenManyToMany_thenAssociation() {
|
||||
val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
|
||||
val connection = database.connector.invoke()
|
||||
val film = transaction {
|
||||
SchemaUtils.create(StarWarsFilms)
|
||||
StarWarsFilm.new {
|
||||
name = "The Last Jedi"
|
||||
sequelId = 8
|
||||
director = "Rian Johnson"
|
||||
}
|
||||
}
|
||||
|
||||
val actor = transaction {
|
||||
SchemaUtils.create(Actors)
|
||||
Actor.new {
|
||||
firstname = "Daisy"
|
||||
lastname = "Ridley"
|
||||
}
|
||||
}
|
||||
|
||||
transaction {
|
||||
SchemaUtils.create(StarWarsFilmActors)
|
||||
film.actors = SizedCollection(listOf(actor))
|
||||
}
|
||||
connection.close()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
object Cities: IntIdTable() {
|
||||
val name = varchar("name", 50)
|
||||
}
|
||||
|
||||
object StarWarsFilms_Simple : Table() {
|
||||
val id = integer("id").autoIncrement().primaryKey()
|
||||
val sequelId = integer("sequel_id").uniqueIndex()
|
||||
val name = varchar("name", 50)
|
||||
val director = varchar("director", 50)
|
||||
}
|
||||
|
||||
object StarWarsFilms : IntIdTable() {
|
||||
val sequelId = integer("sequel_id").uniqueIndex()
|
||||
val name = varchar("name", 50)
|
||||
val director = varchar("director", 50)
|
||||
}
|
||||
|
||||
object Players : Table() {
|
||||
//val sequelId = integer("sequel_id").uniqueIndex().references(StarWarsFilms.sequelId)
|
||||
val sequelId = reference("sequel_id", StarWarsFilms.sequelId).uniqueIndex()
|
||||
//val filmId = reference("film_id", StarWarsFilms).nullable()
|
||||
val name = varchar("name", 50)
|
||||
}
|
||||
|
||||
class StarWarsFilm(id: EntityID<Int>) : Entity<Int>(id) {
|
||||
companion object : EntityClass<Int, StarWarsFilm>(StarWarsFilms)
|
||||
|
||||
var sequelId by StarWarsFilms.sequelId
|
||||
var name by StarWarsFilms.name
|
||||
var director by StarWarsFilms.director
|
||||
var actors by Actor via StarWarsFilmActors
|
||||
val ratings by UserRating referrersOn UserRatings.film
|
||||
}
|
||||
|
||||
object Users: IntIdTable() {
|
||||
val name = varchar("name", 50)
|
||||
}
|
||||
|
||||
object UserRatings: IntIdTable() {
|
||||
val value = long("value")
|
||||
val film = reference("film", StarWarsFilms)
|
||||
val user = reference("user", Users)
|
||||
}
|
||||
|
||||
class User(id: EntityID<Int>): IntEntity(id) {
|
||||
companion object : IntEntityClass<User>(Users)
|
||||
|
||||
var name by Users.name
|
||||
}
|
||||
|
||||
class UserRating(id: EntityID<Int>): IntEntity(id) {
|
||||
companion object : IntEntityClass<UserRating>(UserRatings)
|
||||
|
||||
var value by UserRatings.value
|
||||
var film by StarWarsFilm referencedOn UserRatings.film
|
||||
var user by User referencedOn UserRatings.user
|
||||
}
|
||||
|
||||
object Actors: IntIdTable() {
|
||||
val firstname = varchar("firstname", 50)
|
||||
val lastname = varchar("lastname", 50)
|
||||
}
|
||||
|
||||
class Actor(id: EntityID<Int>): IntEntity(id) {
|
||||
companion object : IntEntityClass<Actor>(Actors)
|
||||
|
||||
var firstname by Actors.firstname
|
||||
var lastname by Actors.lastname
|
||||
}
|
||||
|
||||
object StarWarsFilmActors : Table() {
|
||||
val starWarsFilm = reference("starWarsFilm", StarWarsFilms).primaryKey(0)
|
||||
val actor = reference("actor", Actors).primaryKey(1)
|
||||
}
|
@ -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>
|
||||
|
@ -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>
|
||||
|
@ -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));
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
14
drools/src/main/resources/courseSchedule.drl
Normal file
14
drools/src/main/resources/courseSchedule.drl
Normal 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
|
@ -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>
|
@ -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>
|
@ -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());
|
||||
}
|
||||
}
|
@ -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>
|
||||
|
@ -17,7 +17,6 @@
|
||||
|
||||
<modules>
|
||||
<module>ejb-remote</module>
|
||||
<module>ejb-client</module>
|
||||
<module>ejb-session-beans</module>
|
||||
</modules>
|
||||
|
||||
|
@ -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>
|
||||
|
@ -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>
|
||||
|
@ -1 +0,0 @@
|
||||
## Relevant articles:
|
@ -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);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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>
|
@ -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>
|
||||
|
@ -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>
|
||||
|
@ -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>
|
||||
|
@ -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>
|
||||
|
@ -0,0 +1,34 @@
|
||||
package com.baeldung.hibernate.joincolumn;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Address {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "ZIP")
|
||||
private String zipCode;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getZipCode() {
|
||||
return zipCode;
|
||||
}
|
||||
|
||||
public void setZipCode(String zipCode) {
|
||||
this.zipCode = zipCode;
|
||||
}
|
||||
}
|
@ -0,0 +1,47 @@
|
||||
package com.baeldung.hibernate.joincolumn;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToOne;
|
||||
|
||||
@Entity
|
||||
public class Email {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
private String address;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "employee_id")
|
||||
private Employee employee;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public Employee getEmployee() {
|
||||
return employee;
|
||||
}
|
||||
|
||||
public void setEmployee(Employee employee) {
|
||||
this.employee = employee;
|
||||
}
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
package com.baeldung.hibernate.joincolumn;
|
||||
|
||||
import java.util.List;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.OneToMany;
|
||||
|
||||
@Entity
|
||||
public class Employee {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@OneToMany(fetch = FetchType.LAZY, mappedBy = "employee")
|
||||
private List<Email> emails;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public List<Email> getEmails() {
|
||||
return emails;
|
||||
}
|
||||
|
||||
public void setEmails(List<Email> emails) {
|
||||
this.emails = emails;
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package com.baeldung.hibernate.joincolumn;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.JoinColumns;
|
||||
import javax.persistence.ManyToOne;
|
||||
|
||||
@Entity
|
||||
public class Office {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumns({
|
||||
@JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
|
||||
@JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
|
||||
})
|
||||
private Address address;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(Address address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
@ -0,0 +1,57 @@
|
||||
package com.baeldung.hibernate.joincolumn;
|
||||
|
||||
import com.baeldung.hibernate.HibernateUtil;
|
||||
import java.io.IOException;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.Transaction;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
|
||||
public class JoinColumnIntegrationTest {
|
||||
|
||||
private Session session;
|
||||
private Transaction transaction;
|
||||
|
||||
@Before
|
||||
public void setUp() throws IOException {
|
||||
session = HibernateUtil.getSessionFactory("hibernate-spatial.properties")
|
||||
.openSession();
|
||||
transaction = session.beginTransaction();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
transaction.rollback();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOfficeEntity_setAddress_shouldPersist() {
|
||||
Office office = new Office();
|
||||
|
||||
Address address = new Address();
|
||||
address.setZipCode("11-111");
|
||||
office.setAddress(address);
|
||||
|
||||
session.save(office);
|
||||
session.flush();
|
||||
session.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeEntity_setEmails_shouldPersist() {
|
||||
Employee employee = new Employee();
|
||||
|
||||
Email email = new Email();
|
||||
email.setAddress("example@email.com");
|
||||
email.setEmployee(employee);
|
||||
|
||||
session.save(employee);
|
||||
session.flush();
|
||||
session.clear();
|
||||
}
|
||||
|
||||
}
|
@ -1,7 +1,6 @@
|
||||
<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>jackson</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>jackson</name>
|
||||
@ -119,17 +118,16 @@
|
||||
|
||||
<properties>
|
||||
<!-- marshalling -->
|
||||
<jackson.version>2.9.4</jackson.version>
|
||||
<jackson.version>2.9.6</jackson.version>
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<joda-time.version>2.9.6</joda-time.version>
|
||||
<gson.version>2.8.0</gson.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<commons-lang3.version>3.8</commons-lang3.version>
|
||||
<joda-time.version>2.10</joda-time.version>
|
||||
<gson.version>2.8.5</gson.version>
|
||||
<commons-collections4.version>4.2</commons-collections4.version>
|
||||
|
||||
<!-- testing -->
|
||||
<rest-assured.version>3.0.1</rest-assured.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<rest-assured.version>3.1.1</rest-assured.version>
|
||||
<assertj.version>3.11.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
@ -1,7 +1,6 @@
|
||||
<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>java-streams</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
@ -15,6 +14,18 @@
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core -->
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
@ -107,6 +118,7 @@
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<jmh.version>1.21</jmh.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<lombok.version>1.16.12</lombok.version>
|
||||
<vavr.version>0.9.0</vavr.version>
|
||||
|
@ -1,15 +1,14 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import org.junit.Test;
|
||||
|
||||
public class PrimitiveStreamsUnitTest {
|
||||
|
||||
@ -17,7 +16,7 @@ public class PrimitiveStreamsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAnArrayOfIntegersWhenMinIsCalledThenCorrectMinIsReturned() {
|
||||
int[] integers = new int[] {20, 98, 12, 7, 35};
|
||||
int[] integers = new int[] { 20, 98, 12, 7, 35 };
|
||||
int min = streams.min(integers); // returns 7
|
||||
|
||||
assertEquals(7, min);
|
||||
@ -66,19 +65,14 @@ public class PrimitiveStreamsUnitTest {
|
||||
@Test
|
||||
public void givenAnArrayWhenSumIsCalledThenTheCorrectSumIsReturned() {
|
||||
|
||||
int sum = Stream.of(33,45)
|
||||
.mapToInt(i -> i)
|
||||
.sum();
|
||||
int sum = Stream.of(33, 45).mapToInt(i -> i).sum();
|
||||
|
||||
assertEquals(78, sum);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIntStreamThenGetTheEvenIntegers() {
|
||||
List<Integer> evenInts = IntStream.rangeClosed(1, 10)
|
||||
.filter(i -> i % 2 == 0)
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
List<Integer> evenInts = IntStream.rangeClosed(1, 10).filter(i -> i % 2 == 0).boxed().collect(Collectors.toList());
|
||||
|
||||
List<Integer> expected = IntStream.of(2, 4, 6, 8, 10).boxed().collect(Collectors.toList());
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
package benchmarking;
|
||||
package com.baeldung.streamordering;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
@ -15,10 +15,9 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
|
||||
public class TestBenchmark
|
||||
public class BenchmarkUnitTest
|
||||
{
|
||||
|
||||
@Test
|
||||
public void
|
||||
launchBenchmark() throws Exception {
|
||||
|
||||
@ -94,4 +93,4 @@ public class TestBenchmark
|
||||
for (int i = 0; i < 1000; i++)
|
||||
bh.consume (list.get (i));
|
||||
}
|
||||
}
|
||||
}
|
@ -1,3 +1,5 @@
|
||||
package com.baeldung.streamordering;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
@ -10,10 +12,9 @@ import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StreamsOrderingUnitTest {
|
||||
|
||||
public class StreamsOrderingTest {
|
||||
|
||||
Logger logger = Logger.getLogger( StreamsOrderingTest.class.getName());
|
||||
Logger logger = Logger.getLogger( StreamsOrderingUnitTest.class.getName());
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
@ -52,6 +52,13 @@
|
||||
<artifactId>icu4j</artifactId>
|
||||
<version>${icu4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.vdurmont</groupId>
|
||||
<artifactId>emoji-java</artifactId>
|
||||
<version>4.0.0</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -0,0 +1,29 @@
|
||||
package com.baeldung.string.sorting;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class AnagramValidator {
|
||||
|
||||
public static boolean isValid(String text, String anagram) {
|
||||
text = prepare(text);
|
||||
anagram = prepare(anagram);
|
||||
|
||||
String sortedText = sort(text);
|
||||
String sortedAnagram = sort(anagram);
|
||||
|
||||
return sortedText.equals(sortedAnagram);
|
||||
}
|
||||
|
||||
private static String sort(String text) {
|
||||
char[] chars = prepare(text).toCharArray();
|
||||
|
||||
Arrays.sort(chars);
|
||||
return new String(chars);
|
||||
}
|
||||
|
||||
private static String prepare(String text) {
|
||||
return text.toLowerCase()
|
||||
.trim()
|
||||
.replaceAll("\\s+", "");
|
||||
}
|
||||
}
|
@ -0,0 +1,78 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.hamcrest.CoreMatchers.not;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.vdurmont.emoji.EmojiParser;
|
||||
|
||||
public class RemovingEmojiFromStringUnitTest {
|
||||
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"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReplaceEmojiUsingLibrary_thenSuccess() {
|
||||
String result = EmojiParser.parseToAliases(text);
|
||||
System.out.println(result);
|
||||
assertThat(result, not(containsString("😅")));
|
||||
assertThat(result, containsString("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"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveEmojiUsingMatcher_thenSuccess() {
|
||||
Pattern pattern = Pattern.compile(regex, Pattern.UNICODE_CHARACTER_CLASS);
|
||||
Matcher matcher = pattern.matcher(text);
|
||||
|
||||
String result = matcher.replaceAll("");
|
||||
System.out.println(result);
|
||||
assertThat(result, not(containsString("😅")));
|
||||
assertThat(result, containsString("à"));
|
||||
assertThat(result, containsString("la"));
|
||||
assertThat(result, containsString("10"));
|
||||
}
|
||||
|
||||
@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"));
|
||||
}
|
||||
|
||||
@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"));
|
||||
}
|
||||
}
|
@ -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(')')));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,67 @@
|
||||
package com.baeldung.string.formatter;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class DateToStringFormatterUnitTest {
|
||||
|
||||
private static final String DATE_FORMAT = "MMM d, yyyy HH:mm a";
|
||||
private static final String EXPECTED_STRING_DATE = "Aug 1, 2018 12:00 PM";
|
||||
private static Date date;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUp() {
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("CET"));
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.set(2018, Calendar.AUGUST, 1, 12, 0);
|
||||
date = calendar.getTime();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDateConvertedUsingSimpleDateFormatToString_thenCorrect() {
|
||||
DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
|
||||
String formattedDate = formatter.format(date);
|
||||
|
||||
assertEquals(EXPECTED_STRING_DATE, formattedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDateConvertedUsingDateFormatToString_thenCorrect() {
|
||||
String formattedDate = DateFormat
|
||||
.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)
|
||||
.format(date);
|
||||
|
||||
assertEquals(EXPECTED_STRING_DATE, formattedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDateConvertedUsingFormatterToString_thenCorrect() {
|
||||
String formattedDate = String.format("%1$tb %1$te, %1$tY %1$tI:%1$tM %1$Tp", date);
|
||||
|
||||
assertEquals(EXPECTED_STRING_DATE, formattedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDateConvertedUsingDateTimeApiToString_thenCorrect() {
|
||||
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(DATE_FORMAT);
|
||||
Instant instant = date.toInstant();
|
||||
LocalDateTime ldt = instant
|
||||
.atZone(ZoneId.of("CET"))
|
||||
.toLocalDateTime();
|
||||
String formattedDate = ldt.format(fmt);
|
||||
|
||||
assertEquals(EXPECTED_STRING_DATE, formattedDate);
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package com.baeldung.string.sorting;
|
||||
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.string.sorting.AnagramValidator;
|
||||
|
||||
class AnagramValidatorUnitTest {
|
||||
|
||||
@Test
|
||||
void givenValidAnagrams_whenSorted_thenEqual() {
|
||||
boolean isValidAnagram = AnagramValidator.isValid("Avida Dollars", "Salvador Dali");
|
||||
|
||||
assertTrue(isValidAnagram);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNotValidAnagrams_whenSorted_thenNotEqual() {
|
||||
boolean isValidAnagram = AnagramValidator.isValid("abc", "def");
|
||||
|
||||
assertFalse(isValidAnagram);
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
package com.baeldung.string.sorting;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class SortStringUnitTest {
|
||||
|
||||
@Test
|
||||
void givenString_whenSort_thenSorted() {
|
||||
String abcd = "bdca";
|
||||
char[] chars = abcd.toCharArray();
|
||||
|
||||
Arrays.sort(chars);
|
||||
String sorted = new String(chars);
|
||||
|
||||
assertThat(sorted).isEqualTo("abcd");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenSortJava8_thenSorted() {
|
||||
String sorted = "bdca".chars()
|
||||
.sorted()
|
||||
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
|
||||
.toString();
|
||||
|
||||
assertThat(sorted).isEqualTo("abcd");
|
||||
}
|
||||
}
|
6
javaxval/bin/.gitignore
vendored
6
javaxval/bin/.gitignore
vendored
@ -1,6 +0,0 @@
|
||||
.classpath
|
||||
.project
|
||||
.settings/
|
||||
target/
|
||||
|
||||
|
@ -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>
|
@ -384,10 +384,6 @@
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<prerequisites>
|
||||
<maven>${maven.min.version}</maven>
|
||||
</prerequisites>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>bintray-mvc-spec-maven</id>
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user