Merge branch 'master' into BAEL-4590
This commit is contained in:
commit
94e2a14ded
|
@ -87,4 +87,7 @@ transaction.log
|
||||||
apache-cxf/cxf-aegis/baeldung.xml
|
apache-cxf/cxf-aegis/baeldung.xml
|
||||||
testing-modules/report-*.json
|
testing-modules/report-*.json
|
||||||
|
|
||||||
libraries-2/*.db
|
libraries-2/*.db
|
||||||
|
|
||||||
|
# SDKMan
|
||||||
|
.sdkmanrc
|
||||||
|
|
|
@ -9,4 +9,5 @@
|
||||||
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
|
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
|
||||||
- [Implementing a 2048 Solver in Java](https://www.baeldung.com/2048-java-solver)
|
- [Implementing a 2048 Solver in Java](https://www.baeldung.com/2048-java-solver)
|
||||||
- [Finding Top K Elements in an Array](https://www.baeldung.com/java-array-top-elements)
|
- [Finding Top K Elements in an Array](https://www.baeldung.com/java-array-top-elements)
|
||||||
|
- [Reversing a Linked List in Java](https://www.baeldung.com/java-reverse-linked-list)
|
||||||
- More articles: [[<-- prev]](/../algorithms-miscellaneous-5)
|
- More articles: [[<-- prev]](/../algorithms-miscellaneous-5)
|
||||||
|
|
|
@ -0,0 +1,30 @@
|
||||||
|
package com.baeldung.algorithms.linkedlist;
|
||||||
|
|
||||||
|
public class LinkedListReversal {
|
||||||
|
|
||||||
|
ListNode reverseList(ListNode head) {
|
||||||
|
ListNode previous = null;
|
||||||
|
ListNode current = head;
|
||||||
|
while (current != null) {
|
||||||
|
ListNode nextElement = current.getNext();
|
||||||
|
current.setNext(previous);
|
||||||
|
previous = current;
|
||||||
|
current = nextElement;
|
||||||
|
}
|
||||||
|
return previous;
|
||||||
|
}
|
||||||
|
|
||||||
|
ListNode reverseListRecursive(ListNode head) {
|
||||||
|
if (head == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (head.getNext() == null) {
|
||||||
|
return head;
|
||||||
|
}
|
||||||
|
ListNode node = reverseListRecursive(head.getNext());
|
||||||
|
head.getNext().setNext(head);
|
||||||
|
head.setNext(null);
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
package com.baeldung.algorithms.linkedlist;
|
||||||
|
|
||||||
|
public class ListNode {
|
||||||
|
|
||||||
|
private int data;
|
||||||
|
private ListNode next;
|
||||||
|
|
||||||
|
ListNode(int data) {
|
||||||
|
this.data = data;
|
||||||
|
this.next = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getData() {
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ListNode getNext() {
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setData(int data) {
|
||||||
|
this.data = data;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setNext(ListNode next) {
|
||||||
|
this.next = next;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,59 @@
|
||||||
|
package com.baeldung.algorithms.linkedlist;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
|
||||||
|
public class LinkedListReversalUnitTest {
|
||||||
|
@Test
|
||||||
|
public void givenLinkedList_whenIterativeReverse_thenOutputCorrectResult() {
|
||||||
|
ListNode head = constructLinkedList();
|
||||||
|
ListNode node = head;
|
||||||
|
for (int i = 1; i <= 5; i++) {
|
||||||
|
assertNotNull(node);
|
||||||
|
assertEquals(i, node.getData());
|
||||||
|
node = node.getNext();
|
||||||
|
}
|
||||||
|
LinkedListReversal reversal = new LinkedListReversal();
|
||||||
|
node = reversal.reverseList(head);
|
||||||
|
for (int i = 5; i >= 1; i--) {
|
||||||
|
assertNotNull(node);
|
||||||
|
assertEquals(i, node.getData());
|
||||||
|
node = node.getNext();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLinkedList_whenRecursiveReverse_thenOutputCorrectResult() {
|
||||||
|
ListNode head = constructLinkedList();
|
||||||
|
ListNode node = head;
|
||||||
|
for (int i = 1; i <= 5; i++) {
|
||||||
|
assertNotNull(node);
|
||||||
|
assertEquals(i, node.getData());
|
||||||
|
node = node.getNext();
|
||||||
|
}
|
||||||
|
LinkedListReversal reversal = new LinkedListReversal();
|
||||||
|
node = reversal.reverseListRecursive(head);
|
||||||
|
for (int i = 5; i >= 1; i--) {
|
||||||
|
assertNotNull(node);
|
||||||
|
assertEquals(i, node.getData());
|
||||||
|
node = node.getNext();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private ListNode constructLinkedList() {
|
||||||
|
ListNode head = null;
|
||||||
|
ListNode tail = null;
|
||||||
|
for (int i = 1; i <= 5; i++) {
|
||||||
|
ListNode node = new ListNode(i);
|
||||||
|
if (head == null) {
|
||||||
|
head = node;
|
||||||
|
} else {
|
||||||
|
tail.setNext(node);
|
||||||
|
}
|
||||||
|
tail = node;
|
||||||
|
}
|
||||||
|
return head;
|
||||||
|
}
|
||||||
|
}
|
|
@ -129,6 +129,11 @@
|
||||||
<artifactId>zookeeper</artifactId>
|
<artifactId>zookeeper</artifactId>
|
||||||
<version>${zookeeper.version}</version>
|
<version>${zookeeper.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
|
<artifactId>jackson-core</artifactId>
|
||||||
|
<version>${jackson.version}</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
<artifactId>jackson-databind</artifactId>
|
<artifactId>jackson-databind</artifactId>
|
||||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,75 @@
|
||||||
|
package com.baeldung.differences.dataframe.dataset.rdd;
|
||||||
|
|
||||||
|
|
||||||
|
public class TouristData {
|
||||||
|
|
||||||
|
private String region;
|
||||||
|
private String country;
|
||||||
|
private String year;
|
||||||
|
private String series;
|
||||||
|
private Double value;
|
||||||
|
private String footnotes;
|
||||||
|
private String source;
|
||||||
|
|
||||||
|
public String getRegion() {
|
||||||
|
return region;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRegion(String region) {
|
||||||
|
this.region = region;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCountry() {
|
||||||
|
return country;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCountry(String country) {
|
||||||
|
this.country = country;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getYear() {
|
||||||
|
return year;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setYear(String year) {
|
||||||
|
this.year = year;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getSeries() {
|
||||||
|
return series;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSeries(String series) {
|
||||||
|
this.series = series;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Double getValue() {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setValue(Double value) {
|
||||||
|
this.value = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFootnotes() {
|
||||||
|
return footnotes;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setFootnotes(String footnotes) {
|
||||||
|
this.footnotes = footnotes;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getSource() {
|
||||||
|
return source;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSource(String source) {
|
||||||
|
this.source = source;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "TouristData [region=" + region + ", country=" + country + ", year=" + year + ", series=" + series + ", value=" + value + ", footnotes=" + footnotes + ", source=" + source + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,67 @@
|
||||||
|
package com.baeldung.differences.rdd;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.apache.spark.SparkConf;
|
||||||
|
import org.apache.spark.api.java.JavaPairRDD;
|
||||||
|
import org.apache.spark.api.java.JavaRDD;
|
||||||
|
import org.apache.spark.api.java.JavaSparkContext;
|
||||||
|
import org.junit.AfterClass;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import scala.Tuple2;
|
||||||
|
|
||||||
|
public class ActionsUnitTest {
|
||||||
|
private static JavaRDD<String> tourists;
|
||||||
|
private static JavaSparkContext sc;
|
||||||
|
public static final String COMMA_DELIMITER = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)";
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void init() {
|
||||||
|
SparkConf conf = new SparkConf().setAppName("reduce")
|
||||||
|
.setMaster("local[*]");
|
||||||
|
sc = new JavaSparkContext(conf);
|
||||||
|
tourists = sc.textFile("data/Tourist.csv").filter(line -> !line.startsWith("Region"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterClass
|
||||||
|
public static void cleanup() {
|
||||||
|
sc.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenDistinctCount_thenReturnDistinctNumRecords() {
|
||||||
|
JavaRDD<String> countries = tourists.map(line -> {
|
||||||
|
String[] columns = line.split(COMMA_DELIMITER);
|
||||||
|
return columns[1];
|
||||||
|
})
|
||||||
|
.distinct();
|
||||||
|
Long numberOfCountries = countries.count();
|
||||||
|
System.out.println("Count: " + numberOfCountries);
|
||||||
|
|
||||||
|
assertEquals(Long.valueOf(220), numberOfCountries);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenReduceByKeySum_thenTotalValuePerKey() {
|
||||||
|
JavaRDD<String> touristsExpenditure = tourists.filter(line -> line.split(COMMA_DELIMITER)[3].contains("expenditure"));
|
||||||
|
|
||||||
|
JavaPairRDD<String, Double> expenditurePairRdd = touristsExpenditure.mapToPair(line -> {
|
||||||
|
String[] columns = line.split(COMMA_DELIMITER);
|
||||||
|
return new Tuple2<>(columns[1], Double.valueOf(columns[6]));
|
||||||
|
});
|
||||||
|
List<Tuple2<String, Double>> totalByCountry = expenditurePairRdd.reduceByKey((x, y) -> x + y)
|
||||||
|
.collect();
|
||||||
|
System.out.println("Total per Country: " + totalByCountry);
|
||||||
|
|
||||||
|
for(Tuple2<String, Double> tuple : totalByCountry) {
|
||||||
|
if (tuple._1.equals("Mexico")) {
|
||||||
|
assertEquals(Double.valueOf(99164), tuple._2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,74 @@
|
||||||
|
package com.baeldung.differences.rdd;
|
||||||
|
|
||||||
|
import static org.apache.spark.sql.functions.col;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.apache.spark.sql.DataFrameReader;
|
||||||
|
import org.apache.spark.sql.Dataset;
|
||||||
|
import org.apache.spark.sql.Row;
|
||||||
|
import org.apache.spark.sql.SparkSession;
|
||||||
|
import org.junit.AfterClass;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class DataFrameUnitTest {
|
||||||
|
private static SparkSession session;
|
||||||
|
private static Dataset<Row> data;
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void init() {
|
||||||
|
session = SparkSession.builder()
|
||||||
|
.appName("TouristDataFrameExample")
|
||||||
|
.master("local[*]")
|
||||||
|
.getOrCreate();
|
||||||
|
DataFrameReader dataFrameReader = session.read();
|
||||||
|
data = dataFrameReader.option("header", "true")
|
||||||
|
.csv("data/Tourist.csv");
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterClass
|
||||||
|
public static void cleanup() {
|
||||||
|
session.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSelectSpecificColumns_thenColumnsFiltered() {
|
||||||
|
Dataset<Row> selectedData = data.select(col("country"), col("year"), col("value"));
|
||||||
|
selectedData.show();
|
||||||
|
|
||||||
|
List<String> resultList = Arrays.asList(selectedData.columns());
|
||||||
|
assertTrue(resultList.contains("country"));
|
||||||
|
assertTrue(resultList.contains("year"));
|
||||||
|
assertTrue(resultList.contains("value"));
|
||||||
|
assertFalse(resultList.contains("Series"));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFilteringByCountry_thenCountryRecordsSelected() {
|
||||||
|
Dataset<Row> filteredData = data.filter(col("country").equalTo("Mexico"));
|
||||||
|
filteredData.show();
|
||||||
|
|
||||||
|
filteredData.foreach(record -> {
|
||||||
|
assertEquals("Mexico", record.get(1));
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGroupCountByCountry_thenContryTotalRecords() {
|
||||||
|
Dataset<Row> recordsPerCountry = data.groupBy(col("country"))
|
||||||
|
.count();
|
||||||
|
recordsPerCountry.show();
|
||||||
|
|
||||||
|
Dataset<Row> filteredData = recordsPerCountry.filter(col("country").equalTo("Sweden"));
|
||||||
|
assertEquals(new Long(12), filteredData.first()
|
||||||
|
.get(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,83 @@
|
||||||
|
package com.baeldung.differences.rdd;
|
||||||
|
|
||||||
|
import static org.apache.spark.sql.functions.col;
|
||||||
|
import static org.apache.spark.sql.functions.sum;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.apache.spark.api.java.function.FilterFunction;
|
||||||
|
import org.apache.spark.sql.DataFrameReader;
|
||||||
|
import org.apache.spark.sql.Dataset;
|
||||||
|
import org.apache.spark.sql.Encoders;
|
||||||
|
import org.apache.spark.sql.Row;
|
||||||
|
import org.apache.spark.sql.SparkSession;
|
||||||
|
import org.junit.AfterClass;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.differences.dataframe.dataset.rdd.TouristData;
|
||||||
|
|
||||||
|
public class DatasetUnitTest {
|
||||||
|
private static SparkSession session;
|
||||||
|
private static Dataset<TouristData> typedDataset;
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void init() {
|
||||||
|
session = SparkSession.builder()
|
||||||
|
.appName("TouristDatasetExample")
|
||||||
|
.master("local[*]")
|
||||||
|
.getOrCreate();
|
||||||
|
DataFrameReader dataFrameReader = session.read();
|
||||||
|
Dataset<Row> data = dataFrameReader.option("header", "true")
|
||||||
|
.csv("data/Tourist.csv");
|
||||||
|
Dataset<Row> responseWithSelectedColumns = data.select(col("region"),
|
||||||
|
col("country"), col("year"), col("series"), col("value").cast("double"),
|
||||||
|
col("footnotes"), col("source"));
|
||||||
|
typedDataset = responseWithSelectedColumns.as(Encoders.bean(TouristData.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterClass
|
||||||
|
public static void cleanup() {
|
||||||
|
session.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFilteringByCountry_thenCountryRecordsSelected() {
|
||||||
|
Dataset<TouristData> selectedData = typedDataset
|
||||||
|
.filter((FilterFunction<TouristData>) record -> record.getCountry()
|
||||||
|
.equals("Norway"));
|
||||||
|
selectedData.show();
|
||||||
|
|
||||||
|
selectedData.foreach(record -> {
|
||||||
|
assertEquals("Norway", record.getCountry());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGroupCountByCountry_thenContryTotalRecords() {
|
||||||
|
Dataset<Row> countriesCount = typedDataset.groupBy(typedDataset.col("country"))
|
||||||
|
.count();
|
||||||
|
countriesCount.show();
|
||||||
|
|
||||||
|
assertEquals(Long.valueOf(220), Long.valueOf(countriesCount.count()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFilteredByPropertyRange_thenRetreiveValidRecords() {
|
||||||
|
// Filter records with existing data for years between 2010 and 2017
|
||||||
|
typedDataset.filter((FilterFunction<TouristData>) record -> record.getYear() != null
|
||||||
|
&& (Long.valueOf(record.getYear()) > 2010 && Long.valueOf(record.getYear()) < 2017))
|
||||||
|
.show();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSumValue_thenRetreiveTotalValue() {
|
||||||
|
// Total tourist expenditure by country
|
||||||
|
typedDataset.filter((FilterFunction<TouristData>) record -> record.getValue() != null
|
||||||
|
&& record.getSeries()
|
||||||
|
.contains("expenditure"))
|
||||||
|
.groupBy("country")
|
||||||
|
.agg(sum("value"))
|
||||||
|
.show();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,63 @@
|
||||||
|
package com.baeldung.differences.rdd;
|
||||||
|
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.apache.spark.SparkConf;
|
||||||
|
import org.apache.spark.api.java.JavaRDD;
|
||||||
|
import org.apache.spark.api.java.JavaSparkContext;
|
||||||
|
import org.junit.AfterClass;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class TransformationsUnitTest {
|
||||||
|
|
||||||
|
public static final String COMMA_DELIMITER = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)";
|
||||||
|
private static JavaSparkContext sc;
|
||||||
|
private static JavaRDD<String> tourists;
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void init() {
|
||||||
|
SparkConf conf = new SparkConf().setAppName("uppercaseCountries")
|
||||||
|
.setMaster("local[*]");
|
||||||
|
sc = new JavaSparkContext(conf);
|
||||||
|
tourists = sc.textFile("data/Tourist.csv")
|
||||||
|
.filter(line -> !line.startsWith("Region")); //filter header row
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterClass
|
||||||
|
public static void cleanup() {
|
||||||
|
sc.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMapUpperCase_thenCountryNameUppercased() {
|
||||||
|
JavaRDD<String> upperCaseCountries = tourists.map(line -> {
|
||||||
|
String[] columns = line.split(COMMA_DELIMITER);
|
||||||
|
return columns[1].toUpperCase();
|
||||||
|
})
|
||||||
|
.distinct();
|
||||||
|
|
||||||
|
upperCaseCountries.saveAsTextFile("data/output/uppercase.txt");
|
||||||
|
|
||||||
|
upperCaseCountries.foreach(country -> {
|
||||||
|
//replace non alphanumerical characters
|
||||||
|
country = country.replaceAll("[^a-zA-Z]", "");
|
||||||
|
assertTrue(StringUtils.isAllUpperCase(country));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFilterByCountry_thenShowRequestedCountryRecords() {
|
||||||
|
JavaRDD<String> touristsInMexico = tourists.filter(line -> line.split(COMMA_DELIMITER)[1].equals("Mexico"));
|
||||||
|
|
||||||
|
touristsInMexico.saveAsTextFile("data/output/touristInMexico.txt");
|
||||||
|
|
||||||
|
touristsInMexico.foreach(record -> {
|
||||||
|
assertEquals("Mexico", record.split(COMMA_DELIMITER)[1]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -5,3 +5,4 @@ This module contains articles about AWS Lambda
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Using AWS Lambda with API Gateway](https://www.baeldung.com/aws-lambda-api-gateway)
|
- [Using AWS Lambda with API Gateway](https://www.baeldung.com/aws-lambda-api-gateway)
|
||||||
- [Introduction to AWS Serverless Application Model](https://www.baeldung.com/aws-serverless)
|
- [Introduction to AWS Serverless Application Model](https://www.baeldung.com/aws-serverless)
|
||||||
|
- [How to Implement Hibernate in an AWS Lambda Function in Java](https://www.baeldung.com/java-aws-lambda-hibernate)
|
||||||
|
|
|
@ -0,0 +1,100 @@
|
||||||
|
<?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>aws-lambda-examples</artifactId>
|
||||||
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
|
<name>aws-lambda-examples</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
<relativePath>../../</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.amazonaws</groupId>
|
||||||
|
<artifactId>aws-java-sdk-dynamodb</artifactId>
|
||||||
|
<version>${aws-java-sdk.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.amazonaws</groupId>
|
||||||
|
<artifactId>aws-java-sdk-core</artifactId>
|
||||||
|
<version>${aws-java-sdk.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.amazonaws</groupId>
|
||||||
|
<artifactId>aws-lambda-java-core</artifactId>
|
||||||
|
<version>${aws-lambda-java-core.version}</version>
|
||||||
|
<exclusions>
|
||||||
|
<exclusion>
|
||||||
|
<artifactId>commons-logging</artifactId>
|
||||||
|
<groupId>commons-logging</groupId>
|
||||||
|
</exclusion>
|
||||||
|
</exclusions>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.amazonaws</groupId>
|
||||||
|
<artifactId>aws-lambda-java-events</artifactId>
|
||||||
|
<version>${aws-lambda-java-events.version}</version>
|
||||||
|
<exclusions>
|
||||||
|
<exclusion>
|
||||||
|
<artifactId>commons-logging</artifactId>
|
||||||
|
<groupId>commons-logging</groupId>
|
||||||
|
</exclusion>
|
||||||
|
</exclusions>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.code.gson</groupId>
|
||||||
|
<artifactId>gson</artifactId>
|
||||||
|
<version>${gson.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-io</groupId>
|
||||||
|
<artifactId>commons-io</artifactId>
|
||||||
|
<version>${commons-io.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.googlecode.json-simple</groupId>
|
||||||
|
<artifactId>json-simple</artifactId>
|
||||||
|
<version>${json-simple.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-shade-plugin</artifactId>
|
||||||
|
<version>${maven-shade-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<createDependencyReducedPom>false</createDependencyReducedPom>
|
||||||
|
</configuration>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>shade</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<json-simple.version>1.1.1</json-simple.version>
|
||||||
|
<commons-io.version>2.5</commons-io.version>
|
||||||
|
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
|
||||||
|
<aws-lambda-java-core.version>1.2.0</aws-lambda-java-core.version>
|
||||||
|
<gson.version>2.8.2</gson.version>
|
||||||
|
<aws-java-sdk.version>1.11.241</aws-java-sdk.version>
|
||||||
|
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
|
@ -5,95 +5,19 @@
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>aws-lambda</artifactId>
|
<artifactId>aws-lambda</artifactId>
|
||||||
<version>0.1.0-SNAPSHOT</version>
|
|
||||||
<name>aws-lambda</name>
|
<name>aws-lambda</name>
|
||||||
<packaging>jar</packaging>
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-modules</artifactId>
|
<artifactId>parent-modules</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
<relativePath>../</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<modules>
|
||||||
<dependency>
|
<module>lambda</module>
|
||||||
<groupId>com.amazonaws</groupId>
|
<module>shipping-tracker/ShippingFunction</module>
|
||||||
<artifactId>aws-java-sdk-dynamodb</artifactId>
|
</modules>
|
||||||
<version>${aws-java-sdk.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.amazonaws</groupId>
|
|
||||||
<artifactId>aws-java-sdk-core</artifactId>
|
|
||||||
<version>${aws-java-sdk.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.amazonaws</groupId>
|
|
||||||
<artifactId>aws-lambda-java-core</artifactId>
|
|
||||||
<version>${aws-lambda-java-core.version}</version>
|
|
||||||
<exclusions>
|
|
||||||
<exclusion>
|
|
||||||
<artifactId>commons-logging</artifactId>
|
|
||||||
<groupId>commons-logging</groupId>
|
|
||||||
</exclusion>
|
|
||||||
</exclusions>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.amazonaws</groupId>
|
|
||||||
<artifactId>aws-lambda-java-events</artifactId>
|
|
||||||
<version>${aws-lambda-java-events.version}</version>
|
|
||||||
<exclusions>
|
|
||||||
<exclusion>
|
|
||||||
<artifactId>commons-logging</artifactId>
|
|
||||||
<groupId>commons-logging</groupId>
|
|
||||||
</exclusion>
|
|
||||||
</exclusions>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.google.code.gson</groupId>
|
|
||||||
<artifactId>gson</artifactId>
|
|
||||||
<version>${gson.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>commons-io</groupId>
|
|
||||||
<artifactId>commons-io</artifactId>
|
|
||||||
<version>${commons-io.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.googlecode.json-simple</groupId>
|
|
||||||
<artifactId>json-simple</artifactId>
|
|
||||||
<version>${json-simple.version}</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<build>
|
</project>
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-shade-plugin</artifactId>
|
|
||||||
<version>${maven-shade-plugin.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<createDependencyReducedPom>false</createDependencyReducedPom>
|
|
||||||
</configuration>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<phase>package</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>shade</goal>
|
|
||||||
</goals>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<json-simple.version>1.1.1</json-simple.version>
|
|
||||||
<commons-io.version>2.5</commons-io.version>
|
|
||||||
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
|
|
||||||
<aws-lambda-java-core.version>1.2.0</aws-lambda-java-core.version>
|
|
||||||
<gson.version>2.8.2</gson.version>
|
|
||||||
<aws-java-sdk.version>1.11.241</aws-java-sdk.version>
|
|
||||||
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
|
||||||
|
|
|
@ -0,0 +1 @@
|
||||||
|
.aws-sam/
|
|
@ -0,0 +1,73 @@
|
||||||
|
<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/maven-v4_0_0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>ShippingFunction</artifactId>
|
||||||
|
<version>1.0</version>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
<name>Shipping Tracker Lambda Function</name>
|
||||||
|
<properties>
|
||||||
|
<maven.compiler.source>1.8</maven.compiler.source>
|
||||||
|
<maven.compiler.target>1.8</maven.compiler.target>
|
||||||
|
<hibernate.version>5.4.21.Final</hibernate.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.amazonaws</groupId>
|
||||||
|
<artifactId>aws-lambda-java-core</artifactId>
|
||||||
|
<version>1.2.0</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.amazonaws</groupId>
|
||||||
|
<artifactId>aws-lambda-java-events</artifactId>
|
||||||
|
<version>3.1.0</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
|
<artifactId>jackson-databind</artifactId>
|
||||||
|
<version>2.11.2</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>4.12</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hibernate</groupId>
|
||||||
|
<artifactId>hibernate-core</artifactId>
|
||||||
|
<version>${hibernate.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hibernate</groupId>
|
||||||
|
<artifactId>hibernate-hikaricp</artifactId>
|
||||||
|
<version>${hibernate.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.postgresql</groupId>
|
||||||
|
<artifactId>postgresql</artifactId>
|
||||||
|
<version>42.2.16</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-shade-plugin</artifactId>
|
||||||
|
<version>3.1.1</version>
|
||||||
|
<configuration>
|
||||||
|
</configuration>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>shade</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
|
@ -0,0 +1,108 @@
|
||||||
|
package com.baeldung.lambda.shipping;
|
||||||
|
|
||||||
|
import com.amazonaws.services.lambda.runtime.Context;
|
||||||
|
import com.amazonaws.services.lambda.runtime.RequestHandler;
|
||||||
|
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
|
||||||
|
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
|
||||||
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import org.hibernate.SessionFactory;
|
||||||
|
import org.hibernate.boot.MetadataSources;
|
||||||
|
import org.hibernate.boot.registry.StandardServiceRegistry;
|
||||||
|
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.hibernate.cfg.AvailableSettings.*;
|
||||||
|
import static org.hibernate.cfg.AvailableSettings.PASS;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handler for requests to Lambda function.
|
||||||
|
*/
|
||||||
|
public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
|
||||||
|
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||||
|
|
||||||
|
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
|
||||||
|
try (SessionFactory sessionFactory = createSessionFactory()) {
|
||||||
|
ShippingService service = new ShippingService(sessionFactory, new ShippingDao());
|
||||||
|
return routeRequest(input, service);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private APIGatewayProxyResponseEvent routeRequest(APIGatewayProxyRequestEvent input, ShippingService service) {
|
||||||
|
Map<String, String> headers = new HashMap<>();
|
||||||
|
headers.put("Content-Type", "application/json");
|
||||||
|
headers.put("X-Custom-Header", "application/json");
|
||||||
|
|
||||||
|
Object result = "OK";
|
||||||
|
|
||||||
|
switch (input.getResource()) {
|
||||||
|
case "/consignment":
|
||||||
|
result = service.createConsignment(
|
||||||
|
fromJson(input.getBody(), Consignment.class));
|
||||||
|
break;
|
||||||
|
case "/consignment/{id}":
|
||||||
|
result = service.view(input.getPathParameters().get("id"));
|
||||||
|
break;
|
||||||
|
case "/consignment/{id}/item":
|
||||||
|
service.addItem(input.getPathParameters().get("id"),
|
||||||
|
fromJson(input.getBody(), Item.class));
|
||||||
|
break;
|
||||||
|
case "/consignment/{id}/checkin":
|
||||||
|
service.checkIn(input.getPathParameters().get("id"),
|
||||||
|
fromJson(input.getBody(), Checkin.class));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new APIGatewayProxyResponseEvent()
|
||||||
|
.withHeaders(headers)
|
||||||
|
.withStatusCode(200)
|
||||||
|
.withBody(toJson(result));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static <T> String toJson(T object) {
|
||||||
|
try {
|
||||||
|
return OBJECT_MAPPER.writeValueAsString(object);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static <T> T fromJson(String json, Class<T> type) {
|
||||||
|
try {
|
||||||
|
return OBJECT_MAPPER.readValue(json, type);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static SessionFactory createSessionFactory() {
|
||||||
|
Map<String, String> settings = new HashMap<>();
|
||||||
|
settings.put(URL, System.getenv("DB_URL"));
|
||||||
|
settings.put(DIALECT, "org.hibernate.dialect.PostgreSQLDialect");
|
||||||
|
settings.put(DEFAULT_SCHEMA, "shipping");
|
||||||
|
settings.put(DRIVER, "org.postgresql.Driver");
|
||||||
|
settings.put(USER, System.getenv("DB_USER"));
|
||||||
|
settings.put(PASS, System.getenv("DB_PASSWORD"));
|
||||||
|
settings.put("hibernate.hikari.connectionTimeout", "20000");
|
||||||
|
settings.put("hibernate.hikari.minimumIdle", "1");
|
||||||
|
settings.put("hibernate.hikari.maximumPoolSize", "2");
|
||||||
|
settings.put("hibernate.hikari.idleTimeout", "30000");
|
||||||
|
|
||||||
|
// commented out as we only need them on first use
|
||||||
|
// settings.put(HBM2DDL_AUTO, "create-only");
|
||||||
|
// settings.put(HBM2DDL_DATABASE_ACTION, "create");
|
||||||
|
|
||||||
|
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
|
||||||
|
.applySettings(settings)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
return new MetadataSources(registry)
|
||||||
|
.addAnnotatedClass(Consignment.class)
|
||||||
|
.addAnnotatedClass(Item.class)
|
||||||
|
.addAnnotatedClass(Checkin.class)
|
||||||
|
.buildMetadata()
|
||||||
|
.buildSessionFactory();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
package com.baeldung.lambda.shipping;
|
||||||
|
|
||||||
|
import javax.persistence.Column;
|
||||||
|
import javax.persistence.Embeddable;
|
||||||
|
|
||||||
|
@Embeddable
|
||||||
|
public class Checkin {
|
||||||
|
private String timeStamp;
|
||||||
|
private String location;
|
||||||
|
|
||||||
|
@Column(name = "timestamp")
|
||||||
|
public String getTimeStamp() {
|
||||||
|
return timeStamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTimeStamp(String timeStamp) {
|
||||||
|
this.timeStamp = timeStamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Column(name = "location")
|
||||||
|
public String getLocation() {
|
||||||
|
return location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLocation(String location) {
|
||||||
|
this.location = location;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,77 @@
|
||||||
|
package com.baeldung.lambda.shipping;
|
||||||
|
|
||||||
|
import javax.persistence.*;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static javax.persistence.FetchType.EAGER;
|
||||||
|
|
||||||
|
@Entity(name = "consignment")
|
||||||
|
@Table(name = "consignment")
|
||||||
|
public class Consignment {
|
||||||
|
private String id;
|
||||||
|
private String source;
|
||||||
|
private String destination;
|
||||||
|
private boolean isDelivered;
|
||||||
|
private List<Item> items = new ArrayList<>();
|
||||||
|
private List<Checkin> checkins = new ArrayList<>();
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@Column(name = "consignment_id")
|
||||||
|
public String getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(String id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Column(name = "source")
|
||||||
|
public String getSource() {
|
||||||
|
return source;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSource(String source) {
|
||||||
|
this.source = source;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Column(name = "destination")
|
||||||
|
public String getDestination() {
|
||||||
|
return destination;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDestination(String destination) {
|
||||||
|
this.destination = destination;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Column(name = "delivered", columnDefinition = "boolean")
|
||||||
|
public boolean isDelivered() {
|
||||||
|
return isDelivered;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDelivered(boolean delivered) {
|
||||||
|
isDelivered = delivered;
|
||||||
|
}
|
||||||
|
|
||||||
|
@ElementCollection(fetch = EAGER)
|
||||||
|
@CollectionTable(name = "consignment_item", joinColumns = @JoinColumn(name = "consignment_id"))
|
||||||
|
@OrderColumn(name = "item_index")
|
||||||
|
public List<Item> getItems() {
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setItems(List<Item> items) {
|
||||||
|
this.items = items;
|
||||||
|
}
|
||||||
|
|
||||||
|
@ElementCollection(fetch = EAGER)
|
||||||
|
@CollectionTable(name = "consignment_checkin", joinColumns = @JoinColumn(name = "consignment_id"))
|
||||||
|
@OrderColumn(name = "checkin_index")
|
||||||
|
public List<Checkin> getCheckins() {
|
||||||
|
return checkins;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCheckins(List<Checkin> checkins) {
|
||||||
|
this.checkins = checkins;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,38 @@
|
||||||
|
package com.baeldung.lambda.shipping;
|
||||||
|
|
||||||
|
import javax.persistence.Column;
|
||||||
|
import javax.persistence.Embeddable;
|
||||||
|
|
||||||
|
@Embeddable
|
||||||
|
public class Item {
|
||||||
|
private String location;
|
||||||
|
private String description;
|
||||||
|
private String timeStamp;
|
||||||
|
|
||||||
|
@Column(name = "location")
|
||||||
|
public String getLocation() {
|
||||||
|
return location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLocation(String location) {
|
||||||
|
this.location = location;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Column(name = "description")
|
||||||
|
public String getDescription() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDescription(String description) {
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Column(name = "timestamp")
|
||||||
|
public String getTimeStamp() {
|
||||||
|
return timeStamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTimeStamp(String timeStamp) {
|
||||||
|
this.timeStamp = timeStamp;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,25 @@
|
||||||
|
package com.baeldung.lambda.shipping;
|
||||||
|
|
||||||
|
import org.hibernate.Session;
|
||||||
|
import org.hibernate.Transaction;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public class ShippingDao {
|
||||||
|
/**
|
||||||
|
* Save a consignment to the database
|
||||||
|
* @param consignment the consignment to save
|
||||||
|
*/
|
||||||
|
public void save(Session session, Consignment consignment) {
|
||||||
|
Transaction transaction = session.beginTransaction();
|
||||||
|
session.save(consignment);
|
||||||
|
transaction.commit();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find a consignment in the database by id
|
||||||
|
*/
|
||||||
|
public Optional<Consignment> find(Session session, String id) {
|
||||||
|
return Optional.ofNullable(session.get(Consignment.class, id));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,62 @@
|
||||||
|
package com.baeldung.lambda.shipping;
|
||||||
|
|
||||||
|
import org.hibernate.Session;
|
||||||
|
import org.hibernate.SessionFactory;
|
||||||
|
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public class ShippingService {
|
||||||
|
private SessionFactory sessionFactory;
|
||||||
|
private ShippingDao shippingDao;
|
||||||
|
|
||||||
|
public ShippingService(SessionFactory sessionFactory, ShippingDao shippingDao) {
|
||||||
|
this.sessionFactory = sessionFactory;
|
||||||
|
this.shippingDao = shippingDao;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String createConsignment(Consignment consignment) {
|
||||||
|
try (Session session = sessionFactory.openSession()) {
|
||||||
|
consignment.setDelivered(false);
|
||||||
|
consignment.setId(UUID.randomUUID().toString());
|
||||||
|
shippingDao.save(session, consignment);
|
||||||
|
return consignment.getId();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addItem(String consignmentId, Item item) {
|
||||||
|
try (Session session = sessionFactory.openSession()) {
|
||||||
|
shippingDao.find(session, consignmentId)
|
||||||
|
.ifPresent(consignment -> addItem(session, consignment, item));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addItem(Session session, Consignment consignment, Item item) {
|
||||||
|
consignment.getItems()
|
||||||
|
.add(item);
|
||||||
|
shippingDao.save(session, consignment);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void checkIn(String consignmentId, Checkin checkin) {
|
||||||
|
try (Session session = sessionFactory.openSession()) {
|
||||||
|
shippingDao.find(session, consignmentId)
|
||||||
|
.ifPresent(consignment -> checkIn(session, consignment, checkin));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void checkIn(Session session, Consignment consignment, Checkin checkin) {
|
||||||
|
consignment.getCheckins().add(checkin);
|
||||||
|
consignment.getCheckins().sort(Comparator.comparing(Checkin::getTimeStamp));
|
||||||
|
if (checkin.getLocation().equals(consignment.getDestination())) {
|
||||||
|
consignment.setDelivered(true);
|
||||||
|
}
|
||||||
|
shippingDao.save(session, consignment);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Consignment view(String consignmentId) {
|
||||||
|
try (Session session = sessionFactory.openSession()) {
|
||||||
|
return shippingDao.find(session, consignmentId)
|
||||||
|
.orElseGet(Consignment::new);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,47 @@
|
||||||
|
AWSTemplateFormatVersion: '2010-09-09'
|
||||||
|
Transform: AWS::Serverless-2016-10-31
|
||||||
|
Description: >
|
||||||
|
shipping-tracker
|
||||||
|
|
||||||
|
Sample SAM Template for shipping-tracker
|
||||||
|
|
||||||
|
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
|
||||||
|
Globals:
|
||||||
|
Function:
|
||||||
|
Timeout: 20
|
||||||
|
|
||||||
|
Resources:
|
||||||
|
ShippingFunction:
|
||||||
|
Type: AWS::Serverless::Function
|
||||||
|
Properties:
|
||||||
|
CodeUri: ShippingFunction
|
||||||
|
Handler: com.baeldung.lambda.shipping.App::handleRequest
|
||||||
|
Runtime: java8
|
||||||
|
MemorySize: 512
|
||||||
|
Environment:
|
||||||
|
Variables:
|
||||||
|
DB_URL: jdbc:postgresql://postgres/postgres
|
||||||
|
DB_USER: postgres
|
||||||
|
DB_PASSWORD: password
|
||||||
|
Events:
|
||||||
|
CreateConsignment:
|
||||||
|
Type: Api
|
||||||
|
Properties:
|
||||||
|
Path: /consignment
|
||||||
|
Method: post
|
||||||
|
AddItem:
|
||||||
|
Type: Api
|
||||||
|
Properties:
|
||||||
|
Path: /consignment/{id}/item
|
||||||
|
Method: post
|
||||||
|
CheckIn:
|
||||||
|
Type: Api
|
||||||
|
Properties:
|
||||||
|
Path: /consignment/{id}/checkin
|
||||||
|
Method: post
|
||||||
|
ViewConsignment:
|
||||||
|
Type: Api
|
||||||
|
Properties:
|
||||||
|
Path: /consignment/{id}
|
||||||
|
Method: get
|
||||||
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
### Relevant Articles:
|
||||||
|
|
||||||
|
- [How to Remove a Prefix From Strings in Groovy](https://www.baeldung.com/groovy-remove-string-prefix)
|
|
@ -0,0 +1,122 @@
|
||||||
|
<?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-groovy-strings</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
<name>core-groovy-strings</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.codehaus.groovy</groupId>
|
||||||
|
<artifactId>groovy</artifactId>
|
||||||
|
<version>${groovy.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.codehaus.groovy</groupId>
|
||||||
|
<artifactId>groovy-all</artifactId>
|
||||||
|
<version>${groovy-all.version}</version>
|
||||||
|
<type>pom</type>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.codehaus.groovy</groupId>
|
||||||
|
<artifactId>groovy-dateutil</artifactId>
|
||||||
|
<version>${groovy.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.codehaus.groovy</groupId>
|
||||||
|
<artifactId>groovy-sql</artifactId>
|
||||||
|
<version>${groovy-sql.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>org.hsqldb</groupId>
|
||||||
|
<artifactId>hsqldb</artifactId>
|
||||||
|
<version>${hsqldb.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.spockframework</groupId>
|
||||||
|
<artifactId>spock-core</artifactId>
|
||||||
|
<version>${spock-core.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.gmavenplus</groupId>
|
||||||
|
<artifactId>gmavenplus-plugin</artifactId>
|
||||||
|
<version>${gmavenplus-plugin.version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>addSources</goal>
|
||||||
|
<goal>addTestSources</goal>
|
||||||
|
<goal>compile</goal>
|
||||||
|
<goal>compileTests</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-failsafe-plugin</artifactId>
|
||||||
|
<version>${maven-failsafe-plugin.version}</version>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.platform</groupId>
|
||||||
|
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||||
|
<version>${junit.platform.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>junit5</id>
|
||||||
|
<goals>
|
||||||
|
<goal>integration-test</goal>
|
||||||
|
<goal>verify</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<includes>
|
||||||
|
<include>**/*Test5.java</include>
|
||||||
|
</includes>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<repositories>
|
||||||
|
<repository>
|
||||||
|
<id>central</id>
|
||||||
|
<url>https://jcenter.bintray.com</url>
|
||||||
|
</repository>
|
||||||
|
</repositories>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<junit.platform.version>1.0.0</junit.platform.version>
|
||||||
|
<groovy.version>2.5.6</groovy.version>
|
||||||
|
<groovy-all.version>2.5.6</groovy-all.version>
|
||||||
|
<groovy-sql.version>2.5.6</groovy-sql.version>
|
||||||
|
<hsqldb.version>2.4.0</hsqldb.version>
|
||||||
|
<spock-core.version>1.1-groovy-2.4</spock-core.version>
|
||||||
|
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,70 @@
|
||||||
|
package com.baeldung.removeprefix
|
||||||
|
|
||||||
|
import org.junit.Assert
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class RemovePrefixTest {
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCasePrefixIsRemoved_thenReturnTrue() {
|
||||||
|
def trimPrefix = {
|
||||||
|
it.startsWith('Groovy-') ? it.minus('Groovy-') : it
|
||||||
|
}
|
||||||
|
|
||||||
|
def actual = trimPrefix("Groovy-Tutorials at Baeldung")
|
||||||
|
def expected = "Tutorials at Baeldung"
|
||||||
|
|
||||||
|
Assert.assertEquals(expected, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPrefixIsRemoved_thenReturnTrue() {
|
||||||
|
|
||||||
|
String prefix = "groovy-"
|
||||||
|
String trimPrefix = "Groovy-Tutorials at Baeldung"
|
||||||
|
def actual;
|
||||||
|
if(trimPrefix.startsWithIgnoreCase(prefix)) {
|
||||||
|
actual = trimPrefix.substring(prefix.length())
|
||||||
|
}
|
||||||
|
|
||||||
|
def expected = "Tutorials at Baeldung"
|
||||||
|
|
||||||
|
Assert.assertEquals(expected, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPrefixIsRemovedUsingRegex_thenReturnTrue() {
|
||||||
|
|
||||||
|
def regex = ~"^([Gg])roovy-"
|
||||||
|
String trimPrefix = "Groovy-Tutorials at Baeldung"
|
||||||
|
String actual = trimPrefix - regex
|
||||||
|
|
||||||
|
def expected = "Tutorials at Baeldung"
|
||||||
|
|
||||||
|
Assert.assertEquals(expected, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPrefixIsRemovedUsingReplaceFirst_thenReturnTrue() {
|
||||||
|
def regex = ~"^groovy"
|
||||||
|
String trimPrefix = "groovyTutorials at Baeldung's groovy page"
|
||||||
|
String actual = trimPrefix.replaceFirst(regex, "")
|
||||||
|
|
||||||
|
def expected = "Tutorials at Baeldung's groovy page"
|
||||||
|
|
||||||
|
Assert.assertEquals(expected, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPrefixIsRemovedUsingReplaceAll_thenReturnTrue() {
|
||||||
|
|
||||||
|
String trimPrefix = "groovyTutorials at Baeldung groovy"
|
||||||
|
String actual = trimPrefix.replaceAll(/^groovy/, "")
|
||||||
|
|
||||||
|
def expected = "Tutorials at Baeldung groovy"
|
||||||
|
|
||||||
|
Assert.assertEquals(expected, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -7,7 +7,7 @@ import junit.framework.TestSuite;
|
||||||
/**
|
/**
|
||||||
* Unit test for simple App.
|
* Unit test for simple App.
|
||||||
*/
|
*/
|
||||||
public class AppTest
|
public class AppUnitTest
|
||||||
extends TestCase
|
extends TestCase
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
|
@ -15,7 +15,7 @@ public class AppTest
|
||||||
*
|
*
|
||||||
* @param testName name of the test case
|
* @param testName name of the test case
|
||||||
*/
|
*/
|
||||||
public AppTest( String testName )
|
public AppUnitTest(String testName )
|
||||||
{
|
{
|
||||||
super( testName );
|
super( testName );
|
||||||
}
|
}
|
||||||
|
@ -25,7 +25,7 @@ public class AppTest
|
||||||
*/
|
*/
|
||||||
public static Test suite()
|
public static Test suite()
|
||||||
{
|
{
|
||||||
return new TestSuite( AppTest.class );
|
return new TestSuite( AppUnitTest.class );
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
|
@ -0,0 +1,8 @@
|
||||||
|
## Core Java 11
|
||||||
|
|
||||||
|
This module contains articles about Java 11 core features
|
||||||
|
|
||||||
|
### Relevant articles
|
||||||
|
- [Guide to Java 8 Optional](https://www.baeldung.com/java-optional)
|
||||||
|
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
|
||||||
|
- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors)
|
|
@ -0,0 +1,54 @@
|
||||||
|
<?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-java-11-2</artifactId>
|
||||||
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
|
<name>core-java-11-2</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
<relativePath>../..</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.guava</groupId>
|
||||||
|
<artifactId>guava</artifactId>
|
||||||
|
<version>${guava.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>${maven.compiler.source.version}</source>
|
||||||
|
<target>${maven.compiler.target.version}</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven.compiler.source.version>11</maven.compiler.source.version>
|
||||||
|
<maven.compiler.target.version>11</maven.compiler.target.version>
|
||||||
|
<guava.version>29.0-jre</guava.version>
|
||||||
|
<assertj.version>3.17.2</assertj.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java.reflection;
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
public abstract class Animal implements Eating {
|
public abstract class Animal implements Eating {
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java.reflection;
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
public class Bird extends Animal {
|
public class Bird extends Animal {
|
||||||
private boolean walks;
|
private boolean walks;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java.reflection;
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
import java.lang.annotation.Annotation;
|
import java.lang.annotation.Annotation;
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java.reflection;
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
public interface Eating {
|
public interface Eating {
|
||||||
String eats();
|
String eats();
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java.reflection;
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
public class Goat extends Animal implements Locomotion {
|
public class Goat extends Animal implements Locomotion {
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java.reflection;
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
import java.lang.annotation.Retention;
|
import java.lang.annotation.Retention;
|
||||||
import java.lang.annotation.RetentionPolicy;
|
import java.lang.annotation.RetentionPolicy;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java.reflection;
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
import java.lang.annotation.Annotation;
|
import java.lang.annotation.Annotation;
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java.reflection;
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
@Greeter(greet="Good morning")
|
@Greeter(greet="Good morning")
|
||||||
public class Greetings {
|
public class Greetings {
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java.reflection;
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
public interface Locomotion {
|
public interface Locomotion {
|
||||||
String getLocomotion();
|
String getLocomotion();
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java.reflection;
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
public class Operations {
|
public class Operations {
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java.reflection;
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
public class Person {
|
public class Person {
|
||||||
private String name;
|
private String name;
|
|
@ -1,18 +1,11 @@
|
||||||
package com.baeldung.streams.collectors;
|
package com.baeldung.collectors;
|
||||||
|
|
||||||
import com.google.common.collect.ImmutableList;
|
import com.google.common.collect.ImmutableList;
|
||||||
import com.google.common.collect.ImmutableSet;
|
import com.google.common.collect.ImmutableSet;
|
||||||
import com.google.common.collect.Sets;
|
import com.google.common.collect.Sets;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.*;
|
||||||
import java.util.Comparator;
|
|
||||||
import java.util.DoubleSummaryStatistics;
|
|
||||||
import java.util.LinkedList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.function.BiConsumer;
|
import java.util.function.BiConsumer;
|
||||||
import java.util.function.BinaryOperator;
|
import java.util.function.BinaryOperator;
|
||||||
import java.util.function.Function;
|
import java.util.function.Function;
|
||||||
|
@ -20,19 +13,7 @@ import java.util.function.Supplier;
|
||||||
import java.util.stream.Collector;
|
import java.util.stream.Collector;
|
||||||
|
|
||||||
import static com.google.common.collect.Sets.newHashSet;
|
import static com.google.common.collect.Sets.newHashSet;
|
||||||
import static java.util.stream.Collectors.averagingDouble;
|
import static java.util.stream.Collectors.*;
|
||||||
import static java.util.stream.Collectors.collectingAndThen;
|
|
||||||
import static java.util.stream.Collectors.counting;
|
|
||||||
import static java.util.stream.Collectors.groupingBy;
|
|
||||||
import static java.util.stream.Collectors.joining;
|
|
||||||
import static java.util.stream.Collectors.maxBy;
|
|
||||||
import static java.util.stream.Collectors.partitioningBy;
|
|
||||||
import static java.util.stream.Collectors.summarizingDouble;
|
|
||||||
import static java.util.stream.Collectors.summingDouble;
|
|
||||||
import static java.util.stream.Collectors.toCollection;
|
|
||||||
import static java.util.stream.Collectors.toList;
|
|
||||||
import static java.util.stream.Collectors.toMap;
|
|
||||||
import static java.util.stream.Collectors.toSet;
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
|
@ -48,6 +29,14 @@ public class Java8CollectorsUnitTest {
|
||||||
assertThat(result).containsAll(givenList);
|
assertThat(result).containsAll(givenList);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCollectingToUnmodifiableList_shouldCollectToUnmodifiableList() {
|
||||||
|
final List<String> result = givenList.stream().collect(toUnmodifiableList());
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> result.add("foo"))
|
||||||
|
.isInstanceOf(UnsupportedOperationException.class);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToSet_shouldCollectToSet() throws Exception {
|
public void whenCollectingToSet_shouldCollectToSet() throws Exception {
|
||||||
final Set<String> result = givenList.stream().collect(toSet());
|
final Set<String> result = givenList.stream().collect(toSet());
|
||||||
|
@ -55,6 +44,14 @@ public class Java8CollectorsUnitTest {
|
||||||
assertThat(result).containsAll(givenList);
|
assertThat(result).containsAll(givenList);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCollectingToUnmodifiableSet_shouldCollectToUnmodifiableSet() {
|
||||||
|
final Set<String> result = givenList.stream().collect(toUnmodifiableSet());
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> result.add("foo"))
|
||||||
|
.isInstanceOf(UnsupportedOperationException.class);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenContainsDuplicateElements_whenCollectingToSet_shouldAddDuplicateElementsOnlyOnce() throws Exception {
|
public void givenContainsDuplicateElements_whenCollectingToSet_shouldAddDuplicateElementsOnlyOnce() throws Exception {
|
||||||
final Set<String> result = listWithDuplicates.stream().collect(toSet());
|
final Set<String> result = listWithDuplicates.stream().collect(toSet());
|
||||||
|
@ -84,6 +81,15 @@ public class Java8CollectorsUnitTest {
|
||||||
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCollectingToUnmodifiableMap_shouldCollectToUnmodifiableMap() {
|
||||||
|
final Map<String, Integer> result = givenList.stream()
|
||||||
|
.collect(toUnmodifiableMap(Function.identity(), String::length));
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> result.put("foo", 3))
|
||||||
|
.isInstanceOf(UnsupportedOperationException.class);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToMapwWithDuplicates_shouldCollectToMapMergingTheIdenticalItems() throws Exception {
|
public void whenCollectingToMapwWithDuplicates_shouldCollectToMapMergingTheIdenticalItems() throws Exception {
|
||||||
final Map<String, Integer> result = listWithDuplicates.stream().collect(
|
final Map<String, Integer> result = listWithDuplicates.stream().collect(
|
|
@ -7,7 +7,9 @@ import java.util.Optional;
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class OptionalChainingUnitTest {
|
public class OptionalChainingUnitTest {
|
||||||
|
|
|
@ -9,7 +9,9 @@ import java.util.List;
|
||||||
import java.util.NoSuchElementException;
|
import java.util.NoSuchElementException;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class OptionalUnitTest {
|
public class OptionalUnitTest {
|
||||||
|
|
||||||
|
@ -262,6 +264,12 @@ public class OptionalUnitTest {
|
||||||
.orElseThrow(IllegalArgumentException::new);
|
.orElseThrow(IllegalArgumentException::new);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test(expected = NoSuchElementException.class)
|
||||||
|
public void whenNoArgOrElseThrowWorks_thenCorrect() {
|
||||||
|
String nullName = null;
|
||||||
|
String name = Optional.ofNullable(nullName).orElseThrow();
|
||||||
|
}
|
||||||
|
|
||||||
public String getMyDefault() {
|
public String getMyDefault() {
|
||||||
LOG.debug("Getting default value...");
|
LOG.debug("Getting default value...");
|
||||||
return "Default Value";
|
return "Default Value";
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java.reflection;
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
import static org.hamcrest.CoreMatchers.equalTo;
|
import static org.hamcrest.CoreMatchers.equalTo;
|
||||||
import static org.junit.Assert.assertFalse;
|
import static org.junit.Assert.assertFalse;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java.reflection;
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertFalse;
|
import static org.junit.Assert.assertFalse;
|
||||||
|
@ -32,23 +32,23 @@ public class ReflectionUnitTest {
|
||||||
final Class<?> clazz = goat.getClass();
|
final Class<?> clazz = goat.getClass();
|
||||||
|
|
||||||
assertEquals("Goat", clazz.getSimpleName());
|
assertEquals("Goat", clazz.getSimpleName());
|
||||||
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
|
assertEquals("com.baeldung.reflection.Goat", clazz.getName());
|
||||||
assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName());
|
assertEquals("com.baeldung.reflection.Goat", clazz.getCanonicalName());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClassName_whenCreatesObject_thenCorrect() throws ClassNotFoundException {
|
public void givenClassName_whenCreatesObject_thenCorrect() throws ClassNotFoundException {
|
||||||
final Class<?> clazz = Class.forName("com.baeldung.java.reflection.Goat");
|
final Class<?> clazz = Class.forName("com.baeldung.reflection.Goat");
|
||||||
|
|
||||||
assertEquals("Goat", clazz.getSimpleName());
|
assertEquals("Goat", clazz.getSimpleName());
|
||||||
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
|
assertEquals("com.baeldung.reflection.Goat", clazz.getName());
|
||||||
assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName());
|
assertEquals("com.baeldung.reflection.Goat", clazz.getCanonicalName());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenRecognisesModifiers_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenRecognisesModifiers_thenCorrect() throws ClassNotFoundException {
|
||||||
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
final Class<?> goatClass = Class.forName("com.baeldung.reflection.Goat");
|
||||||
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
final Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
|
||||||
final int goatMods = goatClass.getModifiers();
|
final int goatMods = goatClass.getModifiers();
|
||||||
final int animalMods = animalClass.getModifiers();
|
final int animalMods = animalClass.getModifiers();
|
||||||
|
|
||||||
|
@ -63,7 +63,7 @@ public class ReflectionUnitTest {
|
||||||
final Class<?> goatClass = goat.getClass();
|
final Class<?> goatClass = goat.getClass();
|
||||||
final Package pkg = goatClass.getPackage();
|
final Package pkg = goatClass.getPackage();
|
||||||
|
|
||||||
assertEquals("com.baeldung.java.reflection", pkg.getName());
|
assertEquals("com.baeldung.reflection", pkg.getName());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -81,8 +81,8 @@ public class ReflectionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsImplementedInterfaces_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenGetsImplementedInterfaces_thenCorrect() throws ClassNotFoundException {
|
||||||
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
final Class<?> goatClass = Class.forName("com.baeldung.reflection.Goat");
|
||||||
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
final Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
|
||||||
final Class<?>[] goatInterfaces = goatClass.getInterfaces();
|
final Class<?>[] goatInterfaces = goatClass.getInterfaces();
|
||||||
final Class<?>[] animalInterfaces = animalClass.getInterfaces();
|
final Class<?>[] animalInterfaces = animalClass.getInterfaces();
|
||||||
|
|
||||||
|
@ -94,16 +94,16 @@ public class ReflectionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsConstructor_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenGetsConstructor_thenCorrect() throws ClassNotFoundException {
|
||||||
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
final Class<?> goatClass = Class.forName("com.baeldung.reflection.Goat");
|
||||||
final Constructor<?>[] constructors = goatClass.getConstructors();
|
final Constructor<?>[] constructors = goatClass.getConstructors();
|
||||||
|
|
||||||
assertEquals(1, constructors.length);
|
assertEquals(1, constructors.length);
|
||||||
assertEquals("com.baeldung.java.reflection.Goat", constructors[0].getName());
|
assertEquals("com.baeldung.reflection.Goat", constructors[0].getName());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsFields_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenGetsFields_thenCorrect() throws ClassNotFoundException {
|
||||||
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
final Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
|
||||||
final Field[] fields = animalClass.getDeclaredFields();
|
final Field[] fields = animalClass.getDeclaredFields();
|
||||||
|
|
||||||
final List<String> actualFields = getFieldNames(fields);
|
final List<String> actualFields = getFieldNames(fields);
|
||||||
|
@ -114,7 +114,7 @@ public class ReflectionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsMethods_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenGetsMethods_thenCorrect() throws ClassNotFoundException {
|
||||||
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
final Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
|
||||||
final Method[] methods = animalClass.getDeclaredMethods();
|
final Method[] methods = animalClass.getDeclaredMethods();
|
||||||
final List<String> actualMethods = getMethodNames(methods);
|
final List<String> actualMethods = getMethodNames(methods);
|
||||||
|
|
||||||
|
@ -124,7 +124,7 @@ public class ReflectionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsAllConstructors_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenGetsAllConstructors_thenCorrect() throws ClassNotFoundException {
|
||||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||||
final Constructor<?>[] constructors = birdClass.getConstructors();
|
final Constructor<?>[] constructors = birdClass.getConstructors();
|
||||||
|
|
||||||
assertEquals(3, constructors.length);
|
assertEquals(3, constructors.length);
|
||||||
|
@ -132,7 +132,7 @@ public class ReflectionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() throws Exception {
|
public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() throws Exception {
|
||||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||||
birdClass.getConstructor();
|
birdClass.getConstructor();
|
||||||
birdClass.getConstructor(String.class);
|
birdClass.getConstructor(String.class);
|
||||||
birdClass.getConstructor(String.class, boolean.class);
|
birdClass.getConstructor(String.class, boolean.class);
|
||||||
|
@ -140,7 +140,7 @@ public class ReflectionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() throws Exception {
|
public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() throws Exception {
|
||||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||||
|
|
||||||
final Constructor<?> cons1 = birdClass.getConstructor();
|
final Constructor<?> cons1 = birdClass.getConstructor();
|
||||||
final Constructor<?> cons2 = birdClass.getConstructor(String.class);
|
final Constructor<?> cons2 = birdClass.getConstructor(String.class);
|
||||||
|
@ -159,7 +159,7 @@ public class ReflectionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsPublicFields_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenGetsPublicFields_thenCorrect() throws ClassNotFoundException {
|
||||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||||
final Field[] fields = birdClass.getFields();
|
final Field[] fields = birdClass.getFields();
|
||||||
assertEquals(1, fields.length);
|
assertEquals(1, fields.length);
|
||||||
assertEquals("CATEGORY", fields[0].getName());
|
assertEquals("CATEGORY", fields[0].getName());
|
||||||
|
@ -168,7 +168,7 @@ public class ReflectionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsPublicFieldByName_thenCorrect() throws Exception {
|
public void givenClass_whenGetsPublicFieldByName_thenCorrect() throws Exception {
|
||||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||||
final Field field = birdClass.getField("CATEGORY");
|
final Field field = birdClass.getField("CATEGORY");
|
||||||
assertEquals("CATEGORY", field.getName());
|
assertEquals("CATEGORY", field.getName());
|
||||||
|
|
||||||
|
@ -176,7 +176,7 @@ public class ReflectionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsDeclaredFields_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenGetsDeclaredFields_thenCorrect() throws ClassNotFoundException {
|
||||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||||
final Field[] fields = birdClass.getDeclaredFields();
|
final Field[] fields = birdClass.getDeclaredFields();
|
||||||
assertEquals(1, fields.length);
|
assertEquals(1, fields.length);
|
||||||
assertEquals("walks", fields[0].getName());
|
assertEquals("walks", fields[0].getName());
|
||||||
|
@ -184,7 +184,7 @@ public class ReflectionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsFieldsByName_thenCorrect() throws Exception {
|
public void givenClass_whenGetsFieldsByName_thenCorrect() throws Exception {
|
||||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||||
final Field field = birdClass.getDeclaredField("walks");
|
final Field field = birdClass.getDeclaredField("walks");
|
||||||
assertEquals("walks", field.getName());
|
assertEquals("walks", field.getName());
|
||||||
|
|
||||||
|
@ -192,14 +192,14 @@ public class ReflectionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClassField_whenGetsType_thenCorrect() throws Exception {
|
public void givenClassField_whenGetsType_thenCorrect() throws Exception {
|
||||||
final Field field = Class.forName("com.baeldung.java.reflection.Bird").getDeclaredField("walks");
|
final Field field = Class.forName("com.baeldung.reflection.Bird").getDeclaredField("walks");
|
||||||
final Class<?> fieldClass = field.getType();
|
final Class<?> fieldClass = field.getType();
|
||||||
assertEquals("boolean", fieldClass.getSimpleName());
|
assertEquals("boolean", fieldClass.getSimpleName());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClassField_whenSetsAndGetsValue_thenCorrect() throws Exception {
|
public void givenClassField_whenSetsAndGetsValue_thenCorrect() throws Exception {
|
||||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||||
final Bird bird = (Bird) birdClass.getConstructor().newInstance();
|
final Bird bird = (Bird) birdClass.getConstructor().newInstance();
|
||||||
final Field field = birdClass.getDeclaredField("walks");
|
final Field field = birdClass.getDeclaredField("walks");
|
||||||
field.setAccessible(true);
|
field.setAccessible(true);
|
||||||
|
@ -216,7 +216,7 @@ public class ReflectionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() throws Exception {
|
public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() throws Exception {
|
||||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||||
final Field field = birdClass.getField("CATEGORY");
|
final Field field = birdClass.getField("CATEGORY");
|
||||||
field.setAccessible(true);
|
field.setAccessible(true);
|
||||||
|
|
||||||
|
@ -225,7 +225,7 @@ public class ReflectionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsAllPublicMethods_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenGetsAllPublicMethods_thenCorrect() throws ClassNotFoundException {
|
||||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||||
final Method[] methods = birdClass.getMethods();
|
final Method[] methods = birdClass.getMethods();
|
||||||
final List<String> methodNames = getMethodNames(methods);
|
final List<String> methodNames = getMethodNames(methods);
|
||||||
|
|
||||||
|
@ -235,7 +235,7 @@ public class ReflectionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() throws ClassNotFoundException {
|
||||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||||
final List<String> actualMethodNames = getMethodNames(birdClass.getDeclaredMethods());
|
final List<String> actualMethodNames = getMethodNames(birdClass.getDeclaredMethods());
|
||||||
|
|
||||||
final List<String> expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats");
|
final List<String> expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats");
|
||||||
|
@ -248,24 +248,17 @@ public class ReflectionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenMethodName_whenGetsMethod_thenCorrect() throws Exception {
|
public void givenMethodName_whenGetsMethod_thenCorrect() throws Exception {
|
||||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Bird bird = new Bird();
|
||||||
final Method walksMethod = birdClass.getDeclaredMethod("walks");
|
final Method walksMethod = bird.getClass().getDeclaredMethod("walks");
|
||||||
final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
|
final Method setWalksMethod = bird.getClass().getDeclaredMethod("setWalks", boolean.class);
|
||||||
|
|
||||||
assertFalse(walksMethod.isAccessible());
|
|
||||||
assertFalse(setWalksMethod.isAccessible());
|
|
||||||
|
|
||||||
walksMethod.setAccessible(true);
|
|
||||||
setWalksMethod.setAccessible(true);
|
|
||||||
|
|
||||||
assertTrue(walksMethod.isAccessible());
|
|
||||||
assertTrue(setWalksMethod.isAccessible());
|
|
||||||
|
|
||||||
|
assertTrue(walksMethod.canAccess(bird));
|
||||||
|
assertTrue(setWalksMethod.canAccess(bird));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenMethod_whenInvokes_thenCorrect() throws Exception {
|
public void givenMethod_whenInvokes_thenCorrect() throws Exception {
|
||||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||||
final Bird bird = (Bird) birdClass.getConstructor().newInstance();
|
final Bird bird = (Bird) birdClass.getConstructor().newInstance();
|
||||||
final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
|
final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
|
||||||
final Method walksMethod = birdClass.getDeclaredMethod("walks");
|
final Method walksMethod = birdClass.getDeclaredMethod("walks");
|
|
@ -107,7 +107,7 @@
|
||||||
<uberjar.name>benchmarks</uberjar.name>
|
<uberjar.name>benchmarks</uberjar.name>
|
||||||
<jmh.version>1.22</jmh.version>
|
<jmh.version>1.22</jmh.version>
|
||||||
<eclipse.collections.version>10.0.0</eclipse.collections.version>
|
<eclipse.collections.version>10.0.0</eclipse.collections.version>
|
||||||
<shade.plugin.version>10.0.0</shade.plugin.version>
|
<shade.plugin.version>3.2.4</shade.plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -5,7 +5,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class StringAPITest {
|
public class StringAPIUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPositiveArgument_thenReturnIndentedString() {
|
public void whenPositiveArgument_thenReturnIndentedString() {
|
|
@ -7,7 +7,7 @@ import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class PersonTest {
|
public class PersonUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenSameNameAndAddress_whenEquals_thenPersonsEqual() {
|
public void givenSameNameAndAddress_whenEquals_thenPersonsEqual() {
|
|
@ -44,6 +44,16 @@
|
||||||
<artifactId>commons-collections4</artifactId>
|
<artifactId>commons-collections4</artifactId>
|
||||||
<version>${commons-collections4.version}</version>
|
<version>${commons-collections4.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-lang3</artifactId>
|
||||||
|
<version>3.11</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-io</groupId>
|
||||||
|
<artifactId>commons-io</artifactId>
|
||||||
|
<version>2.7</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -77,6 +87,7 @@
|
||||||
<maven.compiler.target>1.9</maven.compiler.target>
|
<maven.compiler.target>1.9</maven.compiler.target>
|
||||||
<guava.version>25.1-jre</guava.version>
|
<guava.version>25.1-jre</guava.version>
|
||||||
<commons-collections4.version>4.1</commons-collections4.version>
|
<commons-collections4.version>4.1</commons-collections4.version>
|
||||||
|
<commons-collections3.version>3.2.2</commons-collections3.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -17,7 +17,7 @@ import org.junit.Test;
|
||||||
/**
|
/**
|
||||||
* Test case for the {@link MethodHandles} API
|
* Test case for the {@link MethodHandles} API
|
||||||
*/
|
*/
|
||||||
public class MethodHandlesTest {
|
public class MethodHandlesUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenConcatMethodHandle_whenInvoked_thenCorrectlyConcatenated() throws Throwable {
|
public void givenConcatMethodHandle_whenInvoked_thenCorrectlyConcatenated() throws Throwable {
|
|
@ -6,3 +6,4 @@ This module contains complete guides about arrays in Java
|
||||||
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
|
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
|
||||||
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
|
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
|
||||||
- [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)
|
- [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)
|
||||||
|
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)
|
||||||
|
|
|
@ -13,3 +13,4 @@
|
||||||
- [Quick Guide to the Java Stack](https://www.baeldung.com/java-stack)
|
- [Quick Guide to the Java Stack](https://www.baeldung.com/java-stack)
|
||||||
- [Convert an Array of Primitives to a List](https://www.baeldung.com/java-primitive-array-to-list)
|
- [Convert an Array of Primitives to a List](https://www.baeldung.com/java-primitive-array-to-list)
|
||||||
- [A Guide to BitSet in Java](https://www.baeldung.com/java-bitset)
|
- [A Guide to BitSet in Java](https://www.baeldung.com/java-bitset)
|
||||||
|
- [Get the First Key and Value From a HashMap](https://www.baeldung.com/java-hashmap-get-first-entry)
|
||||||
|
|
|
@ -0,0 +1,86 @@
|
||||||
|
package com.baeldung.collections.removeallperformance;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.RandomStringUtils;
|
||||||
|
import org.openjdk.jmh.annotations.Benchmark;
|
||||||
|
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||||
|
import org.openjdk.jmh.annotations.Level;
|
||||||
|
import org.openjdk.jmh.annotations.Mode;
|
||||||
|
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||||
|
import org.openjdk.jmh.annotations.Scope;
|
||||||
|
import org.openjdk.jmh.annotations.Setup;
|
||||||
|
import org.openjdk.jmh.annotations.State;
|
||||||
|
import org.openjdk.jmh.annotations.Warmup;
|
||||||
|
import org.openjdk.jmh.runner.Runner;
|
||||||
|
import org.openjdk.jmh.runner.options.Options;
|
||||||
|
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||||
|
|
||||||
|
import com.baeldung.collections.containsperformance.Employee;
|
||||||
|
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||||
|
@Warmup(iterations = 5)
|
||||||
|
public class HashSetBenchmark {
|
||||||
|
|
||||||
|
@State(Scope.Thread)
|
||||||
|
public static class MyState {
|
||||||
|
private Set<Employee> employeeSet1 = new HashSet<>();
|
||||||
|
private List<Employee> employeeList1 = new ArrayList<>();
|
||||||
|
private Set<Employee> employeeSet2 = new HashSet<>();
|
||||||
|
private List<Employee> employeeList2 = new ArrayList<>();
|
||||||
|
|
||||||
|
private long set1Size = 60000;
|
||||||
|
private long list1Size = 50000;
|
||||||
|
private long set2Size = 50000;
|
||||||
|
private long list2Size = 60000;
|
||||||
|
|
||||||
|
@Setup(Level.Trial)
|
||||||
|
public void setUp() {
|
||||||
|
|
||||||
|
for (long i = 0; i < set1Size; i++) {
|
||||||
|
employeeSet1.add(new Employee(i, RandomStringUtils.random(7, true, false)));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (long i = 0; i < list1Size; i++) {
|
||||||
|
employeeList1.add(new Employee(i, RandomStringUtils.random(7, true, false)));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (long i = 0; i < set2Size; i++) {
|
||||||
|
employeeSet2.add(new Employee(i, RandomStringUtils.random(7, true, false)));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (long i = 0; i < list2Size; i++) {
|
||||||
|
employeeList2.add(new Employee(i, RandomStringUtils.random(7, true, false)));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public boolean given_SizeOfHashsetGreaterThanSizeOfCollection_When_RemoveAllFromHashSet_Then_GoodPerformance(MyState state) {
|
||||||
|
return state.employeeSet1.removeAll(state.employeeList1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public boolean given_SizeOfHashsetSmallerThanSizeOfCollection_When_RemoveAllFromHashSet_Then_BadPerformance(MyState state) {
|
||||||
|
return state.employeeSet2.removeAll(state.employeeList2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
Options options = new OptionsBuilder().include(HashSetBenchmark.class.getSimpleName())
|
||||||
|
.threads(1)
|
||||||
|
.forks(1)
|
||||||
|
.shouldFailOnError(true)
|
||||||
|
.shouldDoGC(true)
|
||||||
|
.jvmArgs("-server")
|
||||||
|
.build();
|
||||||
|
new Runner(options).run();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,33 @@
|
||||||
|
package com.baeldung.collections.hashset;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class HashSetUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenRemoveAllFromHashset_thenRemovesAllElementsFromHashsetThatArePresentInCollection() {
|
||||||
|
Set<Integer> set = new HashSet<>();
|
||||||
|
Collection<Integer> collection = new ArrayList<>();
|
||||||
|
set.add(1);
|
||||||
|
set.add(2);
|
||||||
|
set.add(3);
|
||||||
|
set.add(4);
|
||||||
|
collection.add(1);
|
||||||
|
collection.add(3);
|
||||||
|
|
||||||
|
set.removeAll(collection);
|
||||||
|
|
||||||
|
assertEquals(2, set.size());
|
||||||
|
Integer[] actualElements = new Integer[set.size()];
|
||||||
|
Integer[] expectedElements = new Integer[] { 2, 4 };
|
||||||
|
assertArrayEquals(expectedElements, set.toArray(actualElements));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,146 @@
|
||||||
|
package com.baeldung.collections.mapfirstpair;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNotEquals;
|
||||||
|
|
||||||
|
import java.util.AbstractMap;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class MapFirstPairUnitTest {
|
||||||
|
|
||||||
|
private Map.Entry<Integer, String> getFirstPairUsingIterator(Map<Integer, String> map) {
|
||||||
|
if (map == null || map.size() == 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet()
|
||||||
|
.iterator();
|
||||||
|
|
||||||
|
if (iterator.hasNext()) {
|
||||||
|
return iterator.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map.Entry<Integer, String> getFirstPairUsingStream(Map<Integer, String> map) {
|
||||||
|
if (map == null || map.size() == 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
|
||||||
|
|
||||||
|
return entrySet.stream()
|
||||||
|
.findFirst()
|
||||||
|
.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<Integer, String> populateMapValues(Map<Integer, String> map) {
|
||||||
|
if (map != null) {
|
||||||
|
map.put(5, "A");
|
||||||
|
map.put(1, "B");
|
||||||
|
map.put(2, "C");
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingIteratorForHashMap_thenFirstPairWhichWasNotInsertedFirst() {
|
||||||
|
Map<Integer, String> hashMap = new HashMap<>();
|
||||||
|
hashMap = populateMapValues(hashMap);
|
||||||
|
|
||||||
|
Map.Entry<Integer, String> actualValue = getFirstPairUsingIterator(hashMap);
|
||||||
|
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(1, "B");
|
||||||
|
Map.Entry<Integer, String> pairInsertedFirst = new AbstractMap.SimpleEntry<Integer, String>(5, "A");
|
||||||
|
|
||||||
|
assertEquals(expectedValue, actualValue);
|
||||||
|
assertNotEquals(pairInsertedFirst, actualValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingStreamForHashMap_thenFirstPairWhichWasNotInsertedFirst() {
|
||||||
|
Map<Integer, String> hashMap = new HashMap<>();
|
||||||
|
hashMap = populateMapValues(hashMap);
|
||||||
|
Map.Entry<Integer, String> actualValue = getFirstPairUsingStream(hashMap);
|
||||||
|
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(1, "B");
|
||||||
|
Map.Entry<Integer, String> pairInsertedFirst = new AbstractMap.SimpleEntry<Integer, String>(5, "A");
|
||||||
|
|
||||||
|
assertEquals(expectedValue, actualValue);
|
||||||
|
assertNotEquals(pairInsertedFirst, actualValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingIteratorForLinkedHashMap_thenFirstPairWhichWasInsertedFirst() {
|
||||||
|
Map<Integer, String> linkedHashMap = new LinkedHashMap<>();
|
||||||
|
linkedHashMap = populateMapValues(linkedHashMap);
|
||||||
|
Map.Entry<Integer, String> actualValue = getFirstPairUsingIterator(linkedHashMap);
|
||||||
|
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(5, "A");
|
||||||
|
|
||||||
|
assertEquals(expectedValue, actualValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingStreamForLinkedHashMap_thenFirstPairWhichWasInsertedFirst() {
|
||||||
|
Map<Integer, String> linkedHashMap = new LinkedHashMap<>();
|
||||||
|
linkedHashMap = populateMapValues(linkedHashMap);
|
||||||
|
|
||||||
|
Map.Entry<Integer, String> actualValue = getFirstPairUsingStream(linkedHashMap);
|
||||||
|
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(5, "A");
|
||||||
|
|
||||||
|
assertEquals(expectedValue, actualValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenAddedAnElementInHashMap_thenFirstPairChangedUsingIterator() {
|
||||||
|
Map<Integer, String> hashMap = new HashMap<>();
|
||||||
|
hashMap = populateMapValues(hashMap);
|
||||||
|
|
||||||
|
hashMap.put(0, "D");
|
||||||
|
Map.Entry<Integer, String> actualValue = getFirstPairUsingIterator(hashMap);
|
||||||
|
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(0, "D");
|
||||||
|
|
||||||
|
assertEquals(expectedValue, actualValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenAddedAnElementInHashMap_thenFirstPairChangedUsingStream() {
|
||||||
|
Map<Integer, String> hashMap = new HashMap<>();
|
||||||
|
hashMap = populateMapValues(hashMap);
|
||||||
|
|
||||||
|
hashMap.put(0, "D");
|
||||||
|
Map.Entry<Integer, String> actualValue = getFirstPairUsingStream(hashMap);
|
||||||
|
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(0, "D");
|
||||||
|
|
||||||
|
assertEquals(expectedValue, actualValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenAddedAnElementInLinkedHashMap_thenFirstPairRemainUnchangedUsingIterator() {
|
||||||
|
Map<Integer, String> linkedHashMap = new LinkedHashMap<>();
|
||||||
|
linkedHashMap = populateMapValues(linkedHashMap);
|
||||||
|
|
||||||
|
linkedHashMap.put(0, "D");
|
||||||
|
Map.Entry<Integer, String> actualValue = getFirstPairUsingIterator(linkedHashMap);
|
||||||
|
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(5, "A");
|
||||||
|
|
||||||
|
assertEquals(expectedValue, actualValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenAddedAnElementInLinkedHashMap_thenFirstPairRemainUnchangedUsingStream() {
|
||||||
|
Map<Integer, String> linkedHashMap = new LinkedHashMap<>();
|
||||||
|
linkedHashMap = populateMapValues(linkedHashMap);
|
||||||
|
|
||||||
|
linkedHashMap.put(0, "D");
|
||||||
|
Map.Entry<Integer, String> actualValue = getFirstPairUsingStream(linkedHashMap);
|
||||||
|
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(5, "A");
|
||||||
|
|
||||||
|
assertEquals(expectedValue, actualValue);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,6 +1,8 @@
|
||||||
package com.baeldung.date;
|
package com.baeldung.date;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import org.joda.time.Days;
|
||||||
|
import org.joda.time.Minutes;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.text.ParseException;
|
import java.text.ParseException;
|
||||||
import java.text.SimpleDateFormat;
|
import java.text.SimpleDateFormat;
|
||||||
|
@ -16,7 +18,7 @@ import java.util.Locale;
|
||||||
import java.util.TimeZone;
|
import java.util.TimeZone;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
import org.junit.Test;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
public class DateDiffUnitTest {
|
public class DateDiffUnitTest {
|
||||||
|
|
||||||
|
@ -29,18 +31,39 @@ public class DateDiffUnitTest {
|
||||||
long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime());
|
long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime());
|
||||||
long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
|
long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
|
||||||
|
|
||||||
assertEquals(diff, 6);
|
assertEquals(6, diff);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() {
|
public void givenTwoDatesInJava8_whenUsingPeriodGetDays_thenWorks() {
|
||||||
LocalDate now = LocalDate.now();
|
LocalDate aDate = LocalDate.of(2020, 9, 11);
|
||||||
LocalDate sixDaysBehind = now.minusDays(6);
|
LocalDate sixDaysBehind = aDate.minusDays(6);
|
||||||
|
|
||||||
Period period = Period.between(now, sixDaysBehind);
|
Period period = Period.between(aDate, sixDaysBehind);
|
||||||
int diff = Math.abs(period.getDays());
|
int diff = Math.abs(period.getDays());
|
||||||
|
|
||||||
assertEquals(diff, 6);
|
assertEquals(6, diff);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoDatesInJava8_whenUsingPeriodGetDays_thenDoesNotWork() {
|
||||||
|
LocalDate aDate = LocalDate.of(2020, 9, 11);
|
||||||
|
LocalDate sixtyDaysBehind = aDate.minusDays(60);
|
||||||
|
Period period = Period.between(aDate, sixtyDaysBehind);
|
||||||
|
int diff = Math.abs(period.getDays());
|
||||||
|
//not equals
|
||||||
|
assertNotEquals(60, diff);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoDatesInJava8_whenUsingPeriod_thenWeGet0Year1Month29Days() {
|
||||||
|
LocalDate aDate = LocalDate.of(2020, 9, 11);
|
||||||
|
LocalDate sixtyDaysBehind = aDate.minusDays(60);
|
||||||
|
Period period = Period.between(aDate, sixtyDaysBehind);
|
||||||
|
int years = Math.abs(period.getYears());
|
||||||
|
int months = Math.abs(period.getMonths());
|
||||||
|
int days = Math.abs(period.getDays());
|
||||||
|
assertArrayEquals(new int[] { 0, 1, 29 }, new int[] { years, months, days });
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -51,7 +74,7 @@ public class DateDiffUnitTest {
|
||||||
Duration duration = Duration.between(now, sixMinutesBehind);
|
Duration duration = Duration.between(now, sixMinutesBehind);
|
||||||
long diff = Math.abs(duration.toMinutes());
|
long diff = Math.abs(duration.toMinutes());
|
||||||
|
|
||||||
assertEquals(diff, 6);
|
assertEquals(6, diff);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -61,7 +84,7 @@ public class DateDiffUnitTest {
|
||||||
|
|
||||||
long diff = ChronoUnit.SECONDS.between(now, tenSecondsLater);
|
long diff = ChronoUnit.SECONDS.between(now, tenSecondsLater);
|
||||||
|
|
||||||
assertEquals(diff, 10);
|
assertEquals(10, diff);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -69,9 +92,9 @@ public class DateDiffUnitTest {
|
||||||
LocalDateTime ldt = LocalDateTime.now();
|
LocalDateTime ldt = LocalDateTime.now();
|
||||||
ZonedDateTime now = ldt.atZone(ZoneId.of("America/Montreal"));
|
ZonedDateTime now = ldt.atZone(ZoneId.of("America/Montreal"));
|
||||||
ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore"))
|
ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore"))
|
||||||
.minusDays(6);
|
.minusDays(6);
|
||||||
long diff = ChronoUnit.DAYS.between(sixDaysBehind, now);
|
long diff = ChronoUnit.DAYS.between(sixDaysBehind, now);
|
||||||
assertEquals(diff, 6);
|
assertEquals(6, diff);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -81,7 +104,7 @@ public class DateDiffUnitTest {
|
||||||
|
|
||||||
long diff = now.until(tenSecondsLater, ChronoUnit.SECONDS);
|
long diff = now.until(tenSecondsLater, ChronoUnit.SECONDS);
|
||||||
|
|
||||||
assertEquals(diff, 10);
|
assertEquals(10, diff);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -89,10 +112,9 @@ public class DateDiffUnitTest {
|
||||||
org.joda.time.LocalDate now = org.joda.time.LocalDate.now();
|
org.joda.time.LocalDate now = org.joda.time.LocalDate.now();
|
||||||
org.joda.time.LocalDate sixDaysBehind = now.minusDays(6);
|
org.joda.time.LocalDate sixDaysBehind = now.minusDays(6);
|
||||||
|
|
||||||
org.joda.time.Period period = new org.joda.time.Period(now, sixDaysBehind);
|
long diff = Math.abs(Days.daysBetween(now, sixDaysBehind).getDays());
|
||||||
long diff = Math.abs(period.getDays());
|
|
||||||
|
|
||||||
assertEquals(diff, 6);
|
assertEquals(6, diff);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -100,8 +122,9 @@ public class DateDiffUnitTest {
|
||||||
org.joda.time.LocalDateTime now = org.joda.time.LocalDateTime.now();
|
org.joda.time.LocalDateTime now = org.joda.time.LocalDateTime.now();
|
||||||
org.joda.time.LocalDateTime sixMinutesBehind = now.minusMinutes(6);
|
org.joda.time.LocalDateTime sixMinutesBehind = now.minusMinutes(6);
|
||||||
|
|
||||||
org.joda.time.Period period = new org.joda.time.Period(now, sixMinutesBehind);
|
long diff = Math.abs(Minutes.minutesBetween(now, sixMinutesBehind).getMinutes());
|
||||||
long diff = Math.abs(period.getDays());
|
assertEquals(6, diff);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -111,6 +134,6 @@ public class DateDiffUnitTest {
|
||||||
|
|
||||||
long diff = Math.abs(now.numDaysFrom(sixDaysBehind));
|
long diff = Math.abs(now.numDaysFrom(sixDaysBehind));
|
||||||
|
|
||||||
assertEquals(diff, 6);
|
assertEquals(6, diff);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,7 +6,7 @@ import org.junit.jupiter.api.Test;
|
||||||
import java.sql.Timestamp;
|
import java.sql.Timestamp;
|
||||||
import java.time.format.DateTimeFormatter;
|
import java.time.format.DateTimeFormatter;
|
||||||
|
|
||||||
public class TimestampToStringConverterTest {
|
public class TimestampToStringConverterUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDatePattern_whenFormatting_thenResultingStringIsCorrect() {
|
public void givenDatePattern_whenFormatting_thenResultingStringIsCorrect() {
|
|
@ -1,3 +1,5 @@
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
|
|
||||||
- [NoSuchMethodError in Java](https://www.baeldung.com/java-nosuchmethod-error)
|
- [NoSuchMethodError in Java](https://www.baeldung.com/java-nosuchmethod-error)
|
||||||
|
- [IllegalArgumentException or NullPointerException for a Null Parameter?](https://www.baeldung.com/java-illegalargumentexception-or-nullpointerexception)
|
||||||
|
- [IllegalMonitorStateException in Java](https://www.baeldung.com/java-illegalmonitorstateexception)
|
||||||
|
|
|
@ -0,0 +1,14 @@
|
||||||
|
package com.baeldung.exceptions.illegalmonitorstate;
|
||||||
|
|
||||||
|
public class Data {
|
||||||
|
private String message;
|
||||||
|
|
||||||
|
public void send(String message) {
|
||||||
|
this.message = message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String receive() {
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,39 @@
|
||||||
|
package com.baeldung.exceptions.illegalmonitorstate;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class SynchronizedReceiver implements Runnable {
|
||||||
|
private static Logger log = LoggerFactory.getLogger(SynchronizedReceiver.class);
|
||||||
|
private final Data data;
|
||||||
|
private String message;
|
||||||
|
private boolean illegalMonitorStateExceptionOccurred;
|
||||||
|
|
||||||
|
public SynchronizedReceiver(Data data) {
|
||||||
|
this.data = data;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
synchronized (data) {
|
||||||
|
try {
|
||||||
|
data.wait();
|
||||||
|
this.message = data.receive();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
log.error("thread was interrupted", e);
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
} catch (IllegalMonitorStateException e) {
|
||||||
|
log.error("illegal monitor state exception occurred", e);
|
||||||
|
illegalMonitorStateExceptionOccurred = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasIllegalMonitorStateExceptionOccurred() {
|
||||||
|
return illegalMonitorStateExceptionOccurred;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getMessage() {
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,37 @@
|
||||||
|
package com.baeldung.exceptions.illegalmonitorstate;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class SynchronizedSender implements Runnable {
|
||||||
|
private static Logger log = LoggerFactory.getLogger(SynchronizedSender.class);
|
||||||
|
private final Data data;
|
||||||
|
private boolean illegalMonitorStateExceptionOccurred;
|
||||||
|
|
||||||
|
public SynchronizedSender(Data data) {
|
||||||
|
this.data = data;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
synchronized (data) {
|
||||||
|
try {
|
||||||
|
Thread.sleep(1000);
|
||||||
|
|
||||||
|
data.send("test");
|
||||||
|
|
||||||
|
data.notifyAll();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
log.error("thread was interrupted", e);
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
} catch (IllegalMonitorStateException e) {
|
||||||
|
log.error("illegal monitor state exception occurred", e);
|
||||||
|
illegalMonitorStateExceptionOccurred = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasIllegalMonitorStateExceptionOccurred() {
|
||||||
|
return illegalMonitorStateExceptionOccurred;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,37 @@
|
||||||
|
package com.baeldung.exceptions.illegalmonitorstate;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class UnsynchronizedReceiver implements Runnable {
|
||||||
|
private static Logger log = LoggerFactory.getLogger(UnsynchronizedReceiver.class);
|
||||||
|
private final Data data;
|
||||||
|
private String message;
|
||||||
|
private boolean illegalMonitorStateExceptionOccurred;
|
||||||
|
|
||||||
|
public UnsynchronizedReceiver(Data data) {
|
||||||
|
this.data = data;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
try {
|
||||||
|
data.wait();
|
||||||
|
this.message = data.receive();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
log.error("thread was interrupted", e);
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
} catch (IllegalMonitorStateException e) {
|
||||||
|
log.error("illegal monitor state exception occurred", e);
|
||||||
|
illegalMonitorStateExceptionOccurred = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasIllegalMonitorStateExceptionOccurred() {
|
||||||
|
return illegalMonitorStateExceptionOccurred;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getMessage() {
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,35 @@
|
||||||
|
package com.baeldung.exceptions.illegalmonitorstate;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class UnsynchronizedSender implements Runnable {
|
||||||
|
private static Logger log = LoggerFactory.getLogger(UnsynchronizedSender.class);
|
||||||
|
private final Data data;
|
||||||
|
private boolean illegalMonitorStateExceptionOccurred;
|
||||||
|
|
||||||
|
public UnsynchronizedSender(Data data) {
|
||||||
|
this.data = data;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
try {
|
||||||
|
Thread.sleep(1000);
|
||||||
|
|
||||||
|
data.send("test");
|
||||||
|
|
||||||
|
data.notifyAll();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
log.error("thread was interrupted", e);
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
} catch (IllegalMonitorStateException e) {
|
||||||
|
log.error("illegal monitor state exception occurred", e);
|
||||||
|
illegalMonitorStateExceptionOccurred = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasIllegalMonitorStateExceptionOccurred() {
|
||||||
|
return illegalMonitorStateExceptionOccurred;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,70 @@
|
||||||
|
package com.baeldung.exceptions.illegalmonitorstate;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
public class IllegalMonitorStateExceptionUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenSyncSenderAndSyncReceiverAreUsed_thenIllegalMonitorExceptionShouldNotBeThrown() throws InterruptedException {
|
||||||
|
Data data = new Data();
|
||||||
|
|
||||||
|
SynchronizedReceiver receiver = new SynchronizedReceiver(data);
|
||||||
|
Thread receiverThread = new Thread(receiver, "receiver-thread");
|
||||||
|
receiverThread.start();
|
||||||
|
|
||||||
|
SynchronizedSender sender = new SynchronizedSender(data);
|
||||||
|
Thread senderThread = new Thread(sender, "sender-thread");
|
||||||
|
senderThread.start();
|
||||||
|
|
||||||
|
senderThread.join(1000);
|
||||||
|
receiverThread.join(1000);
|
||||||
|
|
||||||
|
assertEquals("test", receiver.getMessage());
|
||||||
|
assertFalse(sender.hasIllegalMonitorStateExceptionOccurred());
|
||||||
|
assertFalse(receiver.hasIllegalMonitorStateExceptionOccurred());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenSyncSenderAndUnSyncReceiverAreUsed_thenIllegalMonitorExceptionShouldNotBeThrown() throws InterruptedException {
|
||||||
|
Data data = new Data();
|
||||||
|
|
||||||
|
UnsynchronizedReceiver receiver = new UnsynchronizedReceiver(data);
|
||||||
|
Thread receiverThread = new Thread(receiver, "receiver-thread");
|
||||||
|
receiverThread.start();
|
||||||
|
|
||||||
|
SynchronizedSender sender = new SynchronizedSender(data);
|
||||||
|
Thread senderThread = new Thread(sender, "sender-thread");
|
||||||
|
senderThread.start();
|
||||||
|
|
||||||
|
|
||||||
|
receiverThread.join(1000);
|
||||||
|
senderThread.join(1000);
|
||||||
|
|
||||||
|
assertNull(receiver.getMessage());
|
||||||
|
assertFalse(sender.hasIllegalMonitorStateExceptionOccurred());
|
||||||
|
assertTrue(receiver.hasIllegalMonitorStateExceptionOccurred());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUnSyncSenderAndSyncReceiverAreUsed_thenIllegalMonitorExceptionShouldBeThrown() throws InterruptedException {
|
||||||
|
Data data = new Data();
|
||||||
|
|
||||||
|
SynchronizedReceiver receiver = new SynchronizedReceiver(data);
|
||||||
|
Thread receiverThread = new Thread(receiver, "receiver-thread");
|
||||||
|
receiverThread.start();
|
||||||
|
|
||||||
|
UnsynchronizedSender sender = new UnsynchronizedSender(data);
|
||||||
|
Thread senderThread = new Thread(sender, "sender-thread");
|
||||||
|
senderThread.start();
|
||||||
|
|
||||||
|
|
||||||
|
receiverThread.join(1000);
|
||||||
|
senderThread.join(1000);
|
||||||
|
|
||||||
|
assertNull(receiver.getMessage());
|
||||||
|
assertFalse(receiver.hasIllegalMonitorStateExceptionOccurred());
|
||||||
|
assertTrue(sender.hasIllegalMonitorStateExceptionOccurred());
|
||||||
|
}
|
||||||
|
}
|
|
@ -9,4 +9,7 @@ This module contains articles about core Java input and output (IO)
|
||||||
- [Check If a File or Directory Exists in Java](https://www.baeldung.com/java-file-directory-exists)
|
- [Check If a File or Directory Exists in Java](https://www.baeldung.com/java-file-directory-exists)
|
||||||
- [Copy a Directory in Java](https://www.baeldung.com/java-copy-directory)
|
- [Copy a Directory in Java](https://www.baeldung.com/java-copy-directory)
|
||||||
- [Java Files Open Options](https://www.baeldung.com/java-file-options)
|
- [Java Files Open Options](https://www.baeldung.com/java-file-options)
|
||||||
|
- [Creating Temporary Directories in Java](https://www.baeldung.com/java-temp-directories)
|
||||||
|
- [Reading a Line at a Given Line Number From a File in Java](https://www.baeldung.com/java-read-line-at-number)
|
||||||
|
- [Find the Last Modified File in a Directory with Java](https://www.baeldung.com/java-last-modified-file)
|
||||||
- [[<-- Prev]](/core-java-modules/core-java-io-2)
|
- [[<-- Prev]](/core-java-modules/core-java-io-2)
|
||||||
|
|
|
@ -0,0 +1,61 @@
|
||||||
|
package com.baeldung.lastmodifiedfile;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileFilter;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import org.apache.commons.io.comparator.LastModifiedFileComparator;
|
||||||
|
import org.apache.commons.io.filefilter.FileFilterUtils;
|
||||||
|
|
||||||
|
public class LastModifiedFileApp {
|
||||||
|
|
||||||
|
public static File findUsingIOApi(String sdir) {
|
||||||
|
File dir = new File(sdir);
|
||||||
|
if (dir.isDirectory()) {
|
||||||
|
Optional<File> opFile = Arrays.stream(dir.listFiles(File::isFile))
|
||||||
|
.max((f1, f2) -> Long.compare(f1.lastModified(), f2.lastModified()));
|
||||||
|
|
||||||
|
if (opFile.isPresent()) {
|
||||||
|
return opFile.get();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Path findUsingNIOApi(String sdir) throws IOException {
|
||||||
|
Path dir = Paths.get(sdir);
|
||||||
|
if (Files.isDirectory(dir)) {
|
||||||
|
Optional<Path> opPath = Files.list(dir)
|
||||||
|
.filter(p -> !Files.isDirectory(p))
|
||||||
|
.sorted((p1, p2) -> Long.valueOf(p2.toFile().lastModified())
|
||||||
|
.compareTo(p1.toFile().lastModified()))
|
||||||
|
.findFirst();
|
||||||
|
|
||||||
|
if (opPath.isPresent()) {
|
||||||
|
return opPath.get();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static File findUsingCommonsIO(String sdir) {
|
||||||
|
File dir = new File(sdir);
|
||||||
|
if (dir.isDirectory()) {
|
||||||
|
File[] dirFiles = dir.listFiles((FileFilter) FileFilterUtils.fileFileFilter());
|
||||||
|
if (dirFiles != null && dirFiles.length > 0) {
|
||||||
|
Arrays.sort(dirFiles, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
|
||||||
|
return dirFiles[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -4,6 +4,7 @@ import org.junit.Test;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
import java.nio.file.DirectoryStream;
|
import java.nio.file.DirectoryStream;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
|
@ -20,8 +21,8 @@ public class DirectoryEmptinessUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPath_whenNotDirectory_thenReturnsFalse() throws IOException {
|
public void givenPath_whenNotDirectory_thenReturnsFalse() throws IOException, URISyntaxException {
|
||||||
Path aFile = Paths.get(getClass().getResource("/notDir.txt").getPath());
|
Path aFile = Paths.get(getClass().getResource("/notDir.txt").toURI());
|
||||||
assertThat(isEmpty(aFile)).isFalse();
|
assertThat(isEmpty(aFile)).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -4,10 +4,7 @@ import org.junit.Test;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.*;
|
||||||
import java.nio.file.LinkOption;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
import java.util.concurrent.ThreadLocalRandom;
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
import static org.junit.Assert.assertFalse;
|
import static org.junit.Assert.assertFalse;
|
||||||
|
@ -47,8 +44,18 @@ public class ExistenceUnitTest {
|
||||||
public void givenSymbolicLink_whenTargetDoesNotExists_thenFollowOrNotBasedOnTheOptions() throws IOException {
|
public void givenSymbolicLink_whenTargetDoesNotExists_thenFollowOrNotBasedOnTheOptions() throws IOException {
|
||||||
Path target = Files.createTempFile("baeldung", "target");
|
Path target = Files.createTempFile("baeldung", "target");
|
||||||
Path symbol = Paths.get("test-link-" + ThreadLocalRandom.current().nextInt());
|
Path symbol = Paths.get("test-link-" + ThreadLocalRandom.current().nextInt());
|
||||||
|
Path symbolicLink = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
symbolicLink = Files.createSymbolicLink(symbol, target);
|
||||||
|
} catch (FileSystemException ex) {
|
||||||
|
System.out.println("Your OS security policy prevents the current user from creating symbolic links.\n" +
|
||||||
|
"Most probably you're running Windows with UAC.\n" +
|
||||||
|
"If this is the case, please see - https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/create-symbolic-links\n" +
|
||||||
|
"You must change your security settings to run this test under Windows.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
Path symbolicLink = Files.createSymbolicLink(symbol, target);
|
|
||||||
assertTrue(Files.exists(symbolicLink));
|
assertTrue(Files.exists(symbolicLink));
|
||||||
assertTrue(Files.isSymbolicLink(symbolicLink));
|
assertTrue(Files.isSymbolicLink(symbolicLink));
|
||||||
assertFalse(Files.isSymbolicLink(target));
|
assertFalse(Files.isSymbolicLink(target));
|
||||||
|
|
|
@ -0,0 +1,78 @@
|
||||||
|
package com.baeldung.lastmodifiedfile;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
|
||||||
|
import org.apache.commons.io.FileUtils;
|
||||||
|
import org.junit.jupiter.api.AfterAll;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class LastModifiedFileAppUnitTest {
|
||||||
|
|
||||||
|
private final static String SOURCEDIRECTORY = "src/test/resources/lastmodfiles";
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
public static void setUpFiles() throws IOException, InterruptedException {
|
||||||
|
File srcDir = new File(SOURCEDIRECTORY);
|
||||||
|
if (!srcDir.exists()) {
|
||||||
|
srcDir.mkdir();
|
||||||
|
}
|
||||||
|
|
||||||
|
FileUtils.cleanDirectory(srcDir);
|
||||||
|
|
||||||
|
File file01 = new File(SOURCEDIRECTORY + "/file01.txt");
|
||||||
|
file01.createNewFile();
|
||||||
|
|
||||||
|
Thread.sleep(2000);
|
||||||
|
|
||||||
|
File file02 = new File(SOURCEDIRECTORY + "/file02.txt");
|
||||||
|
file02.createNewFile();
|
||||||
|
|
||||||
|
Thread.sleep(2000);
|
||||||
|
|
||||||
|
File file03 = new File(SOURCEDIRECTORY + "/file03.txt");
|
||||||
|
file03.createNewFile();
|
||||||
|
|
||||||
|
Thread.sleep(2000);
|
||||||
|
|
||||||
|
Files.write(Paths.get(SOURCEDIRECTORY + "/file02.txt"), "Hello File02".getBytes());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDirectory_whenUsingIoApi_thenFindLastModfile() throws IOException {
|
||||||
|
File lastModFile = LastModifiedFileApp.findUsingIOApi(SOURCEDIRECTORY);
|
||||||
|
|
||||||
|
assertThat(lastModFile).isNotNull();
|
||||||
|
assertThat(lastModFile.getName()).isEqualTo("file02.txt");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDirectory_whenUsingNioApi_thenFindLastModfile() throws IOException {
|
||||||
|
Path lastModPath = LastModifiedFileApp.findUsingNIOApi(SOURCEDIRECTORY);
|
||||||
|
|
||||||
|
assertThat(lastModPath).isNotNull();
|
||||||
|
assertThat(lastModPath.toFile().getName()).isEqualTo("file02.txt");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDirectory_whenUsingApacheCommons_thenFindLastModfile() throws IOException {
|
||||||
|
File lastModFile = LastModifiedFileApp.findUsingCommonsIO(SOURCEDIRECTORY);
|
||||||
|
|
||||||
|
assertThat(lastModFile).isNotNull();
|
||||||
|
assertThat(lastModFile.getName()).isEqualTo("file02.txt");
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterAll
|
||||||
|
public static void cleanUp() throws IOException {
|
||||||
|
File srcDir = new File(SOURCEDIRECTORY);
|
||||||
|
FileUtils.deleteDirectory(srcDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,82 @@
|
||||||
|
package com.baeldung.tempdirectory;
|
||||||
|
|
||||||
|
import org.apache.commons.io.FileUtils;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.FileSystems;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.nio.file.attribute.FileAttribute;
|
||||||
|
import java.nio.file.attribute.PosixFileAttributes;
|
||||||
|
import java.nio.file.attribute.PosixFilePermission;
|
||||||
|
import java.nio.file.attribute.PosixFilePermissions;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests several possibilities on how to create
|
||||||
|
* temporary directories.
|
||||||
|
*
|
||||||
|
* @author Rui Vilao (rpvilao@gmail.com)
|
||||||
|
*/
|
||||||
|
public class TemporaryDirectoriesUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTempDirWithPrefixNoTargetSpecified_whenCreateWithPlainJava_thenInsideOSTempDirStructure() throws IOException {
|
||||||
|
final String tmpdir = Files.createTempDirectory("tmpDirPrefix").toFile().getAbsolutePath();
|
||||||
|
final String tmpDirsLocation = System.getProperty("java.io.tmpdir");
|
||||||
|
|
||||||
|
assertThat(tmpdir).startsWith(tmpDirsLocation);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTempDirWithPrefixNoTargetSpecified_whenCreateWithGuava_thenInsideOSTempDirStructure() throws IOException {
|
||||||
|
final String tmpdir = com.google.common.io.Files.createTempDir().getAbsolutePath();
|
||||||
|
final String tmpDirsLocation = System.getProperty("java.io.tmpdir");
|
||||||
|
|
||||||
|
assertThat(tmpdir).startsWith(tmpDirsLocation);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTempDirWithPrefixNoTargetSpecified_whenCreateWithApacheCommonsIo_thenInsideOSTempDirStructure() throws IOException {
|
||||||
|
final String tmpDirsLocation = System.getProperty("java.io.tmpdir");
|
||||||
|
final Path path = Paths.get(FileUtils.getTempDirectory().getAbsolutePath(), UUID.randomUUID().toString());
|
||||||
|
final String tmpdir = Files.createDirectories(path).toFile().getAbsolutePath();
|
||||||
|
|
||||||
|
assertThat(tmpdir).startsWith(tmpDirsLocation);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTempDirWithPrefixWithTargetSpecified_whenCreatePlainJava_thenInsideTarget() throws IOException {
|
||||||
|
final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix");
|
||||||
|
assertThat(tmpdir.toFile().getPath()).startsWith("target");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTempDirWithPrefixWithTargetSpecifiedWithDeleteOnExit_whenCreatePlainJava_thenInsideTarget() throws IOException {
|
||||||
|
final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix");
|
||||||
|
assertThat(tmpdir.toFile().getPath()).startsWith("target");
|
||||||
|
tmpdir.toFile().deleteOnExit();
|
||||||
|
// we can really assert this test, just as an example.
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTempDirWithPrefixWithFileAttrs_whenCreatePlainJava_thenAttributesAreSet() throws IOException {
|
||||||
|
boolean isPosix = FileSystems.getDefault().supportedFileAttributeViews().contains("posix");
|
||||||
|
|
||||||
|
if(!isPosix){
|
||||||
|
System.out.println("You must be under a Posix Compliant Filesystem to run this test.");
|
||||||
|
} else {
|
||||||
|
final FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("r--------"));
|
||||||
|
|
||||||
|
final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix", attrs);
|
||||||
|
assertThat(tmpdir.toFile().getPath()).startsWith("target");
|
||||||
|
assertThat(tmpdir.toFile().canWrite()).isFalse();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -17,7 +17,7 @@
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.baeldung.servicemodule</groupId>
|
<groupId>com.baeldung.servicemodule</groupId>
|
||||||
<artifactId>servicemodule</artifactId>
|
<artifactId>servicemodule1</artifactId>
|
||||||
<version>${servicemodule.version}</version>
|
<version>${servicemodule.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
|
@ -4,7 +4,8 @@
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
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">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>servicemodule</artifactId>
|
<groupId>com.baeldung.servicemodule</groupId>
|
||||||
|
<artifactId>servicemodule1</artifactId>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
|
|
|
@ -17,7 +17,7 @@
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.baeldung.servicemodule</groupId>
|
<groupId>com.baeldung.servicemodule</groupId>
|
||||||
<artifactId>servicemodule</artifactId>
|
<artifactId>servicemodule2</artifactId>
|
||||||
<version>${servicemodule.version}</version>
|
<version>${servicemodule.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
|
@ -4,7 +4,8 @@
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
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">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>servicemodule</artifactId>
|
<groupId>com.baeldung.servicemodule</groupId>
|
||||||
|
<artifactId>servicemodule2</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0</version>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
|
|
|
@ -5,4 +5,6 @@ This module contains articles about core features in the Java language
|
||||||
- [Class.isInstance vs Class.isAssignableFrom](https://www.baeldung.com/java-isinstance-isassignablefrom)
|
- [Class.isInstance vs Class.isAssignableFrom](https://www.baeldung.com/java-isinstance-isassignablefrom)
|
||||||
- [Converting a Java String Into a Boolean](https://www.baeldung.com/java-string-to-boolean)
|
- [Converting a Java String Into a Boolean](https://www.baeldung.com/java-string-to-boolean)
|
||||||
- [When are Static Variables Initialized in Java?](https://www.baeldung.com/java-static-variables-initialization)
|
- [When are Static Variables Initialized in Java?](https://www.baeldung.com/java-static-variables-initialization)
|
||||||
|
- [Checking if a Class Exists in Java](https://www.baeldung.com/java-check-class-exists)
|
||||||
|
- [The Difference Between a.getClass() and A.class in Java](https://www.baeldung.com/java-getclass-vs-class)
|
||||||
- [[<-- Prev]](/core-java-modules/core-java-lang-2)
|
- [[<-- Prev]](/core-java-modules/core-java-lang-2)
|
||||||
|
|
|
@ -0,0 +1,5 @@
|
||||||
|
package com.baeldung.getclassobject;
|
||||||
|
|
||||||
|
public class Animal {
|
||||||
|
protected int numberOfEyes;
|
||||||
|
}
|
|
@ -0,0 +1,4 @@
|
||||||
|
package com.baeldung.getclassobject;
|
||||||
|
|
||||||
|
public class Monkey extends Animal {
|
||||||
|
}
|
|
@ -0,0 +1,4 @@
|
||||||
|
package com.baeldung.getclassobject;
|
||||||
|
|
||||||
|
public abstract class SomeAbstractClass {
|
||||||
|
}
|
|
@ -0,0 +1,4 @@
|
||||||
|
package com.baeldung.getclassobject;
|
||||||
|
|
||||||
|
interface SomeInterface {
|
||||||
|
}
|
|
@ -0,0 +1,9 @@
|
||||||
|
package com.baeldung.getclassobject;
|
||||||
|
|
||||||
|
public class SomeUtils {
|
||||||
|
private SomeUtils() {
|
||||||
|
throw new RuntimeException("This Util class is not allowed to be instantiated!");
|
||||||
|
}
|
||||||
|
// public static utilMethods
|
||||||
|
// ...
|
||||||
|
}
|
|
@ -0,0 +1,34 @@
|
||||||
|
package com.baeldung.checkclassexistence;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class CheckClassExistenceUnitTest {
|
||||||
|
|
||||||
|
public static class InitializingClass {
|
||||||
|
static {
|
||||||
|
if (true) { //enable throwing of an exception in a static initialization block
|
||||||
|
throw new RuntimeException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = ClassNotFoundException.class) //thrown when class does not exist
|
||||||
|
public void givenNonExistingClass_whenUsingForName_thenClassNotFound() throws ClassNotFoundException {
|
||||||
|
Class.forName("class.that.does.not.exist");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenExistingClass_whenUsingForName_thenNoException() throws ClassNotFoundException {
|
||||||
|
Class.forName("java.lang.String");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = ExceptionInInitializerError.class) //thrown when exception occurs inside of a static initialization block
|
||||||
|
public void givenInitializingClass_whenUsingForName_thenInitializationError() throws ClassNotFoundException {
|
||||||
|
Class.forName("com.baeldung.checkclassexistence.CheckClassExistenceUnitTest$InitializingClass");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInitializingClass_whenUsingForNameWithoutInitialization_thenNoException() throws ClassNotFoundException {
|
||||||
|
Class.forName("com.baeldung.checkclassexistence.CheckClassExistenceUnitTest$InitializingClass", false, getClass().getClassLoader());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,55 @@
|
||||||
|
package com.baeldung.getclassobject;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class GetClassObjectUnitTest {
|
||||||
|
@Test
|
||||||
|
public void givenObjectAndType_whenGettingClassObject_thenTwoMethodsHaveTheSameResult() {
|
||||||
|
String str = "I am an object of the String class";
|
||||||
|
Class fromStrObject = str.getClass();
|
||||||
|
Class clazz = String.class;
|
||||||
|
assertSame(fromStrObject, clazz);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClassInheritance_whenGettingRuntimeTypeAndStaticType_thenGetDifferentResult() {
|
||||||
|
Animal animal = new Monkey();
|
||||||
|
Class runtimeType = animal.getClass();
|
||||||
|
Class staticType = Animal.class;
|
||||||
|
//Not equals
|
||||||
|
assertNotEquals(staticType, runtimeType);
|
||||||
|
|
||||||
|
Class monkeyClass = Monkey.class;
|
||||||
|
assertSame(runtimeType, monkeyClass);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPrimitiveType_whenGettingClassObject_thenOnlyStaticTypeWorks() {
|
||||||
|
int number = 7;
|
||||||
|
// Class numberClass = number.getClass(); <-- compilation error
|
||||||
|
Class intType = int.class;
|
||||||
|
|
||||||
|
assertNotNull(intType);
|
||||||
|
assertEquals("int", intType.getName());
|
||||||
|
assertTrue(intType.isPrimitive());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTypeCannotInstantiate_whenGetTypeStatically_thenGetTypesSuccefully() {
|
||||||
|
Class interfaceType = SomeInterface.class;
|
||||||
|
Class abstractClassType = SomeAbstractClass.class;
|
||||||
|
Class utilClassType = SomeUtils.class;
|
||||||
|
|
||||||
|
assertNotNull(interfaceType);
|
||||||
|
assertTrue(interfaceType.isInterface());
|
||||||
|
assertEquals("SomeInterface", interfaceType.getSimpleName());
|
||||||
|
|
||||||
|
assertNotNull(abstractClassType);
|
||||||
|
assertEquals("SomeAbstractClass", abstractClassType.getSimpleName());
|
||||||
|
|
||||||
|
assertNotNull(utilClassType);
|
||||||
|
assertEquals("SomeUtils", utilClassType.getSimpleName());
|
||||||
|
}
|
||||||
|
}
|
|
@ -13,4 +13,5 @@
|
||||||
- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude)
|
- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude)
|
||||||
- [Debugging with Eclipse](https://www.baeldung.com/eclipse-debugging)
|
- [Debugging with Eclipse](https://www.baeldung.com/eclipse-debugging)
|
||||||
- [Matrix Multiplication in Java](https://www.baeldung.com/java-matrix-multiplication)
|
- [Matrix Multiplication in Java](https://www.baeldung.com/java-matrix-multiplication)
|
||||||
|
- [Largest Power of 2 That Is Less Than the Given Number](https://www.baeldung.com/java-largest-power-of-2-less-than-number)
|
||||||
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math)
|
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math)
|
||||||
|
|
|
@ -9,3 +9,4 @@ This module contains articles about methods in Java
|
||||||
- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts)
|
- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts)
|
||||||
- [Guide to hashCode() in Java](https://www.baeldung.com/java-hashcode)
|
- [Guide to hashCode() in Java](https://www.baeldung.com/java-hashcode)
|
||||||
- [The Covariant Return Type in Java](https://www.baeldung.com/java-covariant-return-type)
|
- [The Covariant Return Type in Java](https://www.baeldung.com/java-covariant-return-type)
|
||||||
|
- [Does a Method’s Signature Include the Return Type in Java?](https://www.baeldung.com/java-method-signature-return-type)
|
||||||
|
|
|
@ -0,0 +1,72 @@
|
||||||
|
package com.baeldung.signature;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
public class OverloadingErrors<T extends Serializable> {
|
||||||
|
|
||||||
|
public void print() {
|
||||||
|
System.out.println("Signature is: print()");
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
// Uncommenting this method will lead to a compilation error: java: method print() is already defined in class
|
||||||
|
// The method signature is independent from return type
|
||||||
|
public int print() {
|
||||||
|
System.out.println("Signature is: print()");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
// Uncommenting this method will lead to a compilation error: java: method print() is already defined in class
|
||||||
|
// The method signature is independent from modifiers
|
||||||
|
private final void print() {
|
||||||
|
System.out.println("Signature is: print()");
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
// Uncommenting this method will lead to a compilation error: java: method print() is already defined in class
|
||||||
|
// The method signature is independent from thrown exception declaration
|
||||||
|
public void print() throws IllegalStateException {
|
||||||
|
System.out.println("Signature is: print()");
|
||||||
|
throw new IllegalStateException();
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
public void print(int parameter) {
|
||||||
|
System.out.println("Signature is: print(int)");
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
// Uncommenting this method will lead to a compilation error: java: method print(int) is already defined in class
|
||||||
|
// The method signature is independent from parameter names
|
||||||
|
public void print(int anotherParameter) {
|
||||||
|
System.out.println("Signature is: print(int)");
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
public void printElement(T t) {
|
||||||
|
System.out.println("Signature is: printElement(T)");
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
// Uncommenting this method will lead to a compilation error: java: name clash: printElement(java.io.Serializable) and printElement(T) have the same erasure
|
||||||
|
// Even though the signatures appear different, the compiler cannot statically bind the correct method after type erasure
|
||||||
|
public void printElement(Serializable o) {
|
||||||
|
System.out.println("Signature is: printElement(Serializable)");
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
public void print(Object... parameter) {
|
||||||
|
System.out.println("Signature is: print(Object...)");
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
// Uncommenting this method will lead to a compilation error: java cannot declare both sum(Object...) and sum(Object[])
|
||||||
|
// Even though the signatures appear different, after compilation they both resolve to sum(Object[])
|
||||||
|
public void print(Object[] parameter) {
|
||||||
|
System.out.println("Signature is: print(Object[])");
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
}
|
|
@ -0,0 +1,46 @@
|
||||||
|
package com.baeldung.signature;
|
||||||
|
|
||||||
|
public class StaticBinding {
|
||||||
|
|
||||||
|
public Number sum(Integer term1, Integer term2) {
|
||||||
|
System.out.println("Adding integers");
|
||||||
|
return term1 + term2;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Number sum(Number term1, Number term2) {
|
||||||
|
System.out.println("Adding numbers");
|
||||||
|
return term1.doubleValue() + term2.doubleValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Number sum(Object term1, Object term2) {
|
||||||
|
System.out.println("Adding objects");
|
||||||
|
return term1.hashCode() + term2.hashCode();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Number sum(Object term1, Object... term2) {
|
||||||
|
System.out.println("Adding variable arguments: " + term2.length);
|
||||||
|
int result = term1.hashCode();
|
||||||
|
for (Object o : term2) {
|
||||||
|
result += o.hashCode();
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
StaticBinding obj = new StaticBinding();
|
||||||
|
|
||||||
|
obj.sum(2, 3); // "Adding integers" due to auto-boxing from int to Integer
|
||||||
|
obj.sum(Integer.valueOf(2), Integer.valueOf(3)); // "Adding integers" due to exact parameter types
|
||||||
|
obj.sum(2, 0x1); // "Adding integers" due to type promotion from byte to int
|
||||||
|
|
||||||
|
obj.sum((Number) 2, (Number) 3); // "Adding numbers" due to explicit cast to Number
|
||||||
|
obj.sum(2.0d, 3.0d); // "Adding numbers" due to auto-boxing from double to Double
|
||||||
|
obj.sum(Float.valueOf(2), Float.valueOf(3)); // "Adding numbers" due to polimorphism
|
||||||
|
|
||||||
|
obj.sum((Object) 2, (Object) 3); // "Adding objects" due to explicit cast to Object
|
||||||
|
obj.sum(2, "John"); // "Adding objects" due to polimorphism
|
||||||
|
|
||||||
|
obj.sum(new Object(), new Object(), new Object()); // "Adding variable arguments 2"
|
||||||
|
obj.sum(new Object(), new Object[]{new Object()}); // "Adding variable arguments 1"
|
||||||
|
}
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue