Merge branch 'master' into BAEL-4183-dependency-management-in-gradle
This commit is contained in:
commit
d3b4cd59a0
|
@ -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]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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)
|
||||||
|
|
|
@ -11,4 +11,5 @@ This module contains articles about basic Java concurrency
|
||||||
- [Life Cycle of a Thread in Java](https://www.baeldung.com/java-thread-lifecycle)
|
- [Life Cycle of a Thread in Java](https://www.baeldung.com/java-thread-lifecycle)
|
||||||
- [Guide to AtomicMarkableReference](https://www.baeldung.com/java-atomicmarkablereference)
|
- [Guide to AtomicMarkableReference](https://www.baeldung.com/java-atomicmarkablereference)
|
||||||
- [Why are Local Variables Thread-Safe in Java](https://www.baeldung.com/java-local-variables-thread-safe)
|
- [Why are Local Variables Thread-Safe in Java](https://www.baeldung.com/java-local-variables-thread-safe)
|
||||||
|
- [How to Stop Execution After a Certain Time in Java](https://www.baeldung.com/java-stop-execution-after-certain-time)
|
||||||
- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic)
|
- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic)
|
||||||
|
|
|
@ -11,4 +11,5 @@ This module contains articles about core Java input and output (IO)
|
||||||
- [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)
|
- [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)
|
- [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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -6,6 +6,7 @@ import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
|
import java.io.FileOutputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
|
@ -37,6 +38,12 @@ public class CreateFileUnitTest {
|
||||||
assertTrue(success);
|
assertTrue(success);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenUsingFileOutputStream_whenCreatingFile_thenCorrect() throws IOException {
|
||||||
|
try(FileOutputStream fileOutputStream = new FileOutputStream(FILE_NAME)){
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
|
public void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
|
||||||
com.google.common.io.Files.touch(new File(FILE_NAME));
|
com.google.common.io.Files.touch(new File(FILE_NAME));
|
||||||
|
|
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -6,4 +6,5 @@ This module contains articles about core features in the Java language
|
||||||
- [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)
|
- [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,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());
|
||||||
|
}
|
||||||
|
}
|
|
@ -3,3 +3,4 @@
|
||||||
- [Reading the Value of ‘private’ Fields from a Different Class in Java](https://www.baeldung.com/java-reflection-read-private-field-value)
|
- [Reading the Value of ‘private’ Fields from a Different Class in Java](https://www.baeldung.com/java-reflection-read-private-field-value)
|
||||||
- [Set Field Value With Reflection](https://www.baeldung.com/java-set-private-field-value)
|
- [Set Field Value With Reflection](https://www.baeldung.com/java-set-private-field-value)
|
||||||
- [Checking If a Method is Static Using Reflection in Java](https://www.baeldung.com/java-check-method-is-static)
|
- [Checking If a Method is Static Using Reflection in Java](https://www.baeldung.com/java-check-method-is-static)
|
||||||
|
- [Checking if a Java Class is ‘abstract’ Using Reflection](https://www.baeldung.com/java-reflection-is-class-abstract)
|
||||||
|
|
|
@ -0,0 +1,15 @@
|
||||||
|
package com.baeldung.reflection.check.abstractclass;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalTime;
|
||||||
|
|
||||||
|
public abstract class AbstractExample {
|
||||||
|
|
||||||
|
public static String getAuthorName() {
|
||||||
|
return "Umang Budhwar";
|
||||||
|
}
|
||||||
|
|
||||||
|
public abstract LocalDate getLocalDate();
|
||||||
|
|
||||||
|
public abstract LocalTime getLocalTime();
|
||||||
|
}
|
|
@ -0,0 +1,16 @@
|
||||||
|
package com.baeldung.reflection.check.abstractclass;
|
||||||
|
|
||||||
|
import java.lang.reflect.Modifier;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Assertions;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class AbstractExampleUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenAbstractClass_whenCheckModifierIsAbstract_thenTrue() throws Exception {
|
||||||
|
Class<AbstractExample> clazz = AbstractExample.class;
|
||||||
|
Assertions.assertTrue(Modifier.isAbstract(clazz.getModifiers()));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -10,4 +10,6 @@ This module contains articles about core Java Security
|
||||||
- [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java)
|
- [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java)
|
||||||
- [Checksums in Java](https://www.baeldung.com/java-checksums)
|
- [Checksums in Java](https://www.baeldung.com/java-checksums)
|
||||||
- [How to Read PEM File to Get Public and Private Keys](https://www.baeldung.com/java-read-pem-file-keys)
|
- [How to Read PEM File to Get Public and Private Keys](https://www.baeldung.com/java-read-pem-file-keys)
|
||||||
|
- [Listing the Available Cipher Algorithms](https://www.baeldung.com/java-list-cipher-algorithms)
|
||||||
|
- [Get a List of Trusted Certificates in Java](https://www.baeldung.com/java-list-trusted-certificates)
|
||||||
- More articles: [[<-- prev]](/core-java-modules/core-java-security)
|
- More articles: [[<-- prev]](/core-java-modules/core-java-security)
|
||||||
|
|
|
@ -0,0 +1,94 @@
|
||||||
|
package com.baeldung.trustedcert;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import javax.net.ssl.TrustManager;
|
||||||
|
import javax.net.ssl.TrustManagerFactory;
|
||||||
|
import javax.net.ssl.X509TrustManager;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.security.KeyStore;
|
||||||
|
import java.security.KeyStoreException;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.security.cert.Certificate;
|
||||||
|
import java.security.cert.CertificateException;
|
||||||
|
import java.security.cert.PKIXParameters;
|
||||||
|
import java.security.cert.TrustAnchor;
|
||||||
|
import java.security.cert.X509Certificate;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Enumeration;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
public class CertificatesUnitTest {
|
||||||
|
|
||||||
|
private static final String GODADDY_CA_ALIAS = "godaddyrootg2ca [jdk]";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenLoadingCacertsKeyStore_thenCertificatesArePresent() throws Exception {
|
||||||
|
KeyStore keyStore = loadKeyStore();
|
||||||
|
PKIXParameters params = new PKIXParameters(keyStore);
|
||||||
|
|
||||||
|
Set<TrustAnchor> trustAnchors = params.getTrustAnchors();
|
||||||
|
List<Certificate> certificates = trustAnchors.stream()
|
||||||
|
.map(TrustAnchor::getTrustedCert)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertFalse(certificates.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenLoadingDefaultKeyStore_thenCertificatesArePresent() throws Exception {
|
||||||
|
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||||
|
trustManagerFactory.init((KeyStore)null);
|
||||||
|
|
||||||
|
List<TrustManager> trustManagers = Arrays.asList(trustManagerFactory.getTrustManagers());
|
||||||
|
List<X509Certificate> certificates = trustManagers.stream()
|
||||||
|
.filter(X509TrustManager.class::isInstance)
|
||||||
|
.map(X509TrustManager.class::cast)
|
||||||
|
.map(trustManager -> Arrays.asList(trustManager.getAcceptedIssuers()))
|
||||||
|
.flatMap(Collection::stream)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertFalse(certificates.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenLoadingKeyStore_thenGoDaddyCALabelIsPresent() throws Exception {
|
||||||
|
KeyStore keyStore = loadKeyStore();
|
||||||
|
|
||||||
|
Enumeration<String> aliasEnumeration = keyStore.aliases();
|
||||||
|
List<String> aliases = Collections.list(aliasEnumeration);
|
||||||
|
|
||||||
|
assertTrue(aliases.contains(GODADDY_CA_ALIAS));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenLoadingKeyStore_thenGoDaddyCertificateIsPresent() throws Exception {
|
||||||
|
KeyStore keyStore = loadKeyStore();
|
||||||
|
|
||||||
|
Certificate goDaddyCertificate = keyStore.getCertificate(GODADDY_CA_ALIAS);
|
||||||
|
|
||||||
|
assertNotNull(goDaddyCertificate);
|
||||||
|
}
|
||||||
|
|
||||||
|
private KeyStore loadKeyStore() throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException {
|
||||||
|
String relativeCacertsPath = "/lib/security/cacerts".replace("/", File.separator);
|
||||||
|
String filename = System.getProperty("java.home") + relativeCacertsPath;
|
||||||
|
FileInputStream is = new FileInputStream(filename);
|
||||||
|
|
||||||
|
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
|
||||||
|
String password = "changeit";
|
||||||
|
keystore.load(is, password.toCharArray());
|
||||||
|
|
||||||
|
return keystore;
|
||||||
|
}
|
||||||
|
}
|
|
@ -22,30 +22,6 @@ fun main() {
|
||||||
numbers.each { println(random * it) } // capturing the random variable
|
numbers.each { println(random * it) } // capturing the random variable
|
||||||
}
|
}
|
||||||
|
|
||||||
fun namedFunction(): Int {
|
|
||||||
return 42
|
|
||||||
}
|
|
||||||
|
|
||||||
fun anonymous(): () -> Int {
|
|
||||||
return fun(): Int {
|
|
||||||
return 42
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
inline fun <T> List<T>.eachIndexed(f: (Int, T) -> Unit) {
|
|
||||||
for (i in indices) {
|
|
||||||
f(i, this[i])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun <T> List<T>.indexOf(x: T): Int {
|
|
||||||
eachIndexed { index, value ->
|
|
||||||
if (value == x) return index
|
|
||||||
}
|
|
||||||
|
|
||||||
return -1
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generates a random number.
|
* Generates a random number.
|
||||||
*/
|
*/
|
||||||
|
|
|
@ -12,3 +12,4 @@ This module contains articles about Kotlin core features.
|
||||||
- [Sequences in Kotlin](https://www.baeldung.com/kotlin/sequences)
|
- [Sequences in Kotlin](https://www.baeldung.com/kotlin/sequences)
|
||||||
- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class)
|
- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class)
|
||||||
- [Exception Handling in Kotlin](https://www.baeldung.com/kotlin/exception-handling)
|
- [Exception Handling in Kotlin](https://www.baeldung.com/kotlin/exception-handling)
|
||||||
|
- [Quick Guide to Kotlin Default and Named Arguments](https://www.baeldung.com/kotlin/default-named-arguments)
|
||||||
|
|
|
@ -0,0 +1,37 @@
|
||||||
|
package com.baeldung.arguments
|
||||||
|
|
||||||
|
fun main() {
|
||||||
|
|
||||||
|
// Skip both the connectTimeout and enableRetry arguments
|
||||||
|
connect("http://www.baeldung.com")
|
||||||
|
|
||||||
|
// Skip only the enableRetry argument:
|
||||||
|
connect("http://www.baeldung.com", 5000)
|
||||||
|
|
||||||
|
// Skip only the middle argument connectTimeout
|
||||||
|
// connect("http://www.baeldung.com", false) // This results in a compiler error
|
||||||
|
|
||||||
|
// Because we skipped the connectTimeout argument, we must pass the enableRetry as a named argument
|
||||||
|
connect("http://www.baeldung.com", enableRetry = false)
|
||||||
|
|
||||||
|
// Overriding Functions and Default Arguments
|
||||||
|
val realConnector = RealConnector()
|
||||||
|
realConnector.connect("www.baeldung.com")
|
||||||
|
realConnector.connect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun connect(url: String, connectTimeout: Int = 1000, enableRetry: Boolean = true) {
|
||||||
|
println("The parameters are url = $url, connectTimeout = $connectTimeout, enableRetry = $enableRetry")
|
||||||
|
}
|
||||||
|
|
||||||
|
open class AbstractConnector {
|
||||||
|
open fun connect(url: String = "localhost") {
|
||||||
|
// function implementation
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class RealConnector : AbstractConnector() {
|
||||||
|
override fun connect(url: String) {
|
||||||
|
println("The parameter is url = $url")
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
package com.baeldung.arguments
|
||||||
|
|
||||||
|
fun main() {
|
||||||
|
resizePane(newSize = 10, forceResize = true, noAnimation = false)
|
||||||
|
|
||||||
|
// Swap the order of last two named arguments
|
||||||
|
resizePane(newSize = 11, noAnimation = false, forceResize = true)
|
||||||
|
|
||||||
|
// Named arguments can be passed in any order
|
||||||
|
resizePane(forceResize = true, newSize = 12, noAnimation = false)
|
||||||
|
|
||||||
|
// Mixing Named and Positional Arguments
|
||||||
|
// Kotlin 1.3 would allow us to name only the arguments after the positional ones
|
||||||
|
resizePane(20, true, noAnimation = false)
|
||||||
|
|
||||||
|
// Using a positional argument in the middle of named arguments (supported from Kotlin 1.4.0)
|
||||||
|
// resizePane(newSize = 20, true, noAnimation = false)
|
||||||
|
|
||||||
|
// Only the last argument as a positional argument (supported from Kotlin 1.4.0)
|
||||||
|
// resizePane(newSize = 30, forceResize = true, false)
|
||||||
|
|
||||||
|
// Use a named argument in the middle of positional arguments (supported from Kotlin 1.4.0)
|
||||||
|
// resizePane(40, forceResize = true, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun resizePane(newSize: Int, forceResize: Boolean, noAnimation: Boolean) {
|
||||||
|
println("The parameters are newSize = $newSize, forceResize = $forceResize, noAnimation = $noAnimation")
|
||||||
|
}
|
|
@ -1,4 +1,3 @@
|
||||||
## Relevant Articles:
|
## Relevant Articles:
|
||||||
|
|
||||||
- [Introduction to Docker Compose](https://www.baeldung.com/docker-compose)
|
- [Introduction to Docker Compose](https://www.baeldung.com/docker-compose)
|
||||||
- [Creating Docker Images with Spring Boot](https://www.baeldung.com/spring-boot-docker-images)
|
|
||||||
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
### Relevant Articles:
|
||||||
|
|
||||||
|
- [Creating Docker Images with Spring Boot](https://www.baeldung.com/spring-boot-docker-images)
|
|
@ -16,11 +16,6 @@
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
|
||||||
<groupId>io.github.openfeign</groupId>
|
|
||||||
<artifactId>feign-core</artifactId>
|
|
||||||
<version>${feign.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>io.github.openfeign</groupId>
|
<groupId>io.github.openfeign</groupId>
|
||||||
<artifactId>feign-okhttp</artifactId>
|
<artifactId>feign-okhttp</artifactId>
|
||||||
|
@ -44,21 +39,8 @@
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
|
||||||
<pluginManagement>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
|
||||||
<version>${spring-boot-maven-plugin.version}</version>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</pluginManagement>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<feign.version>9.4.0</feign.version>
|
<feign.version>10.11</feign.version>
|
||||||
<spring-boot-maven-plugin.version>1.4.2.RELEASE</spring-boot-maven-plugin.version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -6,8 +6,6 @@ import com.baeldung.feign.models.BookResource;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.junit.runners.JUnit4;
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
@ -22,7 +20,6 @@ import static org.junit.Assert.assertTrue;
|
||||||
* Consumes https://github.com/Baeldung/spring-hypermedia-api
|
* Consumes https://github.com/Baeldung/spring-hypermedia-api
|
||||||
*/
|
*/
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@RunWith(JUnit4.class)
|
|
||||||
public class BookClientLiveTest {
|
public class BookClientLiveTest {
|
||||||
private BookClient bookClient;
|
private BookClient bookClient;
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
### Relevant Articles:
|
||||||
|
|
||||||
|
- [Guide to the Gradle Wrapper](https://www.baeldung.com/gradle-wrapper)
|
|
@ -8,5 +8,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
|
|
||||||
- [How to Set TLS Version in Apache HttpClient](https://www.baeldung.com/TODO)
|
- [How to Set TLS Version in Apache HttpClient](https://www.baeldung.com/apache-httpclient-tls)
|
||||||
|
- [Reading an HTTP Response Body as a String in Java](https://www.baeldung.com/java-http-response-body-as-string)
|
||||||
|
- [How To Get Cookies From the Apache HttpClient Response](https://www.baeldung.com/java-apache-httpclient-cookies)
|
||||||
- More articles: [[<-- prev]](../httpclient)
|
- More articles: [[<-- prev]](../httpclient)
|
||||||
|
|
|
@ -4,6 +4,7 @@
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>httpclient-2</artifactId>
|
<artifactId>httpclient-2</artifactId>
|
||||||
<version>0.1-SNAPSHOT</version>
|
<version>0.1-SNAPSHOT</version>
|
||||||
|
<name>httpclient-2</name>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
|
@ -13,6 +14,7 @@
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
<!-- http client -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.httpcomponents</groupId>
|
<groupId>org.apache.httpcomponents</groupId>
|
||||||
<artifactId>httpclient</artifactId>
|
<artifactId>httpclient</artifactId>
|
||||||
|
@ -24,6 +26,19 @@
|
||||||
</exclusion>
|
</exclusion>
|
||||||
</exclusions>
|
</exclusions>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<!-- rest template -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
<version>${spring-boot.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<version>${spring-boot.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -34,10 +49,24 @@
|
||||||
<filtering>true</filtering>
|
<filtering>true</filtering>
|
||||||
</resource>
|
</resource>
|
||||||
</resources>
|
</resources>
|
||||||
|
<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>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<httpclient.version>4.5.8</httpclient.version>
|
<httpclient.version>4.5.8</httpclient.version>
|
||||||
|
<maven.compiler.source.version>11</maven.compiler.source.version>
|
||||||
|
<maven.compiler.target.version>11</maven.compiler.target.version>
|
||||||
|
<spring-boot.version>2.1.7.RELEASE</spring-boot.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -0,0 +1,54 @@
|
||||||
|
package com.baeldung.httpclient.cookies;
|
||||||
|
|
||||||
|
import org.apache.http.client.CookieStore;
|
||||||
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||||
|
import org.apache.http.client.methods.HttpGet;
|
||||||
|
import org.apache.http.client.protocol.HttpClientContext;
|
||||||
|
import org.apache.http.cookie.Cookie;
|
||||||
|
import org.apache.http.impl.client.BasicCookieStore;
|
||||||
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
|
import org.apache.http.impl.client.HttpClients;
|
||||||
|
import org.apache.http.impl.cookie.BasicClientCookie;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
|
||||||
|
public class HttpClientGettingCookieValueUnitTest {
|
||||||
|
private static Logger log = LoggerFactory.getLogger(HttpClientGettingCookieValueUnitTest.class);
|
||||||
|
|
||||||
|
private static final String SAMPLE_URL = "http://www.baeldung.com/";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public final void whenSettingCustomCookieOnTheRequest_thenGettingTheSameCookieFromTheResponse() throws IOException {
|
||||||
|
HttpClientContext context = HttpClientContext.create();
|
||||||
|
context.setAttribute(HttpClientContext.COOKIE_STORE, createCustomCookieStore());
|
||||||
|
|
||||||
|
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
|
||||||
|
try (CloseableHttpResponse response = httpClient.execute(new HttpGet(SAMPLE_URL), context)) {
|
||||||
|
CookieStore cookieStore = context.getCookieStore();
|
||||||
|
Cookie customCookie = cookieStore.getCookies()
|
||||||
|
.stream()
|
||||||
|
.peek(cookie -> log.info("cookie name:{}", cookie.getName()))
|
||||||
|
.filter(cookie -> "custom_cookie".equals(cookie.getName()))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow(IllegalStateException::new);
|
||||||
|
|
||||||
|
assertEquals("test_value", customCookie.getValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private BasicCookieStore createCustomCookieStore() {
|
||||||
|
BasicCookieStore cookieStore = new BasicCookieStore();
|
||||||
|
BasicClientCookie cookie = new BasicClientCookie("custom_cookie", "test_value");
|
||||||
|
cookie.setDomain("baeldung.com");
|
||||||
|
cookie.setPath("/");
|
||||||
|
cookieStore.addCookie(cookie);
|
||||||
|
return cookieStore;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,26 @@
|
||||||
|
package com.baeldung.httpclient.readresponsebodystring;
|
||||||
|
|
||||||
|
import org.apache.http.HttpEntity;
|
||||||
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||||
|
import org.apache.http.client.methods.HttpGet;
|
||||||
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
|
import org.apache.http.impl.client.HttpClients;
|
||||||
|
import org.apache.http.util.EntityUtils;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class ApacheHttpClientUnitTest {
|
||||||
|
public static final String DUMMY_URL = "https://postman-echo.com/get";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUseApacheHttpClient_thenCorrect() throws IOException {
|
||||||
|
HttpGet request = new HttpGet(DUMMY_URL);
|
||||||
|
|
||||||
|
try (CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(request)) {
|
||||||
|
HttpEntity entity = response.getEntity();
|
||||||
|
String result = EntityUtils.toString(entity);
|
||||||
|
System.out.println("Response -> " + result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,29 @@
|
||||||
|
package com.baeldung.httpclient.readresponsebodystring;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
|
||||||
|
public class HttpClientUnitTest {
|
||||||
|
public static final String DUMMY_URL = "https://postman-echo.com/get";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUseHttpClient_thenCorrect() throws IOException, InterruptedException {
|
||||||
|
HttpClient client = HttpClient.newHttpClient();
|
||||||
|
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(DUMMY_URL)).build();
|
||||||
|
|
||||||
|
// synchronous response
|
||||||
|
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||||
|
System.out.println(response.body());
|
||||||
|
|
||||||
|
// asynchronous response
|
||||||
|
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
||||||
|
.thenApply(HttpResponse::body)
|
||||||
|
.thenAccept(System.out::println)
|
||||||
|
.join();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,34 @@
|
||||||
|
package com.baeldung.httpclient.readresponsebodystring;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.URL;
|
||||||
|
|
||||||
|
public class HttpUrlConnectionUnitTest {
|
||||||
|
|
||||||
|
public static final String DUMMY_URL = "https://postman-echo.com/get";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUseHttpUrlConnection_thenCorrect() throws IOException {
|
||||||
|
HttpURLConnection connection = (HttpURLConnection) new URL(DUMMY_URL).openConnection();
|
||||||
|
|
||||||
|
InputStream inputStream = connection.getInputStream();
|
||||||
|
|
||||||
|
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
|
||||||
|
StringBuilder response = new StringBuilder();
|
||||||
|
String currentLine;
|
||||||
|
|
||||||
|
while ((currentLine = in.readLine()) != null)
|
||||||
|
response.append(currentLine);
|
||||||
|
|
||||||
|
in.close();
|
||||||
|
Assert.assertNotNull(response.toString());
|
||||||
|
System.out.println("Response -> " + response.toString());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
package com.baeldung.httpclient.readresponsebodystring;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
public class SpringRestTemplateUnitTest {
|
||||||
|
|
||||||
|
public static final String DUMMY_URL = "https://postman-echo.com/get";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUseRestTemplate_thenCorrect() {
|
||||||
|
RestTemplate restTemplate = new RestTemplate();
|
||||||
|
String response = restTemplate.getForObject(DUMMY_URL, String.class);
|
||||||
|
System.out.println(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -23,6 +23,13 @@
|
||||||
<artifactId>jackson-datatype-joda</artifactId>
|
<artifactId>jackson-datatype-joda</artifactId>
|
||||||
<version>${jackson.version}</version>
|
<version>${jackson.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
|
<artifactId>jackson-core</artifactId>
|
||||||
|
<version>${jackson.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
|
|
@ -60,8 +60,6 @@ public class CustomDeserializationUnitTest {
|
||||||
String converted = objectMapper.writeValueAsString(now);
|
String converted = objectMapper.writeValueAsString(now);
|
||||||
// restore an instance of ZonedDateTime from String
|
// restore an instance of ZonedDateTime from String
|
||||||
ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
|
ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
|
||||||
System.out.println("serialized: " + now);
|
|
||||||
System.out.println("restored: " + restored);
|
|
||||||
assertThat(now, is(not(restored)));
|
assertThat(now, is(not(restored)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -70,15 +68,14 @@ public class CustomDeserializationUnitTest {
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
objectMapper.findAndRegisterModules();
|
objectMapper.findAndRegisterModules();
|
||||||
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||||
|
objectMapper.enable(SerializationFeature.WRITE_DATES_WITH_ZONE_ID);
|
||||||
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
|
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
|
||||||
// construct a new instance of ZonedDateTime
|
// construct a new instance of ZonedDateTime
|
||||||
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));
|
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));
|
||||||
String converted = objectMapper.writeValueAsString(now);
|
String converted = objectMapper.writeValueAsString(now);
|
||||||
// restore an instance of ZonedDateTime from String
|
// restore an instance of ZonedDateTime from String
|
||||||
ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
|
ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
|
||||||
System.out.println("serialized: " + now);
|
assertThat(restored, is(now));
|
||||||
System.out.println("restored: " + restored);
|
|
||||||
assertThat(now, is(restored));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -24,7 +24,6 @@ public class CustomSerializationUnitTest {
|
||||||
public final void whenSerializing_thenNoExceptions() throws JsonGenerationException, JsonMappingException, IOException {
|
public final void whenSerializing_thenNoExceptions() throws JsonGenerationException, JsonMappingException, IOException {
|
||||||
final Item myItem = new Item(1, "theItem", new User(2, "theUser"));
|
final Item myItem = new Item(1, "theItem", new User(2, "theUser"));
|
||||||
final String serialized = new ObjectMapper().writeValueAsString(myItem);
|
final String serialized = new ObjectMapper().writeValueAsString(myItem);
|
||||||
System.out.println(serialized);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -38,7 +37,6 @@ public class CustomSerializationUnitTest {
|
||||||
mapper.registerModule(simpleModule);
|
mapper.registerModule(simpleModule);
|
||||||
|
|
||||||
final String serialized = mapper.writeValueAsString(myItem);
|
final String serialized = mapper.writeValueAsString(myItem);
|
||||||
System.out.println(serialized);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -46,7 +44,6 @@ public class CustomSerializationUnitTest {
|
||||||
final ItemWithSerializer myItem = new ItemWithSerializer(1, "theItem", new User(2, "theUser"));
|
final ItemWithSerializer myItem = new ItemWithSerializer(1, "theItem", new User(2, "theUser"));
|
||||||
|
|
||||||
final String serialized = new ObjectMapper().writeValueAsString(myItem);
|
final String serialized = new ObjectMapper().writeValueAsString(myItem);
|
||||||
System.out.println(serialized);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -37,7 +37,6 @@ public class IgnoreFieldsWithFilterUnitTest {
|
||||||
assertThat(dtoAsString, not(containsString("intValue")));
|
assertThat(dtoAsString, not(containsString("intValue")));
|
||||||
assertThat(dtoAsString, containsString("booleanValue"));
|
assertThat(dtoAsString, containsString("booleanValue"));
|
||||||
assertThat(dtoAsString, containsString("stringValue"));
|
assertThat(dtoAsString, containsString("stringValue"));
|
||||||
System.out.println(dtoAsString);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -83,7 +82,6 @@ public class IgnoreFieldsWithFilterUnitTest {
|
||||||
assertThat(dtoAsString, not(containsString("intValue")));
|
assertThat(dtoAsString, not(containsString("intValue")));
|
||||||
assertThat(dtoAsString, containsString("booleanValue"));
|
assertThat(dtoAsString, containsString("booleanValue"));
|
||||||
assertThat(dtoAsString, containsString("stringValue"));
|
assertThat(dtoAsString, containsString("stringValue"));
|
||||||
System.out.println(dtoAsString);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -51,8 +51,6 @@ public class JacksonDynamicIgnoreUnitTest {
|
||||||
assertTrue(result.contains("john"));
|
assertTrue(result.contains("john"));
|
||||||
assertTrue(result.contains("address"));
|
assertTrue(result.contains("address"));
|
||||||
assertTrue(result.contains("usa"));
|
assertTrue(result.contains("usa"));
|
||||||
|
|
||||||
System.out.println("Not Hidden = " + result);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -65,8 +63,6 @@ public class JacksonDynamicIgnoreUnitTest {
|
||||||
assertTrue(result.contains("john"));
|
assertTrue(result.contains("john"));
|
||||||
assertFalse(result.contains("address"));
|
assertFalse(result.contains("address"));
|
||||||
assertFalse(result.contains("usa"));
|
assertFalse(result.contains("usa"));
|
||||||
|
|
||||||
System.out.println("Address Hidden = " + result);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -76,8 +72,6 @@ public class JacksonDynamicIgnoreUnitTest {
|
||||||
final String result = mapper.writeValueAsString(person);
|
final String result = mapper.writeValueAsString(person);
|
||||||
|
|
||||||
assertTrue(result.length() == 0);
|
assertTrue(result.length() == 0);
|
||||||
|
|
||||||
System.out.println("All Hidden = " + result);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -90,7 +84,5 @@ public class JacksonDynamicIgnoreUnitTest {
|
||||||
final Person p3 = new Person("adam", ad3, false);
|
final Person p3 = new Person("adam", ad3, false);
|
||||||
|
|
||||||
final String result = mapper.writeValueAsString(Arrays.asList(p1, p2, p3));
|
final String result = mapper.writeValueAsString(Arrays.asList(p1, p2, p3));
|
||||||
|
|
||||||
System.out.println(result);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,3 +5,4 @@ This module contains articles about the Java Native Interface (JNI).
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
|
|
||||||
- [Guide to JNI (Java Native Interface)](https://www.baeldung.com/jni)
|
- [Guide to JNI (Java Native Interface)](https://www.baeldung.com/jni)
|
||||||
|
- [Using JNA to Access Native Dynamic Libraries](https://www.baeldung.com/java-jna-dynamic-libraries)
|
|
@ -0,0 +1,39 @@
|
||||||
|
<?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>java-native</artifactId>
|
||||||
|
<name>java-native</name>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<jna.version>5.6.0</jna.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>net.java.dev.jna</groupId>
|
||||||
|
<artifactId>jna-platform</artifactId>
|
||||||
|
<version>${jna.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<!-- we don't want to reuse JVMs here ! -->
|
||||||
|
<reuseForks>false</reuseForks>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
0
jni/src/main/cpp/generateNativeLib.sh → java-native/src/main/cpp/generateNativeLib.sh
Executable file → Normal file
0
jni/src/main/cpp/generateNativeLib.sh → java-native/src/main/cpp/generateNativeLib.sh
Executable file → Normal file
0
jni/src/main/cpp/generateNativeLibMac.sh → java-native/src/main/cpp/generateNativeLibMac.sh
Executable file → Normal file
0
jni/src/main/cpp/generateNativeLibMac.sh → java-native/src/main/cpp/generateNativeLibMac.sh
Executable file → Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
package com.baeldung.jna;
|
||||||
|
|
||||||
|
import com.sun.jna.Library;
|
||||||
|
import com.sun.jna.Native;
|
||||||
|
import com.sun.jna.Platform;
|
||||||
|
|
||||||
|
public interface CMath extends Library {
|
||||||
|
CMath INSTANCE = Native.load(Platform.isWindows() ? "msvcrt" : "c", CMath.class);
|
||||||
|
double cosh(double value);
|
||||||
|
}
|
|
@ -0,0 +1,8 @@
|
||||||
|
package com.baeldung.jna;
|
||||||
|
|
||||||
|
public class Main {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,46 @@
|
||||||
|
package com.baeldung.jna;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import com.sun.jna.FunctionMapper;
|
||||||
|
import com.sun.jna.LastErrorException;
|
||||||
|
import com.sun.jna.Library;
|
||||||
|
import com.sun.jna.Native;
|
||||||
|
import com.sun.jna.NativeLong;
|
||||||
|
import com.sun.jna.Platform;
|
||||||
|
import com.sun.jna.Structure;
|
||||||
|
import com.sun.jna.Structure.FieldOrder;
|
||||||
|
|
||||||
|
public interface NativeFS extends Library {
|
||||||
|
|
||||||
|
FunctionMapper mapper = (library,method) -> {
|
||||||
|
if (Platform.isWindows()) {
|
||||||
|
return "_" + method.getName();
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return "__x" + method.getName(); // On Linux, stat is actually _xstat
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
public NativeFS INSTANCE = Native.load(Platform.isWindows() ? "msvcrt" : "c",
|
||||||
|
NativeFS.class,
|
||||||
|
Collections.singletonMap(Library.OPTION_FUNCTION_MAPPER, mapper));
|
||||||
|
|
||||||
|
int stat(String path, Stat stat) throws LastErrorException;
|
||||||
|
|
||||||
|
@FieldOrder({"st_dev","st_ino","st_mode","st_nlink","st_uid","st_gid","st_rdev","st_size","st_atime","st_mtime","st_ctime"})
|
||||||
|
public class Stat extends Structure {
|
||||||
|
public int st_dev;
|
||||||
|
public int st_ino;
|
||||||
|
public short st_mode;
|
||||||
|
public short st_nlink;
|
||||||
|
public short st_uid;
|
||||||
|
public short st_gid;
|
||||||
|
public int st_rdev;
|
||||||
|
public NativeLong st_size;
|
||||||
|
public NativeLong st_atime;
|
||||||
|
public NativeLong st_mtime;
|
||||||
|
public NativeLong st_ctime;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
package com.baeldung.jna;
|
||||||
|
|
||||||
|
import com.sun.jna.LastErrorException;
|
||||||
|
import com.sun.jna.Library;
|
||||||
|
import com.sun.jna.Native;
|
||||||
|
import com.sun.jna.Platform;
|
||||||
|
import com.sun.jna.Pointer;
|
||||||
|
|
||||||
|
public interface StdC extends Library {
|
||||||
|
StdC INSTANCE = Native.load(Platform.isWindows() ? "msvcrt" : "c", StdC.class );
|
||||||
|
Pointer malloc(long n);
|
||||||
|
void free(Pointer p);
|
||||||
|
Pointer memset(Pointer p, int c, long n);
|
||||||
|
int open(String path, int flags) throws LastErrorException;
|
||||||
|
int close(int fd) throws LastErrorException;
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,18 @@
|
||||||
|
package com.baeldung.jna;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import com.sun.jna.Native;
|
||||||
|
import com.sun.jna.Platform;
|
||||||
|
|
||||||
|
class CMathUnitTest {
|
||||||
|
@Test
|
||||||
|
void whenCallNative_thenSuccess() {
|
||||||
|
CMath lib = Native.load(Platform.isWindows() ? "msvcrt" : "c", CMath.class);
|
||||||
|
double result = lib.cosh(0);
|
||||||
|
assertEquals(1.0,result);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,38 @@
|
||||||
|
package com.baeldung.jna;
|
||||||
|
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import com.baeldung.jna.NativeFS.Stat;
|
||||||
|
import com.sun.jna.LastErrorException;
|
||||||
|
import com.sun.jna.Platform;
|
||||||
|
|
||||||
|
public class NativeFSUnitTest {
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCallNative_thenSuccess() throws IOException {
|
||||||
|
NativeFS lib = NativeFS.INSTANCE;
|
||||||
|
|
||||||
|
File f = Files.createTempFile("junit", ".bin").toFile();
|
||||||
|
f.deleteOnExit();
|
||||||
|
Stat stat = new Stat();
|
||||||
|
try {
|
||||||
|
if (Platform.isWindows()) {
|
||||||
|
int rc = lib.stat(f.getAbsolutePath(), stat);
|
||||||
|
assertEquals(0, rc);
|
||||||
|
assertEquals(0,stat.st_size.longValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch(LastErrorException error) {
|
||||||
|
fail("stat failed: error code=" + error.getErrorCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,47 @@
|
||||||
|
package com.baeldung.jna;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import com.sun.jna.Native;
|
||||||
|
import com.sun.jna.Platform;
|
||||||
|
import com.sun.jna.Pointer;
|
||||||
|
|
||||||
|
class StdCUnitTest {
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void setupProtectedMode() {
|
||||||
|
Native.setProtected(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMalloc_thenSuccess() {
|
||||||
|
StdC lib = StdC.INSTANCE;
|
||||||
|
Pointer p = lib.malloc(1024);
|
||||||
|
p.setMemory(0l, 1024l, (byte) 0);
|
||||||
|
lib.free(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenAccessViolation_thenShouldThrowError() {
|
||||||
|
// Running this test on Linux requires additional setup using libjsig.so
|
||||||
|
// Details here: http://java-native-access.github.io/jna/5.6.0/javadoc/overview-summary.html#crash-protection
|
||||||
|
// IMPORTANT NOTICE: Code for illustration purposes only. DON'T DO THIS IN YOUR OWN CODE
|
||||||
|
if ( Platform.isWindows()) {
|
||||||
|
Error e = null;
|
||||||
|
Pointer p = new Pointer(0l);
|
||||||
|
|
||||||
|
try {
|
||||||
|
p.setMemory(0, 100*1024, (byte) 0);
|
||||||
|
}
|
||||||
|
catch(Error err) {
|
||||||
|
e = err;
|
||||||
|
}
|
||||||
|
|
||||||
|
assertNotNull(e, "Should throw Error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Binary file not shown.
Binary file not shown.
14
jni/pom.xml
14
jni/pom.xml
|
@ -1,14 +0,0 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<artifactId>jni</artifactId>
|
|
||||||
<name>jni</name>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>parent-modules</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
</project>
|
|
|
@ -53,12 +53,12 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
<artifactId>jackson-annotations</artifactId>
|
<artifactId>jackson-annotations</artifactId>
|
||||||
<version>2.11.0</version>
|
<version>${jackson.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
<artifactId>jackson-databind</artifactId>
|
<artifactId>jackson-databind</artifactId>
|
||||||
<version>2.11.0</version>
|
<version>${jackson.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.io-informatics.oss</groupId>
|
<groupId>com.io-informatics.oss</groupId>
|
||||||
|
|
|
@ -7,22 +7,38 @@ import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
|
||||||
import au.com.dius.pact.model.RequestResponsePact;
|
import au.com.dius.pact.model.RequestResponsePact;
|
||||||
import org.junit.Rule;
|
import org.junit.Rule;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.springframework.http.HttpEntity;
|
import org.springframework.http.*;
|
||||||
import org.springframework.http.HttpHeaders;
|
|
||||||
import org.springframework.http.HttpMethod;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.web.client.RestTemplate;
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.ServerSocket;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
public class PactConsumerDrivenContractUnitTest {
|
public class PactConsumerDrivenContractUnitTest {
|
||||||
|
|
||||||
|
private static int getAvailablePort() {
|
||||||
|
return new Random()
|
||||||
|
.ints(6000, 9000)
|
||||||
|
.filter(PactConsumerDrivenContractUnitTest::isFree)
|
||||||
|
.findFirst()
|
||||||
|
.orElse(8080);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isFree(int port) {
|
||||||
|
try {
|
||||||
|
new ServerSocket(port).close();
|
||||||
|
return true;
|
||||||
|
} catch (IOException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Rule
|
@Rule
|
||||||
public PactProviderRuleMk2 mockProvider = new PactProviderRuleMk2("test_provider", "localhost", 8080, this);
|
public PactProviderRuleMk2 mockProvider = new PactProviderRuleMk2("test_provider", "localhost", getAvailablePort(), this);
|
||||||
|
|
||||||
@Pact(consumer = "test_consumer")
|
@Pact(consumer = "test_consumer")
|
||||||
public RequestResponsePact createPact(PactDslWithProvider builder) {
|
public RequestResponsePact createPact(PactDslWithProvider builder) {
|
||||||
|
|
|
@ -16,4 +16,5 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m
|
||||||
- [Exactly Once Processing in Kafka](https://www.baeldung.com/kafka-exactly-once)
|
- [Exactly Once Processing in Kafka](https://www.baeldung.com/kafka-exactly-once)
|
||||||
- [Introduction to Protonpack](https://www.baeldung.com/java-protonpack)
|
- [Introduction to Protonpack](https://www.baeldung.com/java-protonpack)
|
||||||
- [Java-R Integration](https://www.baeldung.com/java-r-integration)
|
- [Java-R Integration](https://www.baeldung.com/java-r-integration)
|
||||||
|
- [Using libphonenumber to Validate Phone Numbers](https://www.baeldung.com/java-libphonenumber)
|
||||||
- More articles [[<-- prev]](/libraries-5)
|
- More articles [[<-- prev]](/libraries-5)
|
||||||
|
|
|
@ -107,6 +107,12 @@
|
||||||
<artifactId>renjin-script-engine</artifactId>
|
<artifactId>renjin-script-engine</artifactId>
|
||||||
<version>${renjin.version}</version>
|
<version>${renjin.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<!-- libphonenumber -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.googlecode.libphonenumber</groupId>
|
||||||
|
<artifactId>libphonenumber</artifactId>
|
||||||
|
<version>${libphonenumber.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<repositories>
|
<repositories>
|
||||||
|
@ -150,6 +156,7 @@
|
||||||
<renjin.version>RELEASE</renjin.version>
|
<renjin.version>RELEASE</renjin.version>
|
||||||
<rcaller.version>3.0</rcaller.version>
|
<rcaller.version>3.0</rcaller.version>
|
||||||
<rserve.version>1.8.1</rserve.version>
|
<rserve.version>1.8.1</rserve.version>
|
||||||
|
<libphonenumber.version>8.12.9</libphonenumber.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,79 @@
|
||||||
|
package com.baeldung.libphonenumber;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.google.i18n.phonenumbers.NumberParseException;
|
||||||
|
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||||
|
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberType;
|
||||||
|
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
|
||||||
|
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber.CountryCodeSource;
|
||||||
|
|
||||||
|
public class LibPhoneNumberUnitTest {
|
||||||
|
|
||||||
|
private static final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPhoneNumber_whenValid_thenOK() throws Exception {
|
||||||
|
|
||||||
|
PhoneNumber phone = phoneNumberUtil.parse("+911234567890", CountryCodeSource.UNSPECIFIED.name());
|
||||||
|
|
||||||
|
assertTrue(phoneNumberUtil.isValidNumber(phone));
|
||||||
|
assertTrue(phoneNumberUtil.isValidNumberForRegion(phone, "IN"));
|
||||||
|
assertFalse(phoneNumberUtil.isValidNumberForRegion(phone, "US"));
|
||||||
|
assertTrue(phoneNumberUtil.isValidNumber(phoneNumberUtil.getExampleNumber("IN")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPhoneNumber_whenAlphaNumber_thenValid() {
|
||||||
|
assertTrue(phoneNumberUtil.isAlphaNumber("325-CARS"));
|
||||||
|
assertTrue(phoneNumberUtil.isAlphaNumber("0800 REPAIR"));
|
||||||
|
assertTrue(phoneNumberUtil.isAlphaNumber("1-800-MY-APPLE"));
|
||||||
|
assertTrue(phoneNumberUtil.isAlphaNumber("1-800-MY-APPLE.."));
|
||||||
|
assertFalse(phoneNumberUtil.isAlphaNumber("+876 1234-1234"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPhoneNumber_whenPossibleForType_thenValid() {
|
||||||
|
PhoneNumber number = new PhoneNumber();
|
||||||
|
number.setCountryCode(54);
|
||||||
|
|
||||||
|
number.setNationalNumber(123456);
|
||||||
|
assertTrue(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
|
||||||
|
assertFalse(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.TOLL_FREE));
|
||||||
|
|
||||||
|
number.setNationalNumber(12345678901L);
|
||||||
|
assertFalse(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
|
||||||
|
assertTrue(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.MOBILE));
|
||||||
|
assertFalse(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.TOLL_FREE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPhoneNumber_whenPossible_thenValid() {
|
||||||
|
PhoneNumber number = new PhoneNumber();
|
||||||
|
number.setCountryCode(1)
|
||||||
|
.setNationalNumber(123000L);
|
||||||
|
assertFalse(phoneNumberUtil.isPossibleNumber(number));
|
||||||
|
assertFalse(phoneNumberUtil.isPossibleNumber("+1 343 253 00000", "US"));
|
||||||
|
assertFalse(phoneNumberUtil.isPossibleNumber("(343) 253-00000", "US"));
|
||||||
|
assertFalse(phoneNumberUtil.isPossibleNumber("dial p for pizza", "US"));
|
||||||
|
assertFalse(phoneNumberUtil.isPossibleNumber("123-000", "US"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPhoneNumber_whenNumberGeographical_thenValid() throws NumberParseException {
|
||||||
|
|
||||||
|
PhoneNumber phone = phoneNumberUtil.parse("+911234567890", "IN");
|
||||||
|
assertTrue(phoneNumberUtil.isNumberGeographical(phone));
|
||||||
|
|
||||||
|
phone = new PhoneNumber().setCountryCode(1)
|
||||||
|
.setNationalNumber(2530000L);
|
||||||
|
assertFalse(phoneNumberUtil.isNumberGeographical(phone));
|
||||||
|
|
||||||
|
phone = new PhoneNumber().setCountryCode(800)
|
||||||
|
.setNationalNumber(12345678L);
|
||||||
|
assertFalse(phoneNumberUtil.isNumberGeographical(phone));
|
||||||
|
}
|
||||||
|
}
|
|
@ -168,7 +168,7 @@
|
||||||
<crdt.version>0.1.0</crdt.version>
|
<crdt.version>0.1.0</crdt.version>
|
||||||
<unit-ri.version>1.0.3</unit-ri.version>
|
<unit-ri.version>1.0.3</unit-ri.version>
|
||||||
<infinispan.version>9.1.5.Final</infinispan.version>
|
<infinispan.version>9.1.5.Final</infinispan.version>
|
||||||
<jackson.version>2.9.8</jackson.version>
|
<!-- <jackson.version>2.9.8</jackson.version>-->
|
||||||
<spring.version>4.3.8.RELEASE</spring.version>
|
<spring.version>4.3.8.RELEASE</spring.version>
|
||||||
<suanshu.version>4.0.0</suanshu.version>
|
<suanshu.version>4.0.0</suanshu.version>
|
||||||
<derive4j.version>1.1.0</derive4j.version>
|
<derive4j.version>1.1.0</derive4j.version>
|
||||||
|
|
|
@ -72,7 +72,7 @@
|
||||||
<okhttp.version>3.14.2</okhttp.version>
|
<okhttp.version>3.14.2</okhttp.version>
|
||||||
<gson.version>2.8.5</gson.version>
|
<gson.version>2.8.5</gson.version>
|
||||||
<mockwebserver.version>3.14.2</mockwebserver.version>
|
<mockwebserver.version>3.14.2</mockwebserver.version>
|
||||||
<jackson.version>2.9.8</jackson.version>
|
<!-- <jackson.version>2.9.8</jackson.version>-->
|
||||||
<jetty.httpclient.version>1.0.3</jetty.httpclient.version>
|
<jetty.httpclient.version>1.0.3</jetty.httpclient.version>
|
||||||
<jetty.server.version>9.4.19.v20190610</jetty.server.version>
|
<jetty.server.version>9.4.19.v20190610</jetty.server.version>
|
||||||
<rxjava2.version>2.2.11</rxjava2.version>
|
<rxjava2.version>2.2.11</rxjava2.version>
|
||||||
|
|
|
@ -118,7 +118,7 @@
|
||||||
<properties>
|
<properties>
|
||||||
<gson.version>2.8.5</gson.version>
|
<gson.version>2.8.5</gson.version>
|
||||||
<httpclient.version>4.5.3</httpclient.version>
|
<httpclient.version>4.5.3</httpclient.version>
|
||||||
<jackson.version>2.9.8</jackson.version>
|
<!-- <jackson.version>2.9.8</jackson.version>-->
|
||||||
<assertj.version>3.6.2</assertj.version>
|
<assertj.version>3.6.2</assertj.version>
|
||||||
<com.squareup.okhttp3.version>3.14.2</com.squareup.okhttp3.version>
|
<com.squareup.okhttp3.version>3.14.2</com.squareup.okhttp3.version>
|
||||||
<googleclient.version>1.23.0</googleclient.version>
|
<googleclient.version>1.23.0</googleclient.version>
|
||||||
|
|
|
@ -66,12 +66,12 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
<artifactId>jackson-databind</artifactId>
|
<artifactId>jackson-databind</artifactId>
|
||||||
<version>${fasterxml.jackson.version}</version>
|
<version>${jackson.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||||
<artifactId>jackson-dataformat-smile</artifactId>
|
<artifactId>jackson-dataformat-smile</artifactId>
|
||||||
<version>${fasterxml.jackson.version}</version>
|
<version>${jackson.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
|
@ -93,7 +93,7 @@
|
||||||
<dep.ver.servlet>3.1.0</dep.ver.servlet>
|
<dep.ver.servlet>3.1.0</dep.ver.servlet>
|
||||||
<netflix.servo.ver>0.12.17</netflix.servo.ver>
|
<netflix.servo.ver>0.12.17</netflix.servo.ver>
|
||||||
<micrometer.ver>0.12.0.RELEASE</micrometer.ver>
|
<micrometer.ver>0.12.0.RELEASE</micrometer.ver>
|
||||||
<fasterxml.jackson.version>2.9.1</fasterxml.jackson.version>
|
<!-- <fasterxml.jackson.version>2.9.1</fasterxml.jackson.version>-->
|
||||||
<spring-boot-starter-web.version>2.0.7.RELEASE</spring-boot-starter-web.version>
|
<spring-boot-starter-web.version>2.0.7.RELEASE</spring-boot-starter-web.version>
|
||||||
<assertj-core.version>3.11.1</assertj-core.version>
|
<assertj-core.version>3.11.1</assertj-core.version>
|
||||||
<metrics-aspectj.version>1.1.0</metrics-aspectj.version>
|
<metrics-aspectj.version>1.1.0</metrics-aspectj.version>
|
||||||
|
|
|
@ -9,4 +9,5 @@ This module contains articles about enterprise concerns such as Multitenancy, Er
|
||||||
- [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions)
|
- [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions)
|
||||||
- [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions)
|
- [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions)
|
||||||
- [Hibernate Error “Not all named parameters have been set”](https://www.baeldung.com/hibernate-error-named-parameters-not-set)
|
- [Hibernate Error “Not all named parameters have been set”](https://www.baeldung.com/hibernate-error-named-parameters-not-set)
|
||||||
- [Various Logging Levels in Hibernate](https://www.baeldung.com/hibernate-logging-levels)
|
- [Various Logging Levels in Hibernate](https://www.baeldung.com/hibernate-logging-levels)
|
||||||
|
- [Hibernate: save, persist, update, merge, saveOrUpdate](https://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate)
|
|
@ -61,13 +61,25 @@
|
||||||
<version>${byte-buddy.version}</version>
|
<version>${byte-buddy.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hsqldb</groupId>
|
||||||
|
<artifactId>hsqldb</artifactId>
|
||||||
|
<version>${hsqldb.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<repositories>
|
<repositories>
|
||||||
<repository>
|
<repository>
|
||||||
<id>geodb-repo</id>
|
<id>osgeo</id>
|
||||||
<name>GeoDB repository</name>
|
<name>OSGeo Release Repository</name>
|
||||||
<url>http://repo.boundlessgeo.com/main/</url>
|
<url>https://repo.osgeo.org/repository/release/</url>
|
||||||
|
<snapshots>
|
||||||
|
<enabled>false</enabled>
|
||||||
|
</snapshots>
|
||||||
|
<releases>
|
||||||
|
<enabled>true</enabled>
|
||||||
|
</releases>
|
||||||
</repository>
|
</repository>
|
||||||
</repositories>
|
</repositories>
|
||||||
|
|
||||||
|
@ -77,6 +89,7 @@
|
||||||
<mariaDB4j.version>2.2.3</mariaDB4j.version>
|
<mariaDB4j.version>2.2.3</mariaDB4j.version>
|
||||||
<assertj-core.version>3.8.0</assertj-core.version>
|
<assertj-core.version>3.8.0</assertj-core.version>
|
||||||
<geodb.version>0.9</geodb.version>
|
<geodb.version>0.9</geodb.version>
|
||||||
|
<hsqldb.version>2.3.4</hsqldb.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -1,6 +1,14 @@
|
||||||
package com.baeldung.persistence.save;
|
package com.baeldung.persistence.save;
|
||||||
|
|
||||||
import com.baeldung.persistence.model.Person;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNotEquals;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
import static org.junit.Assert.assertNotSame;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.junit.Assert.assertSame;
|
||||||
|
|
||||||
|
import javax.persistence.PersistenceException;
|
||||||
|
|
||||||
import org.hibernate.HibernateException;
|
import org.hibernate.HibernateException;
|
||||||
import org.hibernate.Session;
|
import org.hibernate.Session;
|
||||||
import org.hibernate.SessionFactory;
|
import org.hibernate.SessionFactory;
|
||||||
|
@ -8,9 +16,13 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||||
import org.hibernate.cfg.Configuration;
|
import org.hibernate.cfg.Configuration;
|
||||||
import org.hibernate.dialect.HSQLDialect;
|
import org.hibernate.dialect.HSQLDialect;
|
||||||
import org.hibernate.service.ServiceRegistry;
|
import org.hibernate.service.ServiceRegistry;
|
||||||
import org.junit.*;
|
import org.junit.After;
|
||||||
|
import org.junit.AfterClass;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import com.baeldung.persistence.model.Person;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Testing specific implementation details for different methods:
|
* Testing specific implementation details for different methods:
|
||||||
|
@ -21,12 +33,19 @@ public class SaveMethodsIntegrationTest {
|
||||||
private static SessionFactory sessionFactory;
|
private static SessionFactory sessionFactory;
|
||||||
|
|
||||||
private Session session;
|
private Session session;
|
||||||
|
private boolean doNotCommit = false;
|
||||||
|
|
||||||
@BeforeClass
|
@BeforeClass
|
||||||
public static void beforeTests() {
|
public static void beforeTests() {
|
||||||
Configuration configuration = new Configuration().addAnnotatedClass(Person.class).setProperty("hibernate.dialect", HSQLDialect.class.getName()).setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName())
|
Configuration configuration = new Configuration().addAnnotatedClass(Person.class)
|
||||||
.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test").setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "").setProperty("hibernate.hbm2ddl.auto", "update");
|
.setProperty("hibernate.dialect", HSQLDialect.class.getName())
|
||||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
|
.setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName())
|
||||||
|
.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test")
|
||||||
|
.setProperty("hibernate.connection.username", "sa")
|
||||||
|
.setProperty("hibernate.connection.password", "")
|
||||||
|
.setProperty("hibernate.hbm2ddl.auto", "update");
|
||||||
|
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
|
||||||
|
.build();
|
||||||
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
|
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -34,6 +53,7 @@ public class SaveMethodsIntegrationTest {
|
||||||
public void setUp() {
|
public void setUp() {
|
||||||
session = sessionFactory.openSession();
|
session = sessionFactory.openSession();
|
||||||
session.beginTransaction();
|
session.beginTransaction();
|
||||||
|
doNotCommit = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -43,7 +63,8 @@ public class SaveMethodsIntegrationTest {
|
||||||
person.setName("John");
|
person.setName("John");
|
||||||
session.persist(person);
|
session.persist(person);
|
||||||
|
|
||||||
session.getTransaction().commit();
|
session.getTransaction()
|
||||||
|
.commit();
|
||||||
session.close();
|
session.close();
|
||||||
|
|
||||||
session = sessionFactory.openSession();
|
session = sessionFactory.openSession();
|
||||||
|
@ -68,15 +89,33 @@ public class SaveMethodsIntegrationTest {
|
||||||
assertEquals(id1, id2);
|
assertEquals(id1, id2);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test(expected = HibernateException.class)
|
@Test(expected = PersistenceException.class)
|
||||||
public void whenPersistDetached_thenThrowsException() {
|
public void whenPersistDetached_thenThrowsException() {
|
||||||
|
|
||||||
|
doNotCommit = true;
|
||||||
|
|
||||||
Person person = new Person();
|
Person person = new Person();
|
||||||
person.setName("John");
|
person.setName("John");
|
||||||
session.persist(person);
|
session.persist(person);
|
||||||
session.evict(person);
|
session.evict(person);
|
||||||
|
|
||||||
session.persist(person);
|
session.persist(person);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMergeDetached_thenEntityUpdatedFromDatabase() {
|
||||||
|
|
||||||
|
Person person = new Person();
|
||||||
|
person.setName("John");
|
||||||
|
session.save(person);
|
||||||
|
session.flush();
|
||||||
|
session.evict(person);
|
||||||
|
|
||||||
|
person.setName("Mary");
|
||||||
|
Person mergedPerson = (Person) session.merge(person);
|
||||||
|
|
||||||
|
assertNotSame(person, mergedPerson);
|
||||||
|
assertEquals("Mary", mergedPerson.getName());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -92,7 +131,8 @@ public class SaveMethodsIntegrationTest {
|
||||||
|
|
||||||
assertNotNull(id);
|
assertNotNull(id);
|
||||||
|
|
||||||
session.getTransaction().commit();
|
session.getTransaction()
|
||||||
|
.commit();
|
||||||
session.close();
|
session.close();
|
||||||
|
|
||||||
assertEquals(id, person.getId());
|
assertEquals(id, person.getId());
|
||||||
|
@ -128,22 +168,6 @@ public class SaveMethodsIntegrationTest {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenMergeDetached_thenEntityUpdatedFromDatabase() {
|
|
||||||
|
|
||||||
Person person = new Person();
|
|
||||||
person.setName("John");
|
|
||||||
session.save(person);
|
|
||||||
session.evict(person);
|
|
||||||
|
|
||||||
person.setName("Mary");
|
|
||||||
Person mergedPerson = (Person) session.merge(person);
|
|
||||||
|
|
||||||
assertNotSame(person, mergedPerson);
|
|
||||||
assertEquals("Mary", mergedPerson.getName());
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenMergeTransient_thenNewEntitySavedToDatabase() {
|
public void whenMergeTransient_thenNewEntitySavedToDatabase() {
|
||||||
|
|
||||||
|
@ -151,7 +175,8 @@ public class SaveMethodsIntegrationTest {
|
||||||
person.setName("John");
|
person.setName("John");
|
||||||
Person mergedPerson = (Person) session.merge(person);
|
Person mergedPerson = (Person) session.merge(person);
|
||||||
|
|
||||||
session.getTransaction().commit();
|
session.getTransaction()
|
||||||
|
.commit();
|
||||||
session.beginTransaction();
|
session.beginTransaction();
|
||||||
|
|
||||||
assertNull(person.getId());
|
assertNull(person.getId());
|
||||||
|
@ -227,7 +252,8 @@ public class SaveMethodsIntegrationTest {
|
||||||
person.setName("John");
|
person.setName("John");
|
||||||
session.saveOrUpdate(person);
|
session.saveOrUpdate(person);
|
||||||
|
|
||||||
session.getTransaction().commit();
|
session.getTransaction()
|
||||||
|
.commit();
|
||||||
session.close();
|
session.close();
|
||||||
|
|
||||||
session = sessionFactory.openSession();
|
session = sessionFactory.openSession();
|
||||||
|
@ -250,7 +276,10 @@ public class SaveMethodsIntegrationTest {
|
||||||
|
|
||||||
@After
|
@After
|
||||||
public void tearDown() {
|
public void tearDown() {
|
||||||
session.getTransaction().commit();
|
if (!doNotCommit) {
|
||||||
|
session.getTransaction()
|
||||||
|
.commit();
|
||||||
|
}
|
||||||
session.close();
|
session.close();
|
||||||
}
|
}
|
||||||
|
|
|
@ -170,7 +170,6 @@
|
||||||
<guava.version>29.0-jre</guava.version>
|
<guava.version>29.0-jre</guava.version>
|
||||||
<hibernate-types.version>2.9.7</hibernate-types.version>
|
<hibernate-types.version>2.9.7</hibernate-types.version>
|
||||||
<hibernate.version>5.4.14.Final</hibernate.version>
|
<hibernate.version>5.4.14.Final</hibernate.version>
|
||||||
<jackson.version>2.10.3</jackson.version>
|
|
||||||
<javassist.version>3.27.0-GA</javassist.version>
|
<javassist.version>3.27.0-GA</javassist.version>
|
||||||
<jaxb.version>2.3.1</jaxb.version>
|
<jaxb.version>2.3.1</jaxb.version>
|
||||||
<log4jdbc.version>2.0.0</log4jdbc.version>
|
<log4jdbc.version>2.0.0</log4jdbc.version>
|
||||||
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
### Relevant Articles:
|
||||||
|
|
||||||
|
- [Getting Started with jOOQ](https://www.baeldung.com/jooq-intro)
|
|
@ -19,14 +19,14 @@ public class Crud {
|
||||||
|
|
||||||
public static Result<Record> getAll(DSLContext context, Table<? extends Record> table) {
|
public static Result<Record> getAll(DSLContext context, Table<? extends Record> table) {
|
||||||
return context.select()
|
return context.select()
|
||||||
.from(table)
|
.from(table)
|
||||||
.fetch();
|
.fetch();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Result<Record> getFields(DSLContext context, Table<? extends Record> table, SelectFieldOrAsterisk... fields) {
|
public static Result<Record> getFields(DSLContext context, Table<? extends Record> table, SelectFieldOrAsterisk... fields) {
|
||||||
return context.select(fields)
|
return context.select(fields)
|
||||||
.from(table)
|
.from(table)
|
||||||
.fetch();
|
.fetch();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static <R extends Record> R getOne(DSLContext context, Table<R> table, Condition condition) {
|
public static <R extends Record> R getOne(DSLContext context, Table<R> table, Condition condition) {
|
||||||
|
@ -35,9 +35,9 @@ public class Crud {
|
||||||
|
|
||||||
public static <T> void update(DSLContext context, Table<? extends Record> table, Map<Field<T>, T> values, Condition condition) {
|
public static <T> void update(DSLContext context, Table<? extends Record> table, Map<Field<T>, T> values, Condition condition) {
|
||||||
context.update(table)
|
context.update(table)
|
||||||
.set(values)
|
.set(values)
|
||||||
.where(condition)
|
.where(condition)
|
||||||
.execute();
|
.execute();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static <R extends UpdatableRecord<R>> void update(UpdatableRecord<R> record) {
|
public static <R extends UpdatableRecord<R>> void update(UpdatableRecord<R> record) {
|
||||||
|
@ -46,8 +46,8 @@ public class Crud {
|
||||||
|
|
||||||
public static void delete(DSLContext context, Table<? extends Record> table, Condition condition) {
|
public static void delete(DSLContext context, Table<? extends Record> table, Condition condition) {
|
||||||
context.delete(table)
|
context.delete(table)
|
||||||
.where(condition)
|
.where(condition)
|
||||||
.execute();
|
.execute();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static <R extends UpdatableRecord<R>> void delete(UpdatableRecord<R> record) {
|
public static <R extends UpdatableRecord<R>> void delete(UpdatableRecord<R> record) {
|
||||||
|
|
|
@ -60,8 +60,8 @@ public class CrudExamples {
|
||||||
|
|
||||||
private void readValues(DSLContext context) {
|
private void readValues(DSLContext context) {
|
||||||
Result<Record> authors = getAll(
|
Result<Record> authors = getAll(
|
||||||
context,
|
context,
|
||||||
Author.AUTHOR
|
Author.AUTHOR
|
||||||
);
|
);
|
||||||
|
|
||||||
authors.forEach(author -> {
|
authors.forEach(author -> {
|
||||||
|
@ -73,15 +73,15 @@ public class CrudExamples {
|
||||||
});
|
});
|
||||||
|
|
||||||
Result<Record> articles = getFields(
|
Result<Record> articles = getFields(
|
||||||
context,
|
context,
|
||||||
Author.AUTHOR,
|
Author.AUTHOR,
|
||||||
Article.ARTICLE.ID, Article.ARTICLE.TITLE
|
Article.ARTICLE.ID, Article.ARTICLE.TITLE
|
||||||
);
|
);
|
||||||
|
|
||||||
AuthorRecord author = getOne(
|
AuthorRecord author = getOne(
|
||||||
context,
|
context,
|
||||||
Author.AUTHOR,
|
Author.AUTHOR,
|
||||||
Author.AUTHOR.ID.eq(1)
|
Author.AUTHOR.ID.eq(1)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -90,24 +90,22 @@ public class CrudExamples {
|
||||||
fieldsToUpdate.put(Author.AUTHOR.FIRST_NAME, "David");
|
fieldsToUpdate.put(Author.AUTHOR.FIRST_NAME, "David");
|
||||||
fieldsToUpdate.put(Author.AUTHOR.LAST_NAME, "Brown");
|
fieldsToUpdate.put(Author.AUTHOR.LAST_NAME, "Brown");
|
||||||
update(
|
update(
|
||||||
context,
|
context,
|
||||||
Author.AUTHOR,
|
Author.AUTHOR,
|
||||||
fieldsToUpdate,
|
fieldsToUpdate,
|
||||||
Author.AUTHOR.ID.eq(1)
|
Author.AUTHOR.ID.eq(1)
|
||||||
);
|
);
|
||||||
|
|
||||||
ArticleRecord article = context.fetchOne(Article.ARTICLE, Article.ARTICLE.ID.eq(1));
|
ArticleRecord article = context.fetchOne(Article.ARTICLE, Article.ARTICLE.ID.eq(1));
|
||||||
article.setTitle("A New Article Title");
|
article.setTitle("A New Article Title");
|
||||||
update(
|
update(article);
|
||||||
article
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void deleteValues(DSLContext context) {
|
private void deleteValues(DSLContext context) {
|
||||||
delete(
|
delete(
|
||||||
context,
|
context,
|
||||||
Article.ARTICLE,
|
Article.ARTICLE,
|
||||||
Article.ARTICLE.ID.eq(1)
|
Article.ARTICLE.ID.eq(1)
|
||||||
);
|
);
|
||||||
|
|
||||||
AuthorRecord author = context.fetchOne(Author.AUTHOR, Author.AUTHOR.ID.eq(1));
|
AuthorRecord author = context.fetchOne(Author.AUTHOR, Author.AUTHOR.ID.eq(1));
|
||||||
|
|
|
@ -81,8 +81,7 @@
|
||||||
<module>spring-data-redis</module>
|
<module>spring-data-redis</module>
|
||||||
<module>spring-data-solr</module>
|
<module>spring-data-solr</module>
|
||||||
<module>spring-hibernate-3</module>
|
<module>spring-hibernate-3</module>
|
||||||
<module>spring-hibernate-5</module> <!-- long running -->
|
<module>spring-hibernate-5</module> <!-- long running -->
|
||||||
<module>spring-hibernate4</module>
|
|
||||||
<module>spring-jpa</module>
|
<module>spring-jpa</module>
|
||||||
<module>spring-jpa-2</module>
|
<module>spring-jpa-2</module>
|
||||||
<module>spring-jdbc</module>
|
<module>spring-jdbc</module>
|
||||||
|
|
|
@ -0,0 +1,12 @@
|
||||||
|
package com.baeldung.states;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class Application {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(Application.class, args);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,27 @@
|
||||||
|
package com.baeldung.states;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
import javax.persistence.Entity;
|
||||||
|
import javax.persistence.Id;
|
||||||
|
import javax.persistence.ManyToOne;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
public class UserEntity {
|
||||||
|
@Id
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@ManyToOne
|
||||||
|
private UserEntity manager;
|
||||||
|
|
||||||
|
public UserEntity(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
package com.baeldung.states;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
import javax.persistence.CascadeType;
|
||||||
|
import javax.persistence.Entity;
|
||||||
|
import javax.persistence.Id;
|
||||||
|
import javax.persistence.ManyToOne;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
public class UserEntityWithCascade {
|
||||||
|
@Id
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@ManyToOne(cascade = CascadeType.PERSIST)
|
||||||
|
private UserEntityWithCascade manager;
|
||||||
|
|
||||||
|
public UserEntityWithCascade(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,136 @@
|
||||||
|
package com.baeldung.states;
|
||||||
|
|
||||||
|
import org.hibernate.Session;
|
||||||
|
import org.hibernate.SessionFactory;
|
||||||
|
import org.hibernate.Transaction;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
|
import javax.persistence.EntityManagerFactory;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest
|
||||||
|
class UserEntityIntegrationTest {
|
||||||
|
@Autowired
|
||||||
|
private EntityManagerFactory entityManagerFactory;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenName_thenShouldCreateDetachedUserEntity() {
|
||||||
|
// given
|
||||||
|
Session session = openSession();
|
||||||
|
UserEntity userEntity = new UserEntity("John");
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertThat(session.contains(userEntity)).isFalse();
|
||||||
|
session.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenName_whenPersisted_thenShouldCreatePersistentUserEntity() {
|
||||||
|
// given
|
||||||
|
Session session = openSession();
|
||||||
|
UserEntity userEntity = new UserEntity("John");
|
||||||
|
|
||||||
|
// when
|
||||||
|
session.persist(userEntity);
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertThat(session.contains(userEntity)).isTrue();
|
||||||
|
session.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenPersistentEntity_whenSessionClosed_thenShouldDetachEntity() {
|
||||||
|
// given
|
||||||
|
Session session = openSession();
|
||||||
|
UserEntity userEntity = new UserEntity("John");
|
||||||
|
session.persist(userEntity);
|
||||||
|
assertThat(session.contains(userEntity)).isTrue();
|
||||||
|
|
||||||
|
// when
|
||||||
|
session.close();
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertThat(session.isOpen()).isFalse();
|
||||||
|
assertThatThrownBy(() -> session.contains(userEntity));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenPersistentEntity_whenAddedTransientManager_thenShouldThrowException() {
|
||||||
|
// given
|
||||||
|
Session session = openSession();
|
||||||
|
Transaction transaction = session.beginTransaction();
|
||||||
|
UserEntity userEntity = new UserEntity("John");
|
||||||
|
session.persist(userEntity);
|
||||||
|
UserEntity manager = new UserEntity("Adam");
|
||||||
|
|
||||||
|
// when
|
||||||
|
userEntity.setManager(manager);
|
||||||
|
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertThatThrownBy(() -> {
|
||||||
|
session.saveOrUpdate(userEntity);
|
||||||
|
transaction.commit();
|
||||||
|
});
|
||||||
|
session.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenPersistentEntity_whenAddedPersistentManager_thenShouldSave() {
|
||||||
|
// given
|
||||||
|
Session session = openSession();
|
||||||
|
Transaction transaction = session.beginTransaction();
|
||||||
|
UserEntity userEntity = new UserEntity("John");
|
||||||
|
session.persist(userEntity);
|
||||||
|
UserEntity manager = new UserEntity("Adam");
|
||||||
|
session.persist(manager);
|
||||||
|
|
||||||
|
// when
|
||||||
|
userEntity.setManager(manager);
|
||||||
|
|
||||||
|
|
||||||
|
// then
|
||||||
|
session.saveOrUpdate(userEntity);
|
||||||
|
transaction.commit();
|
||||||
|
session.close();
|
||||||
|
|
||||||
|
Session otherSession = openSession();
|
||||||
|
UserEntity savedUser = otherSession.get(UserEntity.class, "John");
|
||||||
|
assertThat(savedUser.getManager().getName()).isEqualTo("Adam");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenPersistentEntityWithCascade_whenAddedTransientManager_thenShouldSave() {
|
||||||
|
// given
|
||||||
|
Session session = openSession();
|
||||||
|
Transaction transaction = session.beginTransaction();
|
||||||
|
UserEntityWithCascade userEntity = new UserEntityWithCascade("John");
|
||||||
|
session.persist(userEntity);
|
||||||
|
UserEntityWithCascade manager = new UserEntityWithCascade("Adam");
|
||||||
|
|
||||||
|
// when
|
||||||
|
userEntity.setManager(manager);
|
||||||
|
|
||||||
|
|
||||||
|
// then
|
||||||
|
session.saveOrUpdate(userEntity);
|
||||||
|
transaction.commit();
|
||||||
|
session.close();
|
||||||
|
|
||||||
|
Session otherSession = openSession();
|
||||||
|
UserEntityWithCascade savedUser = otherSession.get(UserEntityWithCascade.class, "John");
|
||||||
|
assertThat(savedUser.getManager().getName()).isEqualTo("Adam");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private Session openSession() {
|
||||||
|
return entityManagerFactory.unwrap(SessionFactory.class).openSession();
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,5 +1,7 @@
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
|
|
||||||
- [Access the Same In-Memory H2 Database in Multiple Spring Boot Applications](https://www.baeldung.com/spring-boot-access-h2-database-multiple-apps)
|
- [Access the Same In-Memory H2 Database in Multiple Spring Boot Applications](https://www.baeldung.com/spring-boot-access-h2-database-multiple-apps)
|
||||||
- [Spring Boot With H2 Database](https://www.baeldung.com/spring-boot-h2-database)
|
- [Spring Boot With H2 Database](https://www.baeldung.com/spring-boot-h2-database)
|
||||||
- [Hibernate @NotNull vs @Column(nullable = false)](https://www.baeldung.com/hibernate-notnull-vs-nullable)
|
- [Hibernate @NotNull vs @Column(nullable = false)](https://www.baeldung.com/hibernate-notnull-vs-nullable)
|
||||||
- [Quick Guide to Hibernate enable_lazy_load_no_trans Property](https://www.baeldung.com/hibernate-lazy-loading-workaround)
|
- [Quick Guide to Hibernate enable_lazy_load_no_trans Property](https://www.baeldung.com/hibernate-lazy-loading-workaround)
|
||||||
|
- [Where Does H2’s Embedded Database Store The Data?](https://www.baeldung.com/h2-embedded-db-data-storage)
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue