Merge remote-tracking branch 'baeldung/master' into BAEL-3600

This commit is contained in:
Adrian Maghear 2020-10-04 12:49:45 +02:00
commit fc3fb53bae
256 changed files with 6157 additions and 703 deletions

View File

@ -9,4 +9,5 @@
- [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)
- [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)

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -129,6 +129,11 @@
<artifactId>zookeeper</artifactId>
<version>${zookeeper.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>

File diff suppressed because it is too large Load Diff

View File

@ -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 + "]";
}
}

View File

@ -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);
}
}
}
}

View File

@ -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));
}
}

View File

@ -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();
}
}

View File

@ -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]);
});
}
}

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [How to Remove a Prefix From Strings in Groovy](https://www.baeldung.com/groovy-remove-string-prefix)

View File

@ -13,3 +13,4 @@
- [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)
- [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)

View File

@ -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)
- [Creating Temporary Directories in Java](https://www.baeldung.com/java-temp-directories)
- [Reading a Line at a Given Line Number From a File in Java](https://www.baeldung.com/java-read-line-at-number)
- [Find the Last Modified File in a Directory with Java](https://www.baeldung.com/java-last-modified-file)
- [[<-- Prev]](/core-java-modules/core-java-io-2)

View File

@ -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;
}
}

View File

@ -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);
}
}

View File

@ -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)
- [When are Static Variables Initialized in Java?](https://www.baeldung.com/java-static-variables-initialization)
- [Checking if a Class Exists in Java](https://www.baeldung.com/java-check-class-exists)
- [The Difference Between a.getClass() and A.class in Java](https://www.baeldung.com/java-getclass-vs-class)
- [[<-- Prev]](/core-java-modules/core-java-lang-2)

View File

@ -0,0 +1,5 @@
package com.baeldung.getclassobject;
public class Animal {
protected int numberOfEyes;
}

View File

@ -0,0 +1,4 @@
package com.baeldung.getclassobject;
public class Monkey extends Animal {
}

View File

@ -0,0 +1,4 @@
package com.baeldung.getclassobject;
public abstract class SomeAbstractClass {
}

View File

@ -0,0 +1,4 @@
package com.baeldung.getclassobject;
interface SomeInterface {
}

View File

@ -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
// ...
}

View File

@ -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());
}
}

View File

@ -9,3 +9,4 @@ This module contains articles about methods in Java
- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts)
- [Guide to hashCode() in Java](https://www.baeldung.com/java-hashcode)
- [The Covariant Return Type in Java](https://www.baeldung.com/java-covariant-return-type)
- [Does a Methods Signature Include the Return Type in Java?](https://www.baeldung.com/java-method-signature-return-type)

View File

@ -13,4 +13,5 @@ This module contains articles about networking in Java
- [Download a File from an URL in Java](https://www.baeldung.com/java-download-file)
- [Handling java.net.ConnectException](https://www.baeldung.com/java-net-connectexception)
- [Getting MAC addresses in Java](https://www.baeldung.com/java-mac-address)
- [Sending Emails with Attachments in Java](https://www.baeldung.com/java-send-emails-attachments)
- [[<-- Prev]](/core-java-modules/core-java-networking)

View File

@ -2,3 +2,4 @@
- [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)
- [Checking If a Method is Static Using Reflection in Java](https://www.baeldung.com/java-check-method-is-static)

View File

@ -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();
}

View File

@ -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()));
}
}

View File

@ -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)
- [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)
- [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)

View File

@ -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;
}
}

View File

@ -16,11 +16,6 @@
</parent>
<dependencies>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>${feign.version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
@ -44,21 +39,8 @@
</dependency>
</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>
<feign.version>9.4.0</feign.version>
<spring-boot-maven-plugin.version>1.4.2.RELEASE</spring-boot-maven-plugin.version>
<feign.version>10.11</feign.version>
</properties>
</project>

View File

@ -6,8 +6,6 @@ import com.baeldung.feign.models.BookResource;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.util.List;
import java.util.UUID;
@ -22,7 +20,6 @@ import static org.junit.Assert.assertTrue;
* Consumes https://github.com/Baeldung/spring-hypermedia-api
*/
@Slf4j
@RunWith(JUnit4.class)
public class BookClientLiveTest {
private BookClient bookClient;

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Guide to the Gradle Wrapper](https://www.baeldung.com/gradle-wrapper)

View File

@ -8,5 +8,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
### 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)

View File

@ -4,6 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>httpclient-2</artifactId>
<version>0.1-SNAPSHOT</version>
<name>httpclient-2</name>
<parent>
<groupId>com.baeldung</groupId>
@ -13,6 +14,7 @@
</parent>
<dependencies>
<!-- http client -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
@ -24,6 +26,19 @@
</exclusion>
</exclusions>
</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>
<build>
@ -34,10 +49,24 @@
<filtering>true</filtering>
</resource>
</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>
<properties>
<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>
</project>

View File

@ -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;
}
}

View File

@ -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);
}
}
}

View File

@ -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();
}
}

View File

@ -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());
}
}

View File

@ -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);
}
}

View File

@ -23,6 +23,13 @@
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
<build>

View File

@ -60,8 +60,6 @@ public class CustomDeserializationUnitTest {
String converted = objectMapper.writeValueAsString(now);
// restore an instance of ZonedDateTime from String
ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
System.out.println("serialized: " + now);
System.out.println("restored: " + restored);
assertThat(now, is(not(restored)));
}
@ -70,15 +68,14 @@ public class CustomDeserializationUnitTest {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.findAndRegisterModules();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.enable(SerializationFeature.WRITE_DATES_WITH_ZONE_ID);
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
// construct a new instance of ZonedDateTime
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));
String converted = objectMapper.writeValueAsString(now);
// restore an instance of ZonedDateTime from String
ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
System.out.println("serialized: " + now);
System.out.println("restored: " + restored);
assertThat(now, is(restored));
assertThat(restored, is(now));
}
}

View File

@ -24,7 +24,6 @@ public class CustomSerializationUnitTest {
public final void whenSerializing_thenNoExceptions() throws JsonGenerationException, JsonMappingException, IOException {
final Item myItem = new Item(1, "theItem", new User(2, "theUser"));
final String serialized = new ObjectMapper().writeValueAsString(myItem);
System.out.println(serialized);
}
@Test
@ -38,7 +37,6 @@ public class CustomSerializationUnitTest {
mapper.registerModule(simpleModule);
final String serialized = mapper.writeValueAsString(myItem);
System.out.println(serialized);
}
@Test
@ -46,7 +44,6 @@ public class CustomSerializationUnitTest {
final ItemWithSerializer myItem = new ItemWithSerializer(1, "theItem", new User(2, "theUser"));
final String serialized = new ObjectMapper().writeValueAsString(myItem);
System.out.println(serialized);
}
}

View File

@ -37,7 +37,6 @@ public class IgnoreFieldsWithFilterUnitTest {
assertThat(dtoAsString, not(containsString("intValue")));
assertThat(dtoAsString, containsString("booleanValue"));
assertThat(dtoAsString, containsString("stringValue"));
System.out.println(dtoAsString);
}
@Test
@ -83,7 +82,6 @@ public class IgnoreFieldsWithFilterUnitTest {
assertThat(dtoAsString, not(containsString("intValue")));
assertThat(dtoAsString, containsString("booleanValue"));
assertThat(dtoAsString, containsString("stringValue"));
System.out.println(dtoAsString);
}
}

View File

@ -51,8 +51,6 @@ public class JacksonDynamicIgnoreUnitTest {
assertTrue(result.contains("john"));
assertTrue(result.contains("address"));
assertTrue(result.contains("usa"));
System.out.println("Not Hidden = " + result);
}
@Test
@ -65,8 +63,6 @@ public class JacksonDynamicIgnoreUnitTest {
assertTrue(result.contains("john"));
assertFalse(result.contains("address"));
assertFalse(result.contains("usa"));
System.out.println("Address Hidden = " + result);
}
@Test
@ -76,8 +72,6 @@ public class JacksonDynamicIgnoreUnitTest {
final String result = mapper.writeValueAsString(person);
assertTrue(result.length() == 0);
System.out.println("All Hidden = " + result);
}
@Test
@ -90,7 +84,5 @@ public class JacksonDynamicIgnoreUnitTest {
final Person p3 = new Person("adam", ad3, false);
final String result = mapper.writeValueAsString(Arrays.asList(p1, p2, p3));
System.out.println(result);
}
}

View File

@ -7,4 +7,5 @@ This module contains articles about conversions among Collection types and array
- [Array to String Conversions](https://www.baeldung.com/java-array-to-string)
- [Mapping Lists with ModelMapper](https://www.baeldung.com/java-modelmapper-lists)
- [Converting List to Map With a Custom Supplier](https://www.baeldung.com/list-to-map-supplier)
- [Arrays.asList vs new ArrayList(Arrays.asList())](https://www.baeldung.com/java-arrays-aslist-vs-new-arraylist)
- More articles: [[<-- prev]](../java-collections-conversions)

39
java-native/pom.xml Normal file
View File

@ -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>

View 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);
}

View File

@ -0,0 +1,8 @@
package com.baeldung.jna;
public class Main {
public static void main(String[] args) {
}
}

View File

@ -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;
}
}

View File

@ -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;
}

View File

@ -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);
}
}

View File

@ -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());
}
}
}

View File

@ -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.

View File

@ -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>

View File

@ -53,12 +53,12 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.11.0</version>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.0</version>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.io-informatics.oss</groupId>

View File

@ -13,3 +13,4 @@ This module contains articles about JSON.
- [Get a Value by Key in a JSONArray](https://www.baeldung.com/java-jsonarray-get-value-by-key)
- [Iterating Over an Instance of org.json.JSONObject](https://www.baeldung.com/jsonobject-iteration)
- [Escape JSON String in Java](https://www.baeldung.com/java-json-escaping)
- [Reducing JSON Data Size](https://www.baeldung.com/json-reduce-data-size)

View File

@ -7,22 +7,38 @@ import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.model.RequestResponsePact;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import static org.assertj.core.api.Assertions.assertThat;
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
public PactProviderRuleMk2 mockProvider = new PactProviderRuleMk2("test_provider", "localhost", 8080, this);
public PactProviderRuleMk2 mockProvider = new PactProviderRuleMk2("test_provider", "localhost", getAvailablePort(), this);
@Pact(consumer = "test_consumer")
public RequestResponsePact createPact(PactDslWithProvider builder) {

View File

@ -107,6 +107,12 @@
<artifactId>renjin-script-engine</artifactId>
<version>${renjin.version}</version>
</dependency>
<!-- libphonenumber -->
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>libphonenumber</artifactId>
<version>${libphonenumber.version}</version>
</dependency>
</dependencies>
<repositories>
@ -150,6 +156,7 @@
<renjin.version>RELEASE</renjin.version>
<rcaller.version>3.0</rcaller.version>
<rserve.version>1.8.1</rserve.version>
<libphonenumber.version>8.12.9</libphonenumber.version>
</properties>

View File

@ -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));
}
}

View File

@ -168,7 +168,7 @@
<crdt.version>0.1.0</crdt.version>
<unit-ri.version>1.0.3</unit-ri.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>
<suanshu.version>4.0.0</suanshu.version>
<derive4j.version>1.1.0</derive4j.version>

View File

@ -72,7 +72,7 @@
<okhttp.version>3.14.2</okhttp.version>
<gson.version>2.8.5</gson.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.server.version>9.4.19.v20190610</jetty.server.version>
<rxjava2.version>2.2.11</rxjava2.version>

View File

@ -118,7 +118,7 @@
<properties>
<gson.version>2.8.5</gson.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>
<com.squareup.okhttp3.version>3.14.2</com.squareup.okhttp3.version>
<googleclient.version>1.23.0</googleclient.version>

View File

@ -71,7 +71,7 @@
</build>
<properties>
<org.mapstruct.version>1.4.0.Beta1</org.mapstruct.version>
<org.mapstruct.version>1.3.1.Final</org.mapstruct.version>
<springframework.version>4.3.4.RELEASE</springframework.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>

View File

@ -5,7 +5,8 @@ import com.baeldung.mapstruct.mappingCollections.model.Company;
import org.mapstruct.CollectionMappingStrategy;
import org.mapstruct.Mapper;
@Mapper(collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED)
@Mapper(collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED,
uses = EmployeeMapper.class)
public interface CompanyMapperAdderPreferred {
CompanyDTO map(Company company);

View File

@ -11,6 +11,8 @@ import java.util.Set;
@Mapper
public interface EmployeeMapper {
EmployeeDTO map(Employee employee);
List<EmployeeDTO> map(List<Employee> employees);
Set<EmployeeDTO> map(Set<Employee> employees);

View File

@ -66,12 +66,12 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${fasterxml.jackson.version}</version>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-smile</artifactId>
<version>${fasterxml.jackson.version}</version>
<version>${jackson.version}</version>
</dependency>
<dependency>
@ -93,7 +93,7 @@
<dep.ver.servlet>3.1.0</dep.ver.servlet>
<netflix.servo.ver>0.12.17</netflix.servo.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>
<assertj-core.version>3.11.1</assertj-core.version>
<metrics-aspectj.version>1.1.0</metrics-aspectj.version>

View File

@ -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)
- [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)
- [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)

View File

@ -61,13 +61,25 @@
<version>${byte-buddy.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>geodb-repo</id>
<name>GeoDB repository</name>
<url>http://repo.boundlessgeo.com/main/</url>
<id>osgeo</id>
<name>OSGeo Release Repository</name>
<url>https://repo.osgeo.org/repository/release/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
@ -77,6 +89,7 @@
<mariaDB4j.version>2.2.3</mariaDB4j.version>
<assertj-core.version>3.8.0</assertj-core.version>
<geodb.version>0.9</geodb.version>
<hsqldb.version>2.3.4</hsqldb.version>
</properties>
</project>

View File

@ -1,6 +1,14 @@
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.Session;
import org.hibernate.SessionFactory;
@ -8,9 +16,13 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.HSQLDialect;
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:
@ -21,12 +33,19 @@ public class SaveMethodsIntegrationTest {
private static SessionFactory sessionFactory;
private Session session;
private boolean doNotCommit = false;
@BeforeClass
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())
.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();
Configuration configuration = new Configuration().addAnnotatedClass(Person.class)
.setProperty("hibernate.dialect", HSQLDialect.class.getName())
.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);
}
@ -34,6 +53,7 @@ public class SaveMethodsIntegrationTest {
public void setUp() {
session = sessionFactory.openSession();
session.beginTransaction();
doNotCommit = false;
}
@Test
@ -43,7 +63,8 @@ public class SaveMethodsIntegrationTest {
person.setName("John");
session.persist(person);
session.getTransaction().commit();
session.getTransaction()
.commit();
session.close();
session = sessionFactory.openSession();
@ -68,15 +89,33 @@ public class SaveMethodsIntegrationTest {
assertEquals(id1, id2);
}
@Test(expected = HibernateException.class)
@Test(expected = PersistenceException.class)
public void whenPersistDetached_thenThrowsException() {
doNotCommit = true;
Person person = new Person();
person.setName("John");
session.persist(person);
session.evict(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);
session.getTransaction().commit();
session.getTransaction()
.commit();
session.close();
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
public void whenMergeTransient_thenNewEntitySavedToDatabase() {
@ -151,7 +175,8 @@ public class SaveMethodsIntegrationTest {
person.setName("John");
Person mergedPerson = (Person) session.merge(person);
session.getTransaction().commit();
session.getTransaction()
.commit();
session.beginTransaction();
assertNull(person.getId());
@ -227,7 +252,8 @@ public class SaveMethodsIntegrationTest {
person.setName("John");
session.saveOrUpdate(person);
session.getTransaction().commit();
session.getTransaction()
.commit();
session.close();
session = sessionFactory.openSession();
@ -250,7 +276,10 @@ public class SaveMethodsIntegrationTest {
@After
public void tearDown() {
session.getTransaction().commit();
if (!doNotCommit) {
session.getTransaction()
.commit();
}
session.close();
}

View File

@ -170,7 +170,6 @@
<guava.version>29.0-jre</guava.version>
<hibernate-types.version>2.9.7</hibernate-types.version>
<hibernate.version>5.4.14.Final</hibernate.version>
<jackson.version>2.10.3</jackson.version>
<javassist.version>3.27.0-GA</javassist.version>
<jaxb.version>2.3.1</jaxb.version>
<log4jdbc.version>2.0.0</log4jdbc.version>

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Getting Started with jOOQ](https://www.baeldung.com/jooq-intro)

View File

@ -0,0 +1,46 @@
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jooq</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jooq-examples</name>
<packaging>jar</packaging>
<description>jOOQ Examples</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>persistence-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jooq</artifactId>
<version>3.13.4</version>
</dependency>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jooq-meta</artifactId>
<version>3.13.4</version>
</dependency>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jooq-codegen</artifactId>
<version>3.13.4</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.16</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,57 @@
package com.baeldung.jooq;
import org.jooq.Condition;
import org.jooq.DSLContext;
import org.jooq.Field;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.SelectFieldOrAsterisk;
import org.jooq.Table;
import org.jooq.UpdatableRecord;
import java.util.Map;
public class Crud {
public static <R extends UpdatableRecord<R>> void save(UpdatableRecord<R> record) {
record.store();
}
public static Result<Record> getAll(DSLContext context, Table<? extends Record> table) {
return context.select()
.from(table)
.fetch();
}
public static Result<Record> getFields(DSLContext context, Table<? extends Record> table, SelectFieldOrAsterisk... fields) {
return context.select(fields)
.from(table)
.fetch();
}
public static <R extends Record> R getOne(DSLContext context, Table<R> table, Condition condition) {
return context.fetchOne(table, condition);
}
public static <T> void update(DSLContext context, Table<? extends Record> table, Map<Field<T>, T> values, Condition condition) {
context.update(table)
.set(values)
.where(condition)
.execute();
}
public static <R extends UpdatableRecord<R>> void update(UpdatableRecord<R> record) {
record.update();
}
public static void delete(DSLContext context, Table<? extends Record> table, Condition condition) {
context.delete(table)
.where(condition)
.execute();
}
public static <R extends UpdatableRecord<R>> void delete(UpdatableRecord<R> record) {
record.delete();
}
}

View File

@ -0,0 +1,115 @@
package com.baeldung.jooq;
import com.baeldung.jooq.model.tables.Article;
import com.baeldung.jooq.model.tables.Author;
import com.baeldung.jooq.model.tables.records.ArticleRecord;
import com.baeldung.jooq.model.tables.records.AuthorRecord;
import org.jooq.DSLContext;
import org.jooq.Field;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import static com.baeldung.jooq.Crud.delete;
import static com.baeldung.jooq.Crud.getAll;
import static com.baeldung.jooq.Crud.getFields;
import static com.baeldung.jooq.Crud.getOne;
import static com.baeldung.jooq.Crud.save;
import static com.baeldung.jooq.Crud.update;
public class CrudExamples {
public void crudExamples() throws SQLException {
String userName = "username";
String password = "password";
String url = "jdbc:postgresql://db_url:5432/baeldung_database";
Connection conn = DriverManager.getConnection(url, userName, password);
DSLContext context = DSL.using(conn, SQLDialect.POSTGRES);
createValues(context);
readValues(context);
updateValues(context);
deleteValues(context);
}
private void createValues(DSLContext context) {
ArticleRecord article = context.newRecord(Article.ARTICLE);
article.setId(2);
article.setTitle("jOOQ examples");
article.setDescription("A few examples of jOOQ CRUD operations");
article.setAuthorId(1);
save(article);
AuthorRecord author = context.newRecord(Author.AUTHOR);
author.setId(1);
author.setFirstName("John");
author.setLastName("Smith");
author.setAge(40);
save(author);
}
private void readValues(DSLContext context) {
Result<Record> authors = getAll(
context,
Author.AUTHOR
);
authors.forEach(author -> {
Integer id = author.getValue(Author.AUTHOR.ID);
String firstName = author.getValue(Author.AUTHOR.FIRST_NAME);
String lastName = author.getValue(Author.AUTHOR.LAST_NAME);
Integer age = author.getValue(Author.AUTHOR.AGE);
System.out.printf("Author %s %s has id: %d and age: %d%n", firstName, lastName, id, age);
});
Result<Record> articles = getFields(
context,
Author.AUTHOR,
Article.ARTICLE.ID, Article.ARTICLE.TITLE
);
AuthorRecord author = getOne(
context,
Author.AUTHOR,
Author.AUTHOR.ID.eq(1)
);
}
private void updateValues(DSLContext context) {
HashMap<Field<String>, String> fieldsToUpdate = new HashMap<>();
fieldsToUpdate.put(Author.AUTHOR.FIRST_NAME, "David");
fieldsToUpdate.put(Author.AUTHOR.LAST_NAME, "Brown");
update(
context,
Author.AUTHOR,
fieldsToUpdate,
Author.AUTHOR.ID.eq(1)
);
ArticleRecord article = context.fetchOne(Article.ARTICLE, Article.ARTICLE.ID.eq(1));
article.setTitle("A New Article Title");
update(article);
}
private void deleteValues(DSLContext context) {
delete(
context,
Article.ARTICLE,
Article.ARTICLE.ID.eq(1)
);
AuthorRecord author = context.fetchOne(Author.AUTHOR, Author.AUTHOR.ID.eq(1));
delete(author);
}
}

View File

@ -0,0 +1,44 @@
/*
* This file is generated by jOOQ.
*/
package com.baeldung.jooq.model;
import org.jooq.Schema;
import org.jooq.impl.CatalogImpl;
import java.util.Arrays;
import java.util.List;
/**
* This class is generated by jOOQ.
*/
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class DefaultCatalog extends CatalogImpl {
private static final long serialVersionUID = 1035293962;
/**
* The reference instance of <code>DEFAULT_CATALOG</code>
*/
public static final DefaultCatalog DEFAULT_CATALOG = new DefaultCatalog();
/**
* The schema <code>public</code>.
*/
public final Public PUBLIC = Public.PUBLIC;
/**
* No further instances allowed
*/
private DefaultCatalog() {
super("");
}
@Override
public final List<Schema> getSchemas() {
return Arrays.<Schema>asList(
Public.PUBLIC);
}
}

View File

@ -0,0 +1,48 @@
/*
* This file is generated by jOOQ.
*/
package com.baeldung.jooq.model;
import com.baeldung.jooq.model.tables.Article;
import com.baeldung.jooq.model.tables.Author;
import com.baeldung.jooq.model.tables.records.ArticleRecord;
import com.baeldung.jooq.model.tables.records.AuthorRecord;
import org.jooq.ForeignKey;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.Internal;
/**
* A class modelling foreign key relationships and constraints of tables of
* the <code>public</code> schema.
*/
@SuppressWarnings({"all", "unchecked", "rawtypes"})
public class Keys {
// -------------------------------------------------------------------------
// UNIQUE and PRIMARY KEY definitions
// -------------------------------------------------------------------------
public static final UniqueKey<ArticleRecord> ARTICLE_PKEY = UniqueKeys0.ARTICLE_PKEY;
public static final UniqueKey<AuthorRecord> AUTHOR_PKEY = UniqueKeys0.AUTHOR_PKEY;
// -------------------------------------------------------------------------
// FOREIGN KEY definitions
// -------------------------------------------------------------------------
public static final ForeignKey<ArticleRecord, AuthorRecord> ARTICLE__XXX = ForeignKeys0.ARTICLE__XXX;
// -------------------------------------------------------------------------
// [#1459] distribute members to avoid static initialisers > 64kb
// -------------------------------------------------------------------------
private static class UniqueKeys0 {
public static final UniqueKey<ArticleRecord> ARTICLE_PKEY = Internal.createUniqueKey(Article.ARTICLE, "article_pkey", new TableField[]{Article.ARTICLE.ID}, true);
public static final UniqueKey<AuthorRecord> AUTHOR_PKEY = Internal.createUniqueKey(Author.AUTHOR, "author_pkey", new TableField[]{Author.AUTHOR.ID}, true);
}
private static class ForeignKeys0 {
public static final ForeignKey<ArticleRecord, AuthorRecord> ARTICLE__XXX = Internal.createForeignKey(Keys.AUTHOR_PKEY, Article.ARTICLE, "xxx", new TableField[]{Article.ARTICLE.AUTHOR_ID}, true);
}
}

View File

@ -0,0 +1,59 @@
/*
* This file is generated by jOOQ.
*/
package com.baeldung.jooq.model;
import com.baeldung.jooq.model.tables.Article;
import com.baeldung.jooq.model.tables.Author;
import org.jooq.Catalog;
import org.jooq.Table;
import org.jooq.impl.SchemaImpl;
import java.util.Arrays;
import java.util.List;
/**
* This class is generated by jOOQ.
*/
@SuppressWarnings({"all", "unchecked", "rawtypes"})
public class Public extends SchemaImpl {
private static final long serialVersionUID = -2049410122;
/**
* The reference instance of <code>public</code>
*/
public static final Public PUBLIC = new Public();
/**
* The table <code>public.article</code>.
*/
public final Article ARTICLE = Article.ARTICLE;
/**
* The table <code>public.author</code>.
*/
public final Author AUTHOR = Author.AUTHOR;
/**
* No further instances allowed
*/
private Public() {
super("public", null);
}
@Override
public Catalog getCatalog() {
return DefaultCatalog.DEFAULT_CATALOG;
}
@Override
public final List<Table<?>> getTables() {
return Arrays.<Table<?>>asList(
Article.ARTICLE,
Author.AUTHOR
);
}
}

View File

@ -0,0 +1,25 @@
/*
* This file is generated by jOOQ.
*/
package com.baeldung.jooq.model;
import com.baeldung.jooq.model.tables.Article;
import com.baeldung.jooq.model.tables.Author;
/**
* Convenience access to all tables in public
*/
@SuppressWarnings({"all", "unchecked", "rawtypes"})
public class Tables {
/**
* The table <code>public.article</code>.
*/
public static final Article ARTICLE = Article.ARTICLE;
/**
* The table <code>public.author</code>.
*/
public static final Author AUTHOR = Author.AUTHOR;
}

View File

@ -0,0 +1,159 @@
/*
* This file is generated by jOOQ.
*/
package com.baeldung.jooq.model.tables;
import com.baeldung.jooq.model.Keys;
import com.baeldung.jooq.model.Public;
import com.baeldung.jooq.model.tables.records.ArticleRecord;
import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Name;
import org.jooq.Record;
import org.jooq.Row4;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.TableOptions;
import org.jooq.UniqueKey;
import org.jooq.impl.DSL;
import org.jooq.impl.TableImpl;
import java.util.Arrays;
import java.util.List;
/**
* This class is generated by jOOQ.
*/
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Article extends TableImpl<ArticleRecord> {
private static final long serialVersionUID = -1401275800;
/**
* The reference instance of <code>public.article</code>
*/
public static final Article ARTICLE = new Article();
/**
* The class holding records for this type
*/
@Override
public Class<ArticleRecord> getRecordType() {
return ArticleRecord.class;
}
/**
* The column <code>public.article.id</code>.
*/
public final TableField<ArticleRecord, Integer> ID = createField(DSL.name("id"), org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>public.article.title</code>.
*/
public final TableField<ArticleRecord, String> TITLE = createField(DSL.name("title"), org.jooq.impl.SQLDataType.VARCHAR(255).nullable(false), this, "");
/**
* The column <code>public.article.description</code>.
*/
public final TableField<ArticleRecord, String> DESCRIPTION = createField(DSL.name("description"), org.jooq.impl.SQLDataType.VARCHAR(255), this, "");
/**
* The column <code>public.article.author_id</code>.
*/
public final TableField<ArticleRecord, Integer> AUTHOR_ID = createField(DSL.name("author_id"), org.jooq.impl.SQLDataType.INTEGER, this, "");
/**
* Create a <code>public.article</code> table reference
*/
public Article() {
this(DSL.name("article"), null);
}
/**
* Create an aliased <code>public.article</code> table reference
*/
public Article(String alias) {
this(DSL.name(alias), ARTICLE);
}
/**
* Create an aliased <code>public.article</code> table reference
*/
public Article(Name alias) {
this(alias, ARTICLE);
}
private Article(Name alias, Table<ArticleRecord> aliased) {
this(alias, aliased, null);
}
private Article(Name alias, Table<ArticleRecord> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, DSL.comment(""), TableOptions.table());
}
public <O extends Record> Article(Table<O> child, ForeignKey<O, ArticleRecord> key) {
super(child, key, ARTICLE);
}
@Override
public Schema getSchema() {
return Public.PUBLIC;
}
@Override
public UniqueKey<ArticleRecord> getPrimaryKey() {
return Keys.ARTICLE_PKEY;
}
@Override
public List<UniqueKey<ArticleRecord>> getKeys() {
return Arrays.<UniqueKey<ArticleRecord>>asList(Keys.ARTICLE_PKEY);
}
@Override
public List<ForeignKey<ArticleRecord, ?>> getReferences() {
return Arrays.<ForeignKey<ArticleRecord, ?>>asList(Keys.ARTICLE__XXX);
}
public Author author() {
return new Author(this, Keys.ARTICLE__XXX);
}
@Override
public Article as(String alias) {
return new Article(DSL.name(alias), this);
}
@Override
public Article as(Name alias) {
return new Article(alias, this);
}
/**
* Rename this table
*/
@Override
public Article rename(String name) {
return new Article(DSL.name(name), null);
}
/**
* Rename this table
*/
@Override
public Article rename(Name name) {
return new Article(name, null);
}
// -------------------------------------------------------------------------
// Row4 type methods
// -------------------------------------------------------------------------
@Override
public Row4<Integer, String, String, Integer> fieldsRow() {
return (Row4) super.fieldsRow();
}
}

View File

@ -0,0 +1,149 @@
/*
* This file is generated by jOOQ.
*/
package com.baeldung.jooq.model.tables;
import com.baeldung.jooq.model.Keys;
import com.baeldung.jooq.model.Public;
import com.baeldung.jooq.model.tables.records.AuthorRecord;
import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Name;
import org.jooq.Record;
import org.jooq.Row4;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.TableOptions;
import org.jooq.UniqueKey;
import org.jooq.impl.DSL;
import org.jooq.impl.TableImpl;
import java.util.Arrays;
import java.util.List;
/**
* This class is generated by jOOQ.
*/
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Author extends TableImpl<AuthorRecord> {
private static final long serialVersionUID = -798376522;
/**
* The reference instance of <code>public.author</code>
*/
public static final Author AUTHOR = new Author();
/**
* The class holding records for this type
*/
@Override
public Class<AuthorRecord> getRecordType() {
return AuthorRecord.class;
}
/**
* The column <code>public.author.id</code>.
*/
public final TableField<AuthorRecord, Integer> ID = createField(DSL.name("id"), org.jooq.impl.SQLDataType.INTEGER.nullable(false), AUTHOR, "");
/**
* The column <code>public.author.first_name</code>.
*/
public final TableField<AuthorRecord, String> FIRST_NAME = createField(DSL.name("first_name"), org.jooq.impl.SQLDataType.VARCHAR(255), this, "");
/**
* The column <code>public.author.last_name</code>.
*/
public final TableField<AuthorRecord, String> LAST_NAME = createField(DSL.name("last_name"), org.jooq.impl.SQLDataType.VARCHAR(255), this, "");
/**
* The column <code>public.author.age</code>.
*/
public final TableField<AuthorRecord, Integer> AGE = createField(DSL.name("age"), org.jooq.impl.SQLDataType.INTEGER, this, "");
/**
* Create a <code>public.author</code> table reference
*/
public Author() {
this(DSL.name("author"), null);
}
/**
* Create an aliased <code>public.author</code> table reference
*/
public Author(String alias) {
this(DSL.name(alias), AUTHOR);
}
/**
* Create an aliased <code>public.author</code> table reference
*/
public Author(Name alias) {
this(alias, AUTHOR);
}
private Author(Name alias, Table<AuthorRecord> aliased) {
this(alias, aliased, null);
}
private Author(Name alias, Table<AuthorRecord> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, DSL.comment(""), TableOptions.table());
}
public <O extends Record> Author(Table<O> child, ForeignKey<O, AuthorRecord> key) {
super(child, key, AUTHOR);
}
@Override
public Schema getSchema() {
return Public.PUBLIC;
}
@Override
public UniqueKey<AuthorRecord> getPrimaryKey() {
return Keys.AUTHOR_PKEY;
}
@Override
public List<UniqueKey<AuthorRecord>> getKeys() {
return Arrays.<UniqueKey<AuthorRecord>>asList(Keys.AUTHOR_PKEY);
}
@Override
public Author as(String alias) {
return new Author(DSL.name(alias), this);
}
@Override
public Author as(Name alias) {
return new Author(alias, this);
}
/**
* Rename this table
*/
@Override
public Author rename(String name) {
return new Author(DSL.name(name), null);
}
/**
* Rename this table
*/
@Override
public Author rename(Name name) {
return new Author(name, null);
}
// -------------------------------------------------------------------------
// Row4 type methods
// -------------------------------------------------------------------------
@Override
public Row4<Integer, String, String, Integer> fieldsRow() {
return (Row4) super.fieldsRow();
}
}

Some files were not shown because too many files have changed in this diff Show More