Merge branch 'eugenp:master' into master
This commit is contained in:
commit
5c299c2e54
|
@ -1,7 +1,7 @@
|
|||
<?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">
|
||||
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>apache-poi-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
@ -25,5 +25,4 @@
|
|||
<poi.version>5.2.0</poi.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
</project>
|
|
@ -9,3 +9,4 @@ This module contains articles about Apache Spark
|
|||
- [Machine Learning with Spark MLlib](https://www.baeldung.com/spark-mlib-machine-learning)
|
||||
- [Introduction to Spark Graph Processing with GraphFrames](https://www.baeldung.com/spark-graph-graphframes)
|
||||
- [Apache Spark: Differences between Dataframes, Datasets and RDDs](https://www.baeldung.com/java-spark-dataframe-dataset-rdd)
|
||||
- [Spark DataFrame](https://www.baeldung.com/spark-dataframes)
|
||||
|
|
|
@ -12,21 +12,29 @@ import org.junit.AfterClass;
|
|||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import scala.Tuple2;
|
||||
|
||||
public class ActionsUnitTest {
|
||||
|
||||
public static final Logger LOG = LoggerFactory.getLogger(ActionsUnitTest.class);
|
||||
|
||||
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[*]");
|
||||
SparkConf conf = new SparkConf()
|
||||
.setAppName("reduce")
|
||||
.setMaster("local[*]")
|
||||
.set("spark.driver.allowMultipleContexts", "true");
|
||||
|
||||
sc = new JavaSparkContext(conf);
|
||||
tourists = sc.textFile("data/Tourist.csv").filter(line -> !line.startsWith("Region"));
|
||||
}
|
||||
|
||||
|
||||
@AfterClass
|
||||
public static void cleanup() {
|
||||
sc.close();
|
||||
|
@ -40,11 +48,11 @@ public class ActionsUnitTest {
|
|||
})
|
||||
.distinct();
|
||||
Long numberOfCountries = countries.count();
|
||||
System.out.println("Count: " + numberOfCountries);
|
||||
|
||||
LOG.debug("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"));
|
||||
|
@ -53,10 +61,12 @@ public class ActionsUnitTest {
|
|||
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);
|
||||
|
||||
List<Tuple2<String, Double>> totalByCountry = expenditurePairRdd
|
||||
.reduceByKey(Double::sum)
|
||||
.collect();
|
||||
|
||||
LOG.debug("Total per Country: {}", totalByCountry);
|
||||
|
||||
for(Tuple2<String, Double> tuple : totalByCountry) {
|
||||
if (tuple._1.equals("Mexico")) {
|
||||
assertEquals(Double.valueOf(99164), tuple._2);
|
||||
|
|
|
@ -39,8 +39,10 @@ public class DataFrameUnitTest {
|
|||
@Test
|
||||
public void whenSelectSpecificColumns_thenColumnsFiltered() {
|
||||
Dataset<Row> selectedData = data.select(col("country"), col("year"), col("value"));
|
||||
selectedData.show();
|
||||
|
||||
|
||||
// uncomment to see table
|
||||
// selectedData.show();
|
||||
|
||||
List<String> resultList = Arrays.asList(selectedData.columns());
|
||||
assertTrue(resultList.contains("country"));
|
||||
assertTrue(resultList.contains("year"));
|
||||
|
@ -52,22 +54,26 @@ public class DataFrameUnitTest {
|
|||
@Test
|
||||
public void whenFilteringByCountry_thenCountryRecordsSelected() {
|
||||
Dataset<Row> filteredData = data.filter(col("country").equalTo("Mexico"));
|
||||
filteredData.show();
|
||||
|
||||
|
||||
// uncomment to see table
|
||||
// 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();
|
||||
|
||||
|
||||
// uncomment to see table
|
||||
// recordsPerCountry.show();
|
||||
|
||||
Dataset<Row> filteredData = recordsPerCountry.filter(col("country").equalTo("Sweden"));
|
||||
assertEquals(new Long(12), filteredData.first()
|
||||
assertEquals(12L, filteredData.first()
|
||||
.get(1));
|
||||
}
|
||||
|
||||
|
|
|
@ -3,6 +3,7 @@ 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 static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.apache.spark.api.java.function.FilterFunction;
|
||||
import org.apache.spark.sql.DataFrameReader;
|
||||
|
@ -29,8 +30,8 @@ public class DatasetUnitTest {
|
|||
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"),
|
||||
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));
|
||||
}
|
||||
|
@ -45,7 +46,9 @@ public class DatasetUnitTest {
|
|||
Dataset<TouristData> selectedData = typedDataset
|
||||
.filter((FilterFunction<TouristData>) record -> record.getCountry()
|
||||
.equals("Norway"));
|
||||
selectedData.show();
|
||||
|
||||
// uncomment to see output
|
||||
// selectedData.show();
|
||||
|
||||
selectedData.foreach(record -> {
|
||||
assertEquals("Norway", record.getCountry());
|
||||
|
@ -56,28 +59,41 @@ public class DatasetUnitTest {
|
|||
public void whenGroupCountByCountry_thenContryTotalRecords() {
|
||||
Dataset<Row> countriesCount = typedDataset.groupBy(typedDataset.col("country"))
|
||||
.count();
|
||||
countriesCount.show();
|
||||
|
||||
assertEquals(Long.valueOf(220), Long.valueOf(countriesCount.count()));
|
||||
// uncomment to see output
|
||||
// countriesCount.show();
|
||||
|
||||
assertEquals(220, 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();
|
||||
Dataset<TouristData> filteredData = typedDataset.filter(
|
||||
(FilterFunction<TouristData>) record -> record.getYear() != null
|
||||
&& (Long.parseLong(record.getYear()) > 2010 && Long.parseLong(record.getYear()) < 2017));
|
||||
|
||||
// uncomment to see output
|
||||
// filteredData.show();
|
||||
|
||||
assertEquals(394, filteredData.count());
|
||||
filteredData.foreach(record -> {
|
||||
assertTrue(Integer.parseInt(record.getYear()) > 2010 && Integer.parseInt(record.getYear()) < 2017);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@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();
|
||||
Dataset<Row> filteredData = typedDataset.filter((FilterFunction<TouristData>) record -> record.getValue() != null
|
||||
&& record.getSeries().contains("expenditure"))
|
||||
.groupBy("country")
|
||||
.agg(sum("value"));
|
||||
|
||||
// uncomment to see output
|
||||
// filteredData.show();
|
||||
|
||||
assertEquals(212, filteredData.count());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -23,8 +23,11 @@ public class TransformationsUnitTest {
|
|||
|
||||
@BeforeClass
|
||||
public static void init() {
|
||||
SparkConf conf = new SparkConf().setAppName("uppercaseCountries")
|
||||
.setMaster("local[*]");
|
||||
SparkConf conf = new SparkConf()
|
||||
.setAppName("uppercaseCountries")
|
||||
.setMaster("local[*]")
|
||||
.set("spark.driver.allowMultipleContexts", "true");
|
||||
|
||||
sc = new JavaSparkContext(conf);
|
||||
tourists = sc.textFile("data/Tourist.csv")
|
||||
.filter(line -> !line.startsWith("Region")); //filter header row
|
||||
|
|
|
@ -78,6 +78,25 @@
|
|||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<version>${maven-plugins-version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy</id>
|
||||
<phase>compile</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<includeScope></includeScope>
|
||||
<includeTypes>so,dll,dylib</includeTypes>
|
||||
<outputDirectory>native-libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
@ -99,6 +118,7 @@
|
|||
<commons-codec-version>1.10.L001</commons-codec-version>
|
||||
<jets3t-version>0.9.4.0006L</jets3t-version>
|
||||
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
|
||||
<maven-plugins-version>3.1.1</maven-plugins-version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -20,7 +20,6 @@
|
|||
<artifactId>aws-java-sdk</artifactId>
|
||||
<version>${aws-java-sdk.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
|
@ -58,7 +57,7 @@
|
|||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<aws-java-sdk.version>1.11.290</aws-java-sdk.version>
|
||||
|
|
|
@ -19,6 +19,6 @@
|
|||
<module>aws-miscellaneous</module>
|
||||
<module>aws-reactive</module>
|
||||
<module>aws-s3</module>
|
||||
</modules>
|
||||
</modules>
|
||||
|
||||
</project>
|
|
@ -12,3 +12,4 @@ This module contains articles about Java 11 core features
|
|||
- [Java HTTPS Client Certificate Authentication](https://www.baeldung.com/java-https-client-certificate-authentication)
|
||||
- [Call Methods at Runtime Using Java Reflection](https://www.baeldung.com/java-method-reflection)
|
||||
- [Java HttpClient Basic Authentication](https://www.baeldung.com/java-httpclient-basic-auth)
|
||||
- [Java HttpClient With SSL](https://www.baeldung.com/java-httpclient-ssl)
|
||||
|
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.httpclient.ssl;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Properties;
|
||||
|
||||
public class HttpClientSSLBypassUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenHttpsRequest_thenCorrect() throws IOException, InterruptedException {
|
||||
final Properties props = System.getProperties();
|
||||
props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.TRUE.toString());
|
||||
|
||||
HttpClient httpClient = HttpClient.newBuilder()
|
||||
.build();
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("https://www.testingmcafeesites.com/"))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.FALSE.toString());
|
||||
|
||||
Assertions.assertEquals(200, response.statusCode());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.httpclient.ssl;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.net.ssl.SSLHandshakeException;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class HttpClientSSLUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenValidHttpsRequest_thenCorrect() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpClient httpClient = HttpClient.newHttpClient();
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://www.google.com/"))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertEquals(200, response.statusCode());
|
||||
}
|
||||
|
||||
@Test(expected = SSLHandshakeException.class)
|
||||
public void whenInvalidHttpsRequest_thenInCorrect() throws IOException, InterruptedException {
|
||||
HttpClient httpClient = HttpClient.newHttpClient();
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("https://expired.badssl.com/"))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertEquals(200, response.statusCode());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.java9.delimiters;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class DelimiterDemo {
|
||||
|
||||
public static List<String> scannerWithDelimiter(String input, String delimiter) {
|
||||
try (Scanner scan = new Scanner(input)) {
|
||||
scan.useDelimiter(delimiter);
|
||||
List<String> result = new ArrayList<String>();
|
||||
scan.forEachRemaining(result::add);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public static List<String> scannerWithDelimiterUsingPattern(String input, Pattern delimiter) {
|
||||
try (Scanner scan = new Scanner(input)) {
|
||||
scan.useDelimiter(delimiter);
|
||||
List<String> result = new ArrayList<String>();
|
||||
scan.forEachRemaining(result::add);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public static List<String> baseScanner(String input) {
|
||||
try (Scanner scan = new Scanner(input)) {
|
||||
List<String> result = new ArrayList<String>();
|
||||
scan.forEachRemaining(result::add);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
package com.baeldung.java9.delimiters;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class DelimiterDemoUnitTest {
|
||||
|
||||
@Test
|
||||
void givenSimpleCharacterDelimiter_whenScannerWithDelimiter_ThenInputIsCorrectlyParsed() {
|
||||
checkOutput(DelimiterDemo::scannerWithDelimiter, "Welcome to Baeldung", "\\s", Arrays.asList("Welcome", "to", "Baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringDelimiter_whenScannerWithDelimiter_ThenInputIsCorrectlyParsed() {
|
||||
checkOutput(DelimiterDemo::scannerWithDelimiter, "HelloBaeldungHelloWorld", "Hello", Arrays.asList("Baeldung", "World"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenVariousPossibleDelimiters_whenScannerWithDelimiter_ThenInputIsCorrectlyParsed() {
|
||||
checkOutput(DelimiterDemo::scannerWithDelimiter, "Welcome to Baeldung.\nThank you for reading.\nThe team", "\n|\\s", Arrays.asList("Welcome", "to", "Baeldung.", "Thank", "you", "for", "reading.", "The", "team"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenWildcardRegexDelimiter_whenScannerWithDelimiter_ThenInputIsCorrectlyParsed() {
|
||||
checkOutput(DelimiterDemo::scannerWithDelimiter, "1aaaaaaa2aa3aaa4", "a+", Arrays.asList("1", "2", "3", "4"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSimpleCharacterDelimiter_whenScannerWithDelimiterUsingPattern_ThenInputIsCorrectlyParsed() {
|
||||
checkOutput(DelimiterDemo::scannerWithDelimiterUsingPattern, "Welcome to Baeldung", Pattern.compile("\\s"), Arrays.asList("Welcome", "to", "Baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringDelimiter_whenScannerWithDelimiterUsingPattern_ThenInputIsCorrectlyParsed() {
|
||||
checkOutput(DelimiterDemo::scannerWithDelimiterUsingPattern, "HelloBaeldungHelloWorld", Pattern.compile("Hello"), Arrays.asList("Baeldung", "World"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenVariousPossibleDelimiters_whenScannerWithDelimiterUsingPattern_ThenInputIsCorrectlyParsed() {
|
||||
checkOutput(DelimiterDemo::scannerWithDelimiterUsingPattern, "Welcome to Baeldung.\nThank you for reading.\nThe team", Pattern.compile("\n|\\s"), Arrays.asList("Welcome", "to", "Baeldung.", "Thank", "you", "for", "reading.", "The", "team"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenWildcardRegexDelimiters_whenScannerWithDelimiterUsingPattern_ThenInputIsCorrectlyParsed() {
|
||||
checkOutput(DelimiterDemo::scannerWithDelimiterUsingPattern, "1aaaaaaa2aa3aaa4", Pattern.compile("a*"), Arrays.asList("1", "2", "3", "4"));
|
||||
}
|
||||
|
||||
void checkOutput(BiFunction<String, String, List<String>> function, String input, String delimiter, List<String> expectedOutput) {
|
||||
assertEquals(expectedOutput, function.apply(input, delimiter));
|
||||
}
|
||||
|
||||
void checkOutput(BiFunction<String, Pattern, List<String>> function, String input, Pattern delimiter, List<String> expectedOutput) {
|
||||
assertEquals(expectedOutput, function.apply(input, delimiter));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenBaseScanner_ThenWhitespacesAreUsedAsDelimiters() {
|
||||
assertEquals(List.of("Welcome", "at", "Baeldung"), DelimiterDemo.baseScanner("Welcome at Baeldung"));
|
||||
}
|
||||
|
||||
}
|
|
@ -12,3 +12,4 @@
|
|||
- [Sorting in Java](https://www.baeldung.com/java-sorting)
|
||||
- [Getting the Size of an Iterable in Java](https://www.baeldung.com/java-iterable-size)
|
||||
- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections)
|
||||
- [Differences Between Iterator and Iterable and How to Use Them?](https://www.baeldung.com/java-iterator-vs-iterable)
|
||||
|
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.collections.iterable;
|
||||
|
||||
class CustomIterableClient {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
ShoppingCart<Product> shoppingCart = new ShoppingCart<>();
|
||||
shoppingCart.add(new Product("Tuna", 42));
|
||||
shoppingCart.add(new Product("Eggplant", 65));
|
||||
shoppingCart.add(new Product("Salad", 45));
|
||||
shoppingCart.add(new Product("Banana", 29));
|
||||
|
||||
for (Product product : shoppingCart) {
|
||||
System.out.println(product.getName());
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.collections.iterable;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
public class IterableExample {
|
||||
|
||||
public void iterateUsingIterator(List<Integer> numbers) {
|
||||
Iterator<Integer> iterator = numbers.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
System.out.println(iterator.next());
|
||||
}
|
||||
}
|
||||
|
||||
public void iterateUsingEnhancedForLoop(List<Integer> numbers) {
|
||||
for (Integer number : numbers) {
|
||||
System.out.println(number);
|
||||
}
|
||||
}
|
||||
|
||||
public void iterateUsingForEachLoop(List<Integer> numbers) {
|
||||
numbers.forEach(System.out::println);
|
||||
}
|
||||
|
||||
public void removeElementsUsingIterator(List<Integer> numbers) {
|
||||
Iterator<Integer> iterator = numbers.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
iterator.next();
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.collections.iterable;
|
||||
|
||||
class Product {
|
||||
|
||||
private String name;
|
||||
private double price;
|
||||
|
||||
public Product(String code, double price) {
|
||||
this.name = code;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public double getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(double price) {
|
||||
this.price = price;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,72 @@
|
|||
package com.baeldung.collections.iterable;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.ConcurrentModificationException;
|
||||
import java.util.Iterator;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
public class ShoppingCart<E> implements Iterable<E> {
|
||||
|
||||
private E[] elementData;
|
||||
private int size;
|
||||
|
||||
public ShoppingCart() {
|
||||
this.elementData = (E[]) new Object[]{};
|
||||
}
|
||||
|
||||
public void add(E element) {
|
||||
ensureCapacity(size + 1);
|
||||
elementData[size++] = element;
|
||||
}
|
||||
|
||||
private void ensureCapacity(int minCapacity) {
|
||||
int oldCapacity = elementData.length;
|
||||
int newCapacity = oldCapacity + (oldCapacity >> 1);
|
||||
if (newCapacity - minCapacity < 0) {
|
||||
newCapacity = minCapacity;
|
||||
}
|
||||
elementData = Arrays.copyOf(elementData, newCapacity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<E> iterator() {
|
||||
return new ShoppingCartIterator();
|
||||
}
|
||||
|
||||
public class ShoppingCartIterator implements Iterator<E> {
|
||||
int cursor;
|
||||
int lastReturned = -1;
|
||||
|
||||
public boolean hasNext() {
|
||||
return cursor != size;
|
||||
}
|
||||
|
||||
public E next() {
|
||||
return getNextElement();
|
||||
}
|
||||
|
||||
private E getNextElement() {
|
||||
int current = cursor;
|
||||
exist(current);
|
||||
|
||||
E[] elements = ShoppingCart.this.elementData;
|
||||
validate(elements, current);
|
||||
|
||||
cursor = current + 1;
|
||||
lastReturned = current;
|
||||
return elements[lastReturned];
|
||||
}
|
||||
|
||||
private void exist(int current) {
|
||||
if (current >= size) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
}
|
||||
|
||||
private void validate(E[] elements, int current) {
|
||||
if (current >= elements.length) {
|
||||
throw new ConcurrentModificationException();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.collections.iterator;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
class CustomIteratorClient {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Iterator<Integer> iterator = Numbers.iterator();
|
||||
|
||||
while (iterator.hasNext()) {
|
||||
System.out.println(iterator.next());
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
package com.baeldung.collections.iterator;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
class Numbers {
|
||||
|
||||
private static final List<Integer> NUMBER_LIST = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||
|
||||
private Numbers() {
|
||||
}
|
||||
|
||||
public static Iterator<Integer> iterator() {
|
||||
return new PrimeIterator();
|
||||
}
|
||||
|
||||
private static class PrimeIterator implements Iterator<Integer> {
|
||||
|
||||
private int cursor;
|
||||
|
||||
@Override
|
||||
public Integer next() {
|
||||
exist(cursor);
|
||||
return NUMBER_LIST.get(cursor++);
|
||||
}
|
||||
|
||||
private void exist(int current) {
|
||||
if (current >= NUMBER_LIST.size()) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
if (cursor > NUMBER_LIST.size()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = cursor; i < NUMBER_LIST.size(); i++) {
|
||||
if (isPrime(NUMBER_LIST.get(i))) {
|
||||
cursor = i;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean isPrime(int number) {
|
||||
for (int i = 2; i <= number / 2; ++i) {
|
||||
if (number % i == 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
package com.baeldung.collections.iterable;
|
||||
|
||||
import com.baeldung.collections.iterable.IterableExample;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class IterableUnitTest {
|
||||
|
||||
private static List<Integer> getNumbers() {
|
||||
List<Integer> numbers = new ArrayList<>();
|
||||
numbers.add(10);
|
||||
numbers.add(20);
|
||||
numbers.add(30);
|
||||
numbers.add(40);
|
||||
return numbers;
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNumbers_whenUsingIterator_thenCorrectSize() {
|
||||
List<Integer> numbers = getNumbers();
|
||||
IterableExample iterableExample = new IterableExample();
|
||||
iterableExample.iterateUsingIterator(numbers);
|
||||
assertEquals(4, numbers.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNumbers_whenRemoveElements_thenEmptyList() {
|
||||
List<Integer> numbers = getNumbers();
|
||||
IterableExample iterableExample = new IterableExample();
|
||||
iterableExample.removeElementsUsingIterator(numbers);
|
||||
assertEquals(0, numbers.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNumbers_whenIterateUsingEnhancedForLoop_thenCorrectSize() {
|
||||
List<Integer> numbers = getNumbers();
|
||||
IterableExample iterableExample = new IterableExample();
|
||||
iterableExample.iterateUsingEnhancedForLoop(numbers);
|
||||
assertEquals(4, numbers.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNumbers_whenIterateUsingForEachLoop_thenCorrectSize() {
|
||||
List<Integer> numbers = getNumbers();
|
||||
IterableExample iterableExample = new IterableExample();
|
||||
iterableExample.iterateUsingForEachLoop(numbers);
|
||||
assertEquals(4, numbers.size());
|
||||
}
|
||||
}
|
|
@ -14,4 +14,16 @@
|
|||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>commons-lang</groupId>
|
||||
<artifactId>commons-lang</artifactId>
|
||||
<version>${commons-lang.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<commons-lang.version>2.2</commons-lang.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,72 @@
|
|||
package com.baeldung.collections.sorting;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class Employee implements Comparable<Employee>{
|
||||
|
||||
private String name;
|
||||
private int age;
|
||||
private double salary;
|
||||
private Date joiningDate;
|
||||
|
||||
public Employee(String name, int age, double salary, Date joiningDate) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
this.salary = salary;
|
||||
this.joiningDate = joiningDate;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public double getSalary() {
|
||||
return salary;
|
||||
}
|
||||
|
||||
public void setSalary(double salary) {
|
||||
this.salary = salary;
|
||||
}
|
||||
|
||||
public Date getJoiningDate() {
|
||||
return joiningDate;
|
||||
}
|
||||
|
||||
public void setJoiningDate(Date joiningDate) {
|
||||
this.joiningDate = joiningDate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return ((Employee) obj).getName()
|
||||
.equals(getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new StringBuffer().append("(")
|
||||
.append(getName()).append(",")
|
||||
.append(getAge())
|
||||
.append(",")
|
||||
.append(getSalary()).append(",").append(getJoiningDate())
|
||||
.append(")")
|
||||
.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(Employee employee) {
|
||||
return getJoiningDate().compareTo(employee.getJoiningDate());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,146 @@
|
|||
package com.baeldung.collections.sorting;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import org.apache.commons.lang.time.DateUtils;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class EmployeeSortingByDateUnitTest {
|
||||
|
||||
private List<Employee> employees = new ArrayList<>();
|
||||
private List<Employee> employeesSortedByDateAsc = new ArrayList<>();
|
||||
private List<Employee> employeesSortedByDateDesc = new ArrayList<>();
|
||||
|
||||
@Before
|
||||
public void initVariables() {
|
||||
|
||||
Collections.addAll(employees,
|
||||
new Employee("Earl", 43, 10000, DateUtils.addMonths(new Date(), -2)),
|
||||
new Employee("Frank", 33, 7000, DateUtils.addDays(new Date(), -20)),
|
||||
new Employee("Steve", 26, 6000, DateUtils.addDays(new Date(), -10)),
|
||||
new Employee("Jessica", 23, 4000, DateUtils.addMonths(new Date(), -6)),
|
||||
new Employee("Pearl", 33, 6000, DateUtils.addYears(new Date(), -1)),
|
||||
new Employee("John", 23, 5000, new Date())
|
||||
);
|
||||
|
||||
Collections.addAll(employeesSortedByDateDesc,
|
||||
new Employee("John", 23, 5000, new Date()),
|
||||
new Employee("Steve", 26, 6000, DateUtils.addDays(new Date(), -10)),
|
||||
new Employee("Frank", 33, 7000, DateUtils.addDays(new Date(), -20)),
|
||||
new Employee("Earl", 43, 10000, DateUtils.addMonths(new Date(), -2)),
|
||||
new Employee("Jessica", 23, 4000, DateUtils.addMonths(new Date(), -6)),
|
||||
new Employee("Pearl", 33, 6000, DateUtils.addYears(new Date(), -1))
|
||||
);
|
||||
|
||||
Collections.addAll(employeesSortedByDateAsc,
|
||||
new Employee("Pearl", 33, 6000, DateUtils.addYears(new Date(), -1)),
|
||||
new Employee("Jessica", 23, 4000, DateUtils.addMonths(new Date(), -6)),
|
||||
new Employee("Earl", 43, 10000, DateUtils.addMonths(new Date(), -2)),
|
||||
new Employee("Frank", 33, 7000, DateUtils.addDays(new Date(), -20)),
|
||||
new Employee("Steve", 26, 6000, DateUtils.addDays(new Date(), -10)),
|
||||
new Employee("John", 23, 5000, new Date())
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmpList_SortEmpList_thenSortedListinNaturalOrder() {
|
||||
Collections.sort(employees);
|
||||
|
||||
assertEquals(employees, employeesSortedByDateAsc);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmpList_SortEmpList_thenCheckSortedList() {
|
||||
|
||||
Collections.sort(employees, new Comparator<Employee>() {
|
||||
public int compare(Employee o1, Employee o2) {
|
||||
return o1.getJoiningDate().compareTo(o2.getJoiningDate());
|
||||
}
|
||||
});
|
||||
|
||||
assertEquals(employees, employeesSortedByDateAsc);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmpList_SortEmpList_thenCheckSortedListV1() {
|
||||
|
||||
Collections.sort(employees, new Comparator<Employee>() {
|
||||
public int compare(Employee emp1, Employee emp2) {
|
||||
if (emp1.getJoiningDate() == null || emp2.getJoiningDate() == null)
|
||||
return 0;
|
||||
return emp1.getJoiningDate().compareTo(emp2.getJoiningDate());
|
||||
}
|
||||
});
|
||||
|
||||
assertEquals(employees, employeesSortedByDateAsc);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmpList_SortEmpList_thenSortedListinAscOrder() {
|
||||
Collections.sort(employees, Collections.reverseOrder());
|
||||
|
||||
assertEquals(employees, employeesSortedByDateDesc);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmpList_SortEmpList_thenCheckSortedListAsc() {
|
||||
|
||||
Collections.sort(employees, new Comparator<Employee>() {
|
||||
public int compare(Employee emp1, Employee emp2) {
|
||||
return emp2.getJoiningDate().compareTo(emp1.getJoiningDate());
|
||||
}
|
||||
});
|
||||
|
||||
assertEquals(employees, employeesSortedByDateDesc);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmpList_SortEmpList_thenCheckSortedListAscV1() {
|
||||
|
||||
Collections.sort(employees, new Comparator<Employee>() {
|
||||
public int compare(Employee emp1, Employee emp2) {
|
||||
if (emp1.getJoiningDate() == null || emp2.getJoiningDate() == null)
|
||||
return 0;
|
||||
return emp2.getJoiningDate().compareTo(emp1.getJoiningDate());
|
||||
}
|
||||
});
|
||||
|
||||
assertEquals(employees, employeesSortedByDateDesc);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmpList_SortEmpList_thenCheckSortedListDescLambda() {
|
||||
|
||||
Collections.sort(employees,
|
||||
(emp1, emp2) -> emp2.getJoiningDate().compareTo(emp1.getJoiningDate()));
|
||||
|
||||
assertEquals(employees, employeesSortedByDateDesc);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmpList_SortEmpList_thenCheckSortedListDescLambdaV1() {
|
||||
|
||||
Collections.sort(employees, (emp1, emp2) -> {
|
||||
if (emp1.getJoiningDate() == null || emp2.getJoiningDate() == null)
|
||||
return 0;
|
||||
return emp2.getJoiningDate().compareTo(emp1.getJoiningDate());
|
||||
});
|
||||
|
||||
assertEquals(employees, employeesSortedByDateDesc);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmpList_SortEmpList_thenCheckSortedListAscLambda() {
|
||||
Collections.sort(employees,
|
||||
Comparator.comparing(Employee::getJoiningDate));
|
||||
assertEquals(employees, employeesSortedByDateAsc);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
## Core Java Collections List (Part 4)
|
||||
|
||||
This module contains articles about the Java List collection
|
||||
|
||||
### Relevant Articles:
|
||||
- [Working With a List of Lists in Java](https://www.baeldung.com/java-list-of-lists)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-collections-list-3)
|
|
@ -0,0 +1,56 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-collections-list-4</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-collections-list-4</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.sf.trove4j</groupId>
|
||||
<artifactId>trove4j</artifactId>
|
||||
<version>${trove4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>it.unimi.dsi</groupId>
|
||||
<artifactId>fastutil</artifactId>
|
||||
<version>${fastutil.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>colt</groupId>
|
||||
<artifactId>colt</artifactId>
|
||||
<version>${colt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-generator.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<trove4j.version>3.0.2</trove4j.version>
|
||||
<fastutil.version>8.1.0</fastutil.version>
|
||||
<colt.version>1.2.0</colt.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -6,3 +6,4 @@
|
|||
- [Volatile Variables and Thread Safety](https://www.baeldung.com/java-volatile-variables-thread-safety)
|
||||
- [Producer-Consumer Problem With Example in Java](https://www.baeldung.com/java-producer-consumer-problem)
|
||||
- [Acquire a Lock by a Key in Java](https://www.baeldung.com/java-acquire-lock-by-key)
|
||||
- [Differences Between set() and lazySet() in Java Atomic Variables](https://www.baeldung.com/java-atomic-set-vs-lazyset)
|
||||
|
|
|
@ -32,8 +32,8 @@
|
|||
<version>3.8.1</version>
|
||||
<configuration>
|
||||
<compilerArgs>
|
||||
<!-- Comment the arg below to print complete stack trace information -->
|
||||
<!-- <arg>-g:none</arg>-->
|
||||
<!-- Comment the arg below to print complete stack trace information -->
|
||||
<!-- <arg>-g:none</arg> -->
|
||||
</compilerArgs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
|
|
@ -32,8 +32,8 @@
|
|||
<version>3.8.1</version>
|
||||
<configuration>
|
||||
<compilerArgs>
|
||||
<!-- Comment the arg below to print complete stack trace information -->
|
||||
<!-- <arg>-g:none</arg>-->
|
||||
<!-- Comment the arg below to print complete stack trace information -->
|
||||
<!-- <arg>-g:none</arg> -->
|
||||
</compilerArgs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
|
|
@ -0,0 +1,6 @@
|
|||
## Java HttpClient
|
||||
|
||||
This module contains articles about Java HttpClient
|
||||
|
||||
### Relevant articles
|
||||
- TODO
|
|
@ -0,0 +1,58 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-httpclient</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-httpclient</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.mock-server</groupId>
|
||||
<artifactId>mockserver-netty</artifactId>
|
||||
<version>${mockserver.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mock-server</groupId>
|
||||
<artifactId>mockserver-client-java</artifactId>
|
||||
<version>${mockserver.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source.version}</source>
|
||||
<target>${maven.compiler.target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source.version>11</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>11</maven.compiler.target.version>
|
||||
<assertj.version>3.22.0</assertj.version>
|
||||
<mockserver.version>5.11.2</mockserver.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,162 @@
|
|||
package com.baeldung.httpclient;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.Authenticator;
|
||||
import java.net.PasswordAuthentication;
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class HttpClientPost {
|
||||
|
||||
public static HttpResponse<String> sendSynchronousPost(String serviceUrl) throws IOException, InterruptedException {
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create(serviceUrl))
|
||||
.POST(HttpRequest.BodyPublishers.noBody())
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = client
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
public static CompletableFuture<HttpResponse<String>> sendAsynchronousPost(String serviceUrl) {
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create(serviceUrl))
|
||||
.POST(HttpRequest.BodyPublishers.noBody())
|
||||
.build();
|
||||
|
||||
CompletableFuture<HttpResponse<String>> futureResponse = client
|
||||
.sendAsync(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
return futureResponse;
|
||||
}
|
||||
|
||||
public static List<CompletableFuture<HttpResponse<String>>> sendConcurrentPost(List<String> serviceUrls) {
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
|
||||
List<CompletableFuture<HttpResponse<String>>> completableFutures = serviceUrls.stream()
|
||||
.map(URI::create)
|
||||
.map(HttpRequest::newBuilder)
|
||||
.map(builder -> builder.POST(HttpRequest.BodyPublishers.noBody()))
|
||||
.map(HttpRequest.Builder::build)
|
||||
.map(request -> client.sendAsync(request, HttpResponse.BodyHandlers.ofString()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return completableFutures;
|
||||
}
|
||||
|
||||
public static HttpResponse<String> sendPostWithAuthHeader(String serviceUrl) throws IOException, InterruptedException {
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create(serviceUrl))
|
||||
.POST(HttpRequest.BodyPublishers.noBody())
|
||||
.header("Authorization", "Basic " + Base64.getEncoder()
|
||||
.encodeToString(("baeldung:123456").getBytes()))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = client
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
public static HttpResponse<String> sendPostWithAuthClient(String serviceUrl) throws IOException, InterruptedException {
|
||||
HttpClient client = HttpClient.newBuilder()
|
||||
.authenticator(new Authenticator() {
|
||||
@Override
|
||||
protected PasswordAuthentication getPasswordAuthentication() {
|
||||
return new PasswordAuthentication(
|
||||
"baeldung",
|
||||
"123456".toCharArray());
|
||||
}
|
||||
})
|
||||
.build();
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create(serviceUrl))
|
||||
.POST(HttpRequest.BodyPublishers.noBody())
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = client
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
public static HttpResponse<String> sendPostWithJsonBody(String serviceUrl) throws IOException, InterruptedException {
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create(serviceUrl))
|
||||
.POST(HttpRequest.BodyPublishers.ofString("{\"action\":\"hello\"}"))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = client
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
public static HttpResponse<String> sendPostWithFormData(String serviceUrl) throws IOException, InterruptedException {
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
|
||||
Map<String, String> formData = new HashMap<>();
|
||||
formData.put("username", "baeldung");
|
||||
formData.put("message", "hello");
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create(serviceUrl))
|
||||
.POST(HttpRequest.BodyPublishers.ofString(getFormDataAsString(formData)))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = client
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
public static HttpResponse<String> sendPostWithFileData(String serviceUrl, Path file) throws IOException, InterruptedException {
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create(serviceUrl))
|
||||
.POST(HttpRequest.BodyPublishers.ofFile(file))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = client
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
private static String getFormDataAsString(Map<String, String> formData) {
|
||||
StringBuilder formBodyBuilder = new StringBuilder();
|
||||
for (Map.Entry<String, String> singleEntry : formData.entrySet()) {
|
||||
if (formBodyBuilder.length() > 0) {
|
||||
formBodyBuilder.append("&");
|
||||
}
|
||||
formBodyBuilder.append(URLEncoder.encode(singleEntry.getKey(), StandardCharsets.UTF_8));
|
||||
formBodyBuilder.append("=");
|
||||
formBodyBuilder.append(URLEncoder.encode(singleEntry.getValue(), StandardCharsets.UTF_8));
|
||||
}
|
||||
return formBodyBuilder.toString();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,99 @@
|
|||
package com.baeldung.httpclient;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
class HttpClientPostUnitTest extends PostRequestMockServer {
|
||||
|
||||
@Test
|
||||
void givenSyncPostRequest_whenServerIsAvailable_thenOkStatusIsReceived() throws IOException, InterruptedException {
|
||||
HttpResponse<String> response = HttpClientPost.sendSynchronousPost(serviceUrl);
|
||||
assertThat(response.statusCode()).isEqualTo(200);
|
||||
assertThat(response.body()).isEqualTo("{\"message\":\"ok\"}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAsyncPostRequest_whenServerIsAvailable_thenOkStatusIsReceived() throws ExecutionException, InterruptedException {
|
||||
CompletableFuture<HttpResponse<String>> futureResponse = HttpClientPost.sendAsynchronousPost(serviceUrl);
|
||||
HttpResponse<String> response = futureResponse.get();
|
||||
|
||||
assertThat(response.statusCode()).isEqualTo(200);
|
||||
assertThat(response.body()).isEqualTo("{\"message\":\"ok\"}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenConcurrentPostRequests_whenServerIsAvailable_thenOkStatusIsReceived() throws ExecutionException, InterruptedException {
|
||||
List<CompletableFuture<HttpResponse<String>>> completableFutures = HttpClientPost
|
||||
.sendConcurrentPost(List.of(serviceUrl, serviceUrl));
|
||||
|
||||
CompletableFuture<List<HttpResponse<String>>> combinedFutures = CompletableFuture
|
||||
.allOf(completableFutures.toArray(new CompletableFuture[0]))
|
||||
.thenApply(future ->
|
||||
completableFutures.stream()
|
||||
.map(CompletableFuture::join)
|
||||
.collect(Collectors.toList()));
|
||||
|
||||
List<HttpResponse<String>> responses = combinedFutures.get();
|
||||
responses.forEach((response) -> {
|
||||
assertThat(response.statusCode()).isEqualTo(200);
|
||||
assertThat(response.body()).isEqualTo("{\"message\":\"ok\"}");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPostRequestWithAuthClient_whenServerIsAvailable_thenOkStatusIsReceived() throws IOException, InterruptedException {
|
||||
HttpResponse<String> response = HttpClientPost.sendPostWithAuthClient(serviceUrl);
|
||||
|
||||
assertThat(response.statusCode()).isEqualTo(200);
|
||||
assertThat(response.body()).isEqualTo("{\"message\":\"ok\"}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPostRequestWithAuthHeader_whenServerIsAvailable_thenOkStatusIsReceived() throws IOException, InterruptedException {
|
||||
HttpResponse<String> response = HttpClientPost.sendPostWithAuthHeader(serviceUrl);
|
||||
|
||||
assertThat(response.statusCode()).isEqualTo(200);
|
||||
assertThat(response.body()).isEqualTo("{\"message\":\"ok\"}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPostRequestWithJsonBody_whenServerIsAvailable_thenOkStatusIsReceived() throws IOException, InterruptedException {
|
||||
HttpResponse<String> response = HttpClientPost.sendPostWithJsonBody(serviceUrl);
|
||||
|
||||
assertThat(response.statusCode()).isEqualTo(200);
|
||||
assertThat(response.body()).isEqualTo("{\"message\":\"ok\"}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPostRequestWithFormData_whenServerIsAvailable_thenOkStatusIsReceived() throws IOException, InterruptedException {
|
||||
HttpResponse<String> response = HttpClientPost.sendPostWithFormData(serviceUrl);
|
||||
|
||||
assertThat(response.statusCode()).isEqualTo(200);
|
||||
assertThat(response.body()).isEqualTo("{\"message\":\"ok\"}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPostRequestWithFileData_whenServerIsAvailable_thenOkStatusIsReceived(@TempDir Path tempDir) throws IOException, InterruptedException {
|
||||
Path file = tempDir.resolve("temp.txt");
|
||||
List<String> lines = Arrays.asList("1", "2", "3");
|
||||
Files.write(file, lines);
|
||||
|
||||
HttpResponse<String> response = HttpClientPost.sendPostWithFileData(serviceUrl, file);
|
||||
|
||||
assertThat(response.statusCode()).isEqualTo(200);
|
||||
assertThat(response.body()).isEqualTo("{\"message\":\"ok\"}");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
package com.baeldung.httpclient;
|
||||
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.mockserver.client.MockServerClient;
|
||||
import org.mockserver.integration.ClientAndServer;
|
||||
import org.mockserver.model.HttpStatusCode;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URISyntaxException;
|
||||
|
||||
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
|
||||
import static org.mockserver.model.HttpRequest.request;
|
||||
import static org.mockserver.model.HttpResponse.response;
|
||||
|
||||
public abstract class PostRequestMockServer {
|
||||
|
||||
public static ClientAndServer mockServer;
|
||||
public static String serviceUrl;
|
||||
|
||||
private static int serverPort;
|
||||
|
||||
public static final String SERVER_ADDRESS = "127.0.0.1";
|
||||
public static final String PATH = "/test1";
|
||||
public static final String METHOD = "POST";
|
||||
|
||||
@BeforeAll
|
||||
static void startServer() throws IOException, URISyntaxException {
|
||||
serverPort = getFreePort();
|
||||
serviceUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH;
|
||||
mockServer = startClientAndServer(serverPort);
|
||||
mockBasicPostRequest();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopServer() {
|
||||
mockServer.stop();
|
||||
}
|
||||
|
||||
private static void mockBasicPostRequest() {
|
||||
new MockServerClient(SERVER_ADDRESS, serverPort)
|
||||
.when(
|
||||
request()
|
||||
.withPath(PATH)
|
||||
.withMethod(METHOD)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatusCode.OK_200.code())
|
||||
.withBody("{\"message\":\"ok\"}")
|
||||
);
|
||||
}
|
||||
|
||||
private static int getFreePort () throws IOException {
|
||||
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||
return serverSocket.getLocalPort();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -28,9 +28,15 @@ public class EmployeeVO {
|
|||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return Objects.equals(firstName, this.firstName)
|
||||
&& Objects.equals(lastName, this.lastName)
|
||||
&& Objects.equals(startDate, this.startDate);
|
||||
|
||||
if (this == obj) return true;
|
||||
if (obj == null || getClass() != obj.getClass()) return false;
|
||||
|
||||
EmployeeVO emp = (EmployeeVO) obj;
|
||||
|
||||
return Objects.equals(firstName, emp.firstName)
|
||||
&& Objects.equals(lastName, emp.lastName)
|
||||
&& Objects.equals(startDate, emp.startDate);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -2,4 +2,6 @@
|
|||
|
||||
This module contains articles about core features in the Java language
|
||||
|
||||
## TODO ##
|
||||
### Relevant Articles:
|
||||
|
||||
- [Difference Between == and equals() in Java](https://www.baeldung.com/java-equals-method-operator-difference)
|
||||
|
|
|
@ -5,4 +5,5 @@
|
|||
### Relevant articles:
|
||||
|
||||
- [Evaluating a Math Expression in Java](https://www.baeldung.com/java-evaluate-math-expression-string)
|
||||
- [Swap Two Variables in Java](https://www.baeldung.com/java-swap-two-variables)
|
||||
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math-2)
|
||||
|
|
|
@ -35,7 +35,6 @@
|
|||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
|
|
|
@ -67,7 +67,7 @@
|
|||
<dependency>
|
||||
<groupId>com.google.gdata</groupId>
|
||||
<artifactId>core</artifactId>
|
||||
<version>1.47.1</version>
|
||||
<version>${gdata.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
@ -193,6 +193,7 @@
|
|||
<source.version>1.8</source.version>
|
||||
<target.version>1.8</target.version>
|
||||
<spring.core.version>4.3.20.RELEASE</spring.core.version>
|
||||
<gdata.version>1.47.1</gdata.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -28,7 +28,7 @@
|
|||
<dependency>
|
||||
<groupId>io.vavr</groupId>
|
||||
<artifactId>vavr</artifactId>
|
||||
<version>0.10.3</version>
|
||||
<version>${vavr.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
@ -42,4 +42,8 @@
|
|||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<vavr.version>0.10.3</vavr.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -19,7 +19,7 @@
|
|||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>5.8.1</version>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
|
|
|
@ -35,6 +35,7 @@
|
|||
<module>core-java-collections-list</module>
|
||||
<module>core-java-collections-list-2</module>
|
||||
<module>core-java-collections-list-3</module>
|
||||
<module>core-java-collections-list-4</module>
|
||||
<module>core-java-collections-maps</module>
|
||||
<module>core-java-collections-maps-2</module>
|
||||
<module>core-java-collections-maps-3</module>
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
<?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">
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core</artifactId>
|
||||
|
||||
|
@ -22,4 +22,5 @@
|
|||
<maven.compiler.source>8</maven.compiler.source>
|
||||
<maven.compiler.target>8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,6 +1,7 @@
|
|||
<?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">
|
||||
<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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>multi-module-caching</artifactId>
|
||||
|
@ -8,22 +9,24 @@
|
|||
<description>Multi-module Maven caching example</description>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<modules>
|
||||
<module>runner</module>
|
||||
<module>core</module>
|
||||
</modules>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>31.0.1-jre</version>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
<guava.version>31.0.1-jre</guava.version>
|
||||
</properties>
|
||||
|
||||
<modules>
|
||||
<module>runner</module>
|
||||
<module>core</module>
|
||||
</modules>
|
||||
</project>
|
||||
</project>
|
|
@ -1,7 +1,7 @@
|
|||
<?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">
|
||||
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>runner</artifactId>
|
||||
|
||||
|
@ -53,4 +53,5 @@
|
|||
<maven.compiler.source>8</maven.compiler.source>
|
||||
<maven.compiler.target>8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,9 +1,8 @@
|
|||
<?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">
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>single-module-caching</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
@ -12,7 +11,7 @@
|
|||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>31.0.1-jre</version>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
@ -49,5 +48,7 @@
|
|||
<properties>
|
||||
<maven.compiler.source>8</maven.compiler.source>
|
||||
<maven.compiler.target>8</maven.compiler.target>
|
||||
<guava.version>31.0.1-jre</guava.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -3,13 +3,13 @@
|
|||
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>docker-internal-dto</artifactId>
|
||||
<name>docker-internal-dto</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.docker</groupId>
|
||||
<artifactId>docker</artifactId>
|
||||
<version>0.0.1</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>docker-internal-dto</artifactId>
|
||||
<name>docker-internal-dto</name>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -1 +1,3 @@
|
|||
### Relevant Articles:
|
||||
### Relevant Articles:
|
||||
|
||||
- [Pushing a Docker Image to a Private Repository](https://www.baeldung.com/ops/docker-push-image-to-private-repository)
|
||||
|
|
|
@ -1,21 +1,18 @@
|
|||
<?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">
|
||||
<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>docker-sample-app</artifactId>
|
||||
<name>docker-sample-app</name>
|
||||
<description>Demo project for Spring Boot and Docker</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.docker</groupId>
|
||||
<artifactId>docker</artifactId>
|
||||
<version>0.0.1</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>docker-sample-app</artifactId>
|
||||
<name>docker-sample-app</name>
|
||||
<description>Demo project for Spring Boot and Docker</description>
|
||||
|
||||
<properties>
|
||||
<java.version>11</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
|
@ -42,4 +39,8 @@
|
|||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
<properties>
|
||||
<java.version>11</java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,13 +1,14 @@
|
|||
<?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>
|
||||
<groupId>com.baeldung.docker</groupId>
|
||||
<artifactId>docker-spring-boot-postgres</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>docker-spring-boot-postgres</name>
|
||||
<description>Demo project showing Spring Boot, PostgreSQL, and Docker</description>
|
||||
|
||||
<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>
|
||||
<groupId>com.baeldung.docker</groupId>
|
||||
<artifactId>docker-spring-boot-postgres</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>docker-spring-boot-postgres</name>
|
||||
<description>Demo project showing Spring Boot, PostgreSQL, and Docker</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
|
@ -15,33 +16,32 @@
|
|||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<java.version>11</java.version>
|
||||
</properties>
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Creating Docker Images with Spring Boot](https://www.baeldung.com/spring-boot-docker-images)
|
||||
- [Starting Spring Boot Application in Docker With Profile](https://www.baeldung.com/spring-boot-docker-start-with-profile)
|
||||
|
|
|
@ -1,310 +0,0 @@
|
|||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Maven Start Up Batch script
|
||||
#
|
||||
# Required ENV vars:
|
||||
# ------------------
|
||||
# JAVA_HOME - location of a JDK home dir
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# M2_HOME - location of maven2's installed home dir
|
||||
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
# e.g. to debug Maven itself, use
|
||||
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
if [ -z "$MAVEN_SKIP_RC" ] ; then
|
||||
|
||||
if [ -f /etc/mavenrc ] ; then
|
||||
. /etc/mavenrc
|
||||
fi
|
||||
|
||||
if [ -f "$HOME/.mavenrc" ] ; then
|
||||
. "$HOME/.mavenrc"
|
||||
fi
|
||||
|
||||
fi
|
||||
|
||||
# OS specific support. $var _must_ be set to either true or false.
|
||||
cygwin=false;
|
||||
darwin=false;
|
||||
mingw=false
|
||||
case "`uname`" in
|
||||
CYGWIN*) cygwin=true ;;
|
||||
MINGW*) mingw=true;;
|
||||
Darwin*) darwin=true
|
||||
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
|
||||
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
if [ -x "/usr/libexec/java_home" ]; then
|
||||
export JAVA_HOME="`/usr/libexec/java_home`"
|
||||
else
|
||||
export JAVA_HOME="/Library/Java/Home"
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
if [ -r /etc/gentoo-release ] ; then
|
||||
JAVA_HOME=`java-config --jre-home`
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$M2_HOME" ] ; then
|
||||
## resolve links - $0 may be a link to maven's home
|
||||
PRG="$0"
|
||||
|
||||
# need this for relative symlinks
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG="`dirname "$PRG"`/$link"
|
||||
fi
|
||||
done
|
||||
|
||||
saveddir=`pwd`
|
||||
|
||||
M2_HOME=`dirname "$PRG"`/..
|
||||
|
||||
# make it fully qualified
|
||||
M2_HOME=`cd "$M2_HOME" && pwd`
|
||||
|
||||
cd "$saveddir"
|
||||
# echo Using m2 at $M2_HOME
|
||||
fi
|
||||
|
||||
# For Cygwin, ensure paths are in UNIX format before anything is touched
|
||||
if $cygwin ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --unix "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
|
||||
fi
|
||||
|
||||
# For Mingw, ensure paths are in UNIX format before anything is touched
|
||||
if $mingw ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME="`(cd "$M2_HOME"; pwd)`"
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
javaExecutable="`which javac`"
|
||||
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
|
||||
# readlink(1) is not available as standard on Solaris 10.
|
||||
readLink=`which readlink`
|
||||
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
|
||||
if $darwin ; then
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
|
||||
else
|
||||
javaExecutable="`readlink -f \"$javaExecutable\"`"
|
||||
fi
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
|
||||
JAVA_HOME="$javaHome"
|
||||
export JAVA_HOME
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$JAVACMD" ] ; then
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
else
|
||||
JAVACMD="`which java`"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
echo "Error: JAVA_HOME is not defined correctly." >&2
|
||||
echo " We cannot execute $JAVACMD" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
echo "Warning: JAVA_HOME environment variable is not set."
|
||||
fi
|
||||
|
||||
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
|
||||
|
||||
# traverses directory structure from process work directory to filesystem root
|
||||
# first directory with .mvn subdirectory is considered project base directory
|
||||
find_maven_basedir() {
|
||||
|
||||
if [ -z "$1" ]
|
||||
then
|
||||
echo "Path not specified to find_maven_basedir"
|
||||
return 1
|
||||
fi
|
||||
|
||||
basedir="$1"
|
||||
wdir="$1"
|
||||
while [ "$wdir" != '/' ] ; do
|
||||
if [ -d "$wdir"/.mvn ] ; then
|
||||
basedir=$wdir
|
||||
break
|
||||
fi
|
||||
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
|
||||
if [ -d "${wdir}" ]; then
|
||||
wdir=`cd "$wdir/.."; pwd`
|
||||
fi
|
||||
# end of workaround
|
||||
done
|
||||
echo "${basedir}"
|
||||
}
|
||||
|
||||
# concatenates all lines of a file
|
||||
concat_lines() {
|
||||
if [ -f "$1" ]; then
|
||||
echo "$(tr -s '\n' ' ' < "$1")"
|
||||
fi
|
||||
}
|
||||
|
||||
BASE_DIR=`find_maven_basedir "$(pwd)"`
|
||||
if [ -z "$BASE_DIR" ]; then
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
##########################################################################################
|
||||
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||
# This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||
##########################################################################################
|
||||
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found .mvn/wrapper/maven-wrapper.jar"
|
||||
fi
|
||||
else
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
|
||||
fi
|
||||
if [ -n "$MVNW_REPOURL" ]; then
|
||||
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
|
||||
else
|
||||
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
|
||||
fi
|
||||
while IFS="=" read key value; do
|
||||
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
|
||||
esac
|
||||
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Downloading from: $jarUrl"
|
||||
fi
|
||||
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
|
||||
if $cygwin; then
|
||||
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
|
||||
fi
|
||||
|
||||
if command -v wget > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found wget ... using wget"
|
||||
fi
|
||||
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
|
||||
wget "$jarUrl" -O "$wrapperJarPath"
|
||||
else
|
||||
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
|
||||
fi
|
||||
elif command -v curl > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found curl ... using curl"
|
||||
fi
|
||||
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
|
||||
curl -o "$wrapperJarPath" "$jarUrl" -f
|
||||
else
|
||||
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
|
||||
fi
|
||||
|
||||
else
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Falling back to using Java to download"
|
||||
fi
|
||||
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
|
||||
# For Cygwin, switch paths to Windows format before running javac
|
||||
if $cygwin; then
|
||||
javaClass=`cygpath --path --windows "$javaClass"`
|
||||
fi
|
||||
if [ -e "$javaClass" ]; then
|
||||
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo " - Compiling MavenWrapperDownloader.java ..."
|
||||
fi
|
||||
# Compiling the Java class
|
||||
("$JAVA_HOME/bin/javac" "$javaClass")
|
||||
fi
|
||||
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||
# Running the downloader
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo " - Running MavenWrapperDownloader.java ..."
|
||||
fi
|
||||
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
##########################################################################################
|
||||
# End of extension
|
||||
##########################################################################################
|
||||
|
||||
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo $MAVEN_PROJECTBASEDIR
|
||||
fi
|
||||
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --path --windows "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
|
||||
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
|
||||
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
|
||||
fi
|
||||
|
||||
# Provide a "standardized" way to retrieve the CLI args that will
|
||||
# work with both Windows and non-Windows executions.
|
||||
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
|
||||
export MAVEN_CMD_LINE_ARGS
|
||||
|
||||
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
exec "$JAVACMD" \
|
||||
$MAVEN_OPTS \
|
||||
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
|
||||
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
|
||||
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
|
|
@ -1,182 +0,0 @@
|
|||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM https://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Maven Start Up Batch script
|
||||
@REM
|
||||
@REM Required ENV vars:
|
||||
@REM JAVA_HOME - location of a JDK home dir
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM M2_HOME - location of maven2's installed home dir
|
||||
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
|
||||
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
|
||||
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
@REM e.g. to debug Maven itself, use
|
||||
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
|
||||
@echo off
|
||||
@REM set title of command window
|
||||
title %0
|
||||
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
|
||||
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
|
||||
|
||||
@REM set %HOME% to equivalent of $HOME
|
||||
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
|
||||
|
||||
@REM Execute a user defined script before this one
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
|
||||
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
|
||||
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
|
||||
:skipRcPre
|
||||
|
||||
@setlocal
|
||||
|
||||
set ERROR_CODE=0
|
||||
|
||||
@REM To isolate internal variables from possible post scripts, we use another setlocal
|
||||
@setlocal
|
||||
|
||||
@REM ==== START VALIDATION ====
|
||||
if not "%JAVA_HOME%" == "" goto OkJHome
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME not found in your environment. >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
:OkJHome
|
||||
if exist "%JAVA_HOME%\bin\java.exe" goto init
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME is set to an invalid directory. >&2
|
||||
echo JAVA_HOME = "%JAVA_HOME%" >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
@REM ==== END VALIDATION ====
|
||||
|
||||
:init
|
||||
|
||||
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
|
||||
@REM Fallback to current working directory if not found.
|
||||
|
||||
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
|
||||
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
|
||||
|
||||
set EXEC_DIR=%CD%
|
||||
set WDIR=%EXEC_DIR%
|
||||
:findBaseDir
|
||||
IF EXIST "%WDIR%"\.mvn goto baseDirFound
|
||||
cd ..
|
||||
IF "%WDIR%"=="%CD%" goto baseDirNotFound
|
||||
set WDIR=%CD%
|
||||
goto findBaseDir
|
||||
|
||||
:baseDirFound
|
||||
set MAVEN_PROJECTBASEDIR=%WDIR%
|
||||
cd "%EXEC_DIR%"
|
||||
goto endDetectBaseDir
|
||||
|
||||
:baseDirNotFound
|
||||
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
|
||||
cd "%EXEC_DIR%"
|
||||
|
||||
:endDetectBaseDir
|
||||
|
||||
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
|
||||
|
||||
@setlocal EnableExtensions EnableDelayedExpansion
|
||||
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
|
||||
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
|
||||
|
||||
:endReadAdditionalConfig
|
||||
|
||||
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
|
||||
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
|
||||
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
|
||||
|
||||
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
|
||||
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
|
||||
)
|
||||
|
||||
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||
if exist %WRAPPER_JAR% (
|
||||
if "%MVNW_VERBOSE%" == "true" (
|
||||
echo Found %WRAPPER_JAR%
|
||||
)
|
||||
) else (
|
||||
if not "%MVNW_REPOURL%" == "" (
|
||||
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
|
||||
)
|
||||
if "%MVNW_VERBOSE%" == "true" (
|
||||
echo Couldn't find %WRAPPER_JAR%, downloading it ...
|
||||
echo Downloading from: %DOWNLOAD_URL%
|
||||
)
|
||||
|
||||
powershell -Command "&{"^
|
||||
"$webclient = new-object System.Net.WebClient;"^
|
||||
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
|
||||
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
|
||||
"}"^
|
||||
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
|
||||
"}"
|
||||
if "%MVNW_VERBOSE%" == "true" (
|
||||
echo Finished downloading %WRAPPER_JAR%
|
||||
)
|
||||
)
|
||||
@REM End of extension
|
||||
|
||||
@REM Provide a "standardized" way to retrieve the CLI args that will
|
||||
@REM work with both Windows and non-Windows executions.
|
||||
set MAVEN_CMD_LINE_ARGS=%*
|
||||
|
||||
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
|
||||
if ERRORLEVEL 1 goto error
|
||||
goto end
|
||||
|
||||
:error
|
||||
set ERROR_CODE=1
|
||||
|
||||
:end
|
||||
@endlocal & set ERROR_CODE=%ERROR_CODE%
|
||||
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
|
||||
@REM check for post script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
|
||||
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
|
||||
:skipRcPost
|
||||
|
||||
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
|
||||
if "%MAVEN_BATCH_PAUSE%" == "on" pause
|
||||
|
||||
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
|
||||
|
||||
exit /B %ERROR_CODE%
|
|
@ -3,33 +3,21 @@
|
|||
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>docker-spring-boot</artifactId>
|
||||
<name>docker-spring-boot</name>
|
||||
<description>Demo project showing Spring Boot and Docker</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.docker</groupId>
|
||||
<artifactId>docker</artifactId>
|
||||
<version>0.0.1</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>docker-spring-boot</artifactId>
|
||||
|
||||
<name>docker-spring-boot</name>
|
||||
<description>Demo project showing Spring Boot and Docker</description>
|
||||
|
||||
<properties>
|
||||
<java.version>11</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.baeldung.docker</groupId>
|
||||
<artifactId>docker-internal-dto</artifactId>
|
||||
<version>0.0.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
|
@ -58,4 +46,8 @@
|
|||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
<properties>
|
||||
<java.version>11</java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -48,7 +48,6 @@
|
|||
<groupId>com.google.cloud.tools</groupId>
|
||||
<artifactId>jib-maven-plugin</artifactId>
|
||||
<version>2.7.1</version>
|
||||
|
||||
<configuration>
|
||||
<to>
|
||||
<image>heapsizing-demo-jib</image>
|
||||
|
@ -62,4 +61,4 @@
|
|||
<java.version>11</java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
</project>
|
|
@ -3,14 +3,13 @@
|
|||
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>
|
||||
|
||||
<groupId>com.baeldung.docker</groupId>
|
||||
<artifactId>docker</artifactId>
|
||||
<version>0.0.1</version>
|
||||
<name>docker</name>
|
||||
<description>Demo project showing Spring Boot and Docker</description>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
|
@ -18,10 +17,6 @@
|
|||
<relativePath>../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<java.version>11</java.version>
|
||||
</properties>
|
||||
|
||||
<modules>
|
||||
<module>docker-internal-dto</module>
|
||||
<module>docker-spring-boot</module>
|
||||
|
@ -31,4 +26,8 @@
|
|||
<module>docker-push-to-private-repo</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
<properties>
|
||||
<java.version>11</java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,5 +1,7 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.feign</groupId>
|
||||
<artifactId>feign</artifactId>
|
||||
|
@ -69,6 +71,7 @@
|
|||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -92,10 +95,8 @@
|
|||
<sources>
|
||||
<source>src/main/resources/users.xsd</source>
|
||||
</sources>
|
||||
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.jvnet.jaxb2.maven2</groupId>
|
||||
<artifactId>maven-jaxb2-plugin</artifactId>
|
||||
|
@ -111,7 +112,6 @@
|
|||
<schemaIncludes>
|
||||
<include>*.xsd</include>
|
||||
</schemaIncludes>
|
||||
|
||||
<generatePackage>com.baeldung.feign.soap</generatePackage>
|
||||
<generateDirectory>target/generated-sources/jaxb</generateDirectory>
|
||||
</configuration>
|
||||
|
@ -119,6 +119,6 @@
|
|||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -1,12 +1,12 @@
|
|||
<?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">
|
||||
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>graphql-error-handling</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>graphql-error-handling</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.graphql</groupId>
|
||||
|
@ -19,56 +19,47 @@
|
|||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.graphql-java</groupId>
|
||||
<artifactId>graphql-spring-boot-starter</artifactId>
|
||||
<version>${graphql-spring-boot-starter.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.graphql-java</groupId>
|
||||
<artifactId>graphql-java-tools</artifactId>
|
||||
<version>${graphql-java-tools.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.graphql-java</groupId>
|
||||
<artifactId>graphql-spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
<version>${graphql-spring-boot-starter.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.skyscreamer</groupId>
|
||||
<artifactId>jsonassert</artifactId>
|
||||
<version>${jsonassert.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
|
|
@ -85,7 +85,6 @@
|
|||
<artifactId>httpclient</artifactId>
|
||||
<version>${httpclient.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mock-server</groupId>
|
||||
<artifactId>mockserver-netty</artifactId>
|
||||
|
@ -98,13 +97,11 @@
|
|||
<version>${mockserver-client-java.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.graphql-java</groupId>
|
||||
<artifactId>graphql-java-extended-scalars</artifactId>
|
||||
<version>${graphql-java-extended-scalars.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -155,14 +152,11 @@
|
|||
<ratpack-core.version>1.9.0</ratpack-core.version>
|
||||
<nodes.version>0.5.0</nodes.version>
|
||||
<httpclient.version>4.5.13</httpclient.version>
|
||||
|
||||
<mockserver-netty.version>5.13.2</mockserver-netty.version>
|
||||
<mockserver-client-java.version>5.13.2</mockserver-client-java.version>
|
||||
|
||||
<jetty-maven-plugin.version>10.0.7</jetty-maven-plugin.version>
|
||||
|
||||
<graphql.java.generator.version>1.18</graphql.java.generator.version>
|
||||
<graphql-java-extended-scalars.version>2022-04-06T00-10-27-a70541e</graphql-java-extended-scalars.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
</project>
|
|
@ -3,12 +3,13 @@ package com.baeldung.graphql;
|
|||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.mockserver.client.MockServerClient;
|
||||
import org.mockserver.configuration.Configuration;
|
||||
import org.mockserver.integration.ClientAndServer;
|
||||
import org.mockserver.model.HttpStatusCode;
|
||||
import org.slf4j.event.Level;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URISyntaxException;
|
||||
|
||||
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
|
||||
import static org.mockserver.matchers.Times.exactly;
|
||||
|
@ -17,20 +18,22 @@ import static org.mockserver.model.HttpResponse.response;
|
|||
|
||||
public class GraphQLMockServer {
|
||||
|
||||
public static ClientAndServer mockServer;
|
||||
private static final String SERVER_ADDRESS = "127.0.0.1";
|
||||
private static final String PATH = "/graphql";
|
||||
|
||||
public static String serviceUrl;
|
||||
|
||||
private static ClientAndServer mockServer;
|
||||
private static int serverPort;
|
||||
|
||||
public static final String SERVER_ADDRESS = "127.0.0.1";
|
||||
public static final String HTTP_GET_POST = "GET";
|
||||
public static final String PATH = "/graphql";
|
||||
|
||||
@BeforeAll
|
||||
static void startServer() throws IOException, URISyntaxException {
|
||||
static void startServer() throws IOException {
|
||||
serverPort = getFreePort();
|
||||
serviceUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH;
|
||||
mockServer = startClientAndServer(serverPort);
|
||||
|
||||
Configuration config = Configuration.configuration().logLevel(Level.WARN);
|
||||
mockServer = startClientAndServer(config, serverPort);
|
||||
|
||||
mockAllBooksTitleRequest();
|
||||
mockAllBooksTitleAuthorRequest();
|
||||
}
|
||||
|
|
|
@ -28,4 +28,5 @@
|
|||
<properties>
|
||||
<graphql-spqr-spring-boot-starter-version>0.0.6</graphql-spqr-spring-boot-starter-version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -40,7 +40,7 @@
|
|||
<dependency>
|
||||
<groupId>javax.annotation</groupId>
|
||||
<artifactId>javax.annotation-api</artifactId>
|
||||
<version>1.2</version>
|
||||
<version>${annotation-api.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
@ -79,6 +79,7 @@
|
|||
<protoc.version>3.17.2</protoc.version>
|
||||
<os-maven-plugin.version>1.6.2</os-maven-plugin.version>
|
||||
<protobuf-maven-plugin.version>0.6.1</protobuf-maven-plugin.version>
|
||||
<annotation-api.version>1.2</annotation-api.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -51,25 +51,20 @@
|
|||
<user>admin</user>
|
||||
<!-- <passwordFile>${local.glassfish.passfile}</passwordFile> -->
|
||||
<adminPassword>password</adminPassword>
|
||||
|
||||
<domain>
|
||||
<name>${local.glassfish.domain}</name>
|
||||
<httpPort>8080</httpPort>
|
||||
<adminPort>4848</adminPort>
|
||||
|
||||
</domain>
|
||||
<components>
|
||||
<component>
|
||||
<name>${project.artifactId}</name>
|
||||
<artifact>target/${project.build.finalName}.war</artifact>
|
||||
|
||||
</component>
|
||||
</components>
|
||||
<debug>true</debug>
|
||||
<terse>false</terse>
|
||||
<echo>true</echo>
|
||||
|
||||
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
|
|
|
@ -23,7 +23,6 @@
|
|||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
|
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.booleantoint;
|
||||
|
||||
import org.apache.commons.lang3.BooleanUtils;
|
||||
|
||||
public class BooleanToInt {
|
||||
public static int booleanPrimitiveToInt(boolean foo) {
|
||||
int bar = 0;
|
||||
if (foo) {
|
||||
bar = 1;
|
||||
}
|
||||
return bar;
|
||||
}
|
||||
|
||||
public static int booleanPrimitiveToIntTernary(boolean foo) {
|
||||
return (foo) ? 1 : 0;
|
||||
}
|
||||
|
||||
public static int booleanObjectToInt(boolean foo) {
|
||||
return Boolean.compare(foo, false);
|
||||
}
|
||||
|
||||
public static int booleanObjectToIntInverse(boolean foo) {
|
||||
return Boolean.compare(foo, true) + 1;
|
||||
}
|
||||
|
||||
public static int booleanObjectMethodToInt(Boolean foo) {
|
||||
return foo.compareTo(false);
|
||||
}
|
||||
|
||||
public static int booleanObjectMethodToIntInverse(Boolean foo) {
|
||||
return foo.compareTo(true) + 1;
|
||||
}
|
||||
|
||||
public static int booleanUtilsToInt(Boolean foo) {
|
||||
return BooleanUtils.toInteger(foo);
|
||||
}
|
||||
|
||||
public static int bitwiseBooleanToInt(Boolean foo) {
|
||||
return (Boolean.hashCode(foo) >> 1) & 1;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.reversenumber;
|
||||
|
||||
public class ReverseNumber {
|
||||
|
||||
public static int reverseNumberWhileLoop(int number) {
|
||||
int reversedNumber = 0;
|
||||
int numberToReverse = Math.abs(number);
|
||||
|
||||
while (numberToReverse > 0) {
|
||||
int mod = numberToReverse % 10;
|
||||
reversedNumber = reversedNumber * 10 + mod;
|
||||
numberToReverse /= 10;
|
||||
}
|
||||
|
||||
return number < 0 ? reversedNumber * -1 : reversedNumber;
|
||||
}
|
||||
|
||||
public static int reverseNumberForLoop(int number) {
|
||||
int reversedNumber = 0;
|
||||
int numberToReverse = Math.abs(number);
|
||||
|
||||
for (; numberToReverse > 0; numberToReverse /= 10) {
|
||||
int mod = numberToReverse % 10;
|
||||
reversedNumber = reversedNumber * 10 + mod;
|
||||
}
|
||||
|
||||
return number < 0 ? reversedNumber * -1 : reversedNumber;
|
||||
}
|
||||
|
||||
public static int reverseNumberRecWrapper(int number) {
|
||||
int output = reverseNumberRec(Math.abs(number), 0);
|
||||
return number < 0 ? output * -1 : output;
|
||||
}
|
||||
private static int reverseNumberRec(int numberToReverse, int recursiveReversedNumber) {
|
||||
|
||||
if (numberToReverse > 0) {
|
||||
int mod = numberToReverse % 10;
|
||||
recursiveReversedNumber = recursiveReversedNumber * 10 + mod;
|
||||
numberToReverse /= 10;
|
||||
return reverseNumberRec(numberToReverse, recursiveReversedNumber);
|
||||
}
|
||||
|
||||
return recursiveReversedNumber;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
package com.baeldung.booleantoint;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class BooleanToIntUnitTest {
|
||||
@Test
|
||||
void givenBooleanPrimitiveValue_ThenReturnInt() {
|
||||
assertEquals(1, BooleanToInt.booleanPrimitiveToInt(true));
|
||||
assertEquals(0, BooleanToInt.booleanPrimitiveToInt(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBooleanPrimitiveValue_ThenReturnIntTernary() {
|
||||
assertEquals(1, BooleanToInt.booleanPrimitiveToIntTernary(true));
|
||||
assertEquals(0, BooleanToInt.booleanPrimitiveToIntTernary(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBooleanObject_ThenReturnInt() {
|
||||
assertEquals(0, BooleanToInt.booleanObjectToInt(false));
|
||||
assertEquals(1, BooleanToInt.booleanObjectToInt(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBooleanObject_ThenReturnIntInverse() {
|
||||
assertEquals(0, BooleanToInt.booleanObjectToIntInverse(false));
|
||||
assertEquals(1, BooleanToInt.booleanObjectToIntInverse(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBooleanObject_ThenReturnIntUsingClassMethod() {
|
||||
assertEquals(0, BooleanToInt.booleanObjectMethodToInt(false));
|
||||
assertEquals(1, BooleanToInt.booleanObjectMethodToInt(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBooleanObject_ThenReturnIntUsingClassMethodInverse() {
|
||||
assertEquals(0, BooleanToInt.booleanObjectMethodToIntInverse(false));
|
||||
assertEquals(1, BooleanToInt.booleanObjectMethodToIntInverse(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBoolean_ThenReturnIntUsingBooleanUtils() {
|
||||
assertEquals(0, BooleanToInt.booleanUtilsToInt(false));
|
||||
assertEquals(1, BooleanToInt.booleanUtilsToInt(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBoolean_ThenReturnIntUsingBitwiseOperators() {
|
||||
assertEquals(0, BooleanToInt.bitwiseBooleanToInt(false));
|
||||
assertEquals(1, BooleanToInt.bitwiseBooleanToInt(true));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.reversenumber;
|
||||
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ReverseNumberUnitTest {
|
||||
|
||||
private static final int ORIGINAL_NUMBER = 123456789;
|
||||
private static final int REVERSED_NUMBER = 987654321;
|
||||
|
||||
@Test
|
||||
void whenReverseNumberWhileLoop_thenOriginalEqualToReverse() {
|
||||
Assertions.assertThat(ReverseNumber.reverseNumberWhileLoop(ORIGINAL_NUMBER)).isEqualTo(REVERSED_NUMBER);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenReverseNumberForLoop_thenOriginalEqualToReverse() {
|
||||
Assertions.assertThat(ReverseNumber.reverseNumberForLoop(ORIGINAL_NUMBER)).isEqualTo(REVERSED_NUMBER);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenReverseNumberRec_thenOriginalEqualToReverse() {
|
||||
Assertions.assertThat(ReverseNumber.reverseNumberRecWrapper(ORIGINAL_NUMBER)).isEqualTo(REVERSED_NUMBER);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenReverseNegativeNumber_thenNumberShouldReverse() {
|
||||
Assertions.assertThat(ReverseNumber.reverseNumberWhileLoop(ORIGINAL_NUMBER * -1)).isEqualTo(REVERSED_NUMBER * -1);
|
||||
Assertions.assertThat(ReverseNumber.reverseNumberForLoop(ORIGINAL_NUMBER * -1)).isEqualTo(REVERSED_NUMBER * -1);
|
||||
Assertions.assertThat(ReverseNumber.reverseNumberRecWrapper(ORIGINAL_NUMBER * -1)).isEqualTo(REVERSED_NUMBER * -1);
|
||||
}
|
||||
}
|
|
@ -43,4 +43,5 @@
|
|||
<properties>
|
||||
<jib-maven-plugin.version>2.5.0</jib-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -27,7 +27,7 @@
|
|||
<dependency>
|
||||
<groupId>org.jsonschema2pojo</groupId>
|
||||
<artifactId>jsonschema2pojo-core</artifactId>
|
||||
<version>1.1.1</version>
|
||||
<version>${jsonschema2pojo-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jsoniter</groupId>
|
||||
|
@ -62,7 +62,7 @@
|
|||
<dependency>
|
||||
<groupId>com.io-informatics.oss</groupId>
|
||||
<artifactId>jackson-jsonld</artifactId>
|
||||
<version>0.1.1</version>
|
||||
<version>${jackson-jsonld.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
|
@ -85,7 +85,7 @@
|
|||
<dependency>
|
||||
<groupId>de.escalon.hypermedia</groupId>
|
||||
<artifactId>hydra-jsonld</artifactId>
|
||||
<version>0.4.2</version>
|
||||
<version>${hydra-jsonld.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
|
@ -96,7 +96,7 @@
|
|||
<dependency>
|
||||
<groupId>com.github.jsonld-java</groupId>
|
||||
<artifactId>jsonld-java</artifactId>
|
||||
<version>0.13.0</version>
|
||||
<version>${jsonld-java.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>jackson-core</artifactId>
|
||||
|
@ -154,6 +154,10 @@
|
|||
<moshi.version>1.9.2</moshi.version>
|
||||
<fastjson.version>1.2.21</fastjson.version>
|
||||
<json.version>20211205</json.version>
|
||||
<jsonschema2pojo-core.version>1.1.1</jsonschema2pojo-core.version>
|
||||
<jackson-jsonld.version>0.1.1</jackson-jsonld.version>
|
||||
<hydra-jsonld.version>0.4.2</hydra-jsonld.version>
|
||||
<jsonld-java.version>0.13.0</jsonld-java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -15,7 +15,7 @@
|
|||
<dependency>
|
||||
<groupId>io.kubernetes</groupId>
|
||||
<artifactId>client-java</artifactId>
|
||||
<version>11.0.0</version>
|
||||
<version>${client-java.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
|
@ -39,4 +39,8 @@
|
|||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<client-java.version>11.0.0</client-java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -112,7 +112,7 @@
|
|||
<artifactId>structurizr-plantuml</artifactId>
|
||||
<version>${structurizr.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<dependency>
|
||||
<groupId>org.immutables</groupId>
|
||||
<artifactId>value</artifactId>
|
||||
<version>${immutables.version}</version>
|
||||
|
@ -177,7 +177,7 @@
|
|||
</path>
|
||||
</annotationProcessorPaths>
|
||||
<compilerArgs>
|
||||
<!-- NullAway will warn by default, uncomment the next line to make the build
|
||||
<!-- NullAway will warn by default, uncomment the next line to make the build
|
||||
fail -->
|
||||
<!-- <arg>-Xep:NullAway:ERROR</arg> -->
|
||||
<arg>-XepExcludedPaths:(.*)/test/.*|(.*)/jcabi/.*</arg>
|
||||
|
@ -190,7 +190,7 @@
|
|||
<artifactId>plexus-compiler-javac-errorprone</artifactId>
|
||||
<version>2.8</version>
|
||||
</dependency>
|
||||
<!-- override plexus-compiler-javac-errorprone's dependency on Error Prone with the
|
||||
<!-- override plexus-compiler-javac-errorprone's dependency on Error Prone with the
|
||||
latest version -->
|
||||
<dependency>
|
||||
<groupId>com.google.errorprone</groupId>
|
||||
|
|
|
@ -172,9 +172,9 @@
|
|||
<kafka.version>1.0.0</kafka.version>
|
||||
<ignite.version>2.4.0</ignite.version>
|
||||
<gson.version>2.8.2</gson.version>
|
||||
<cache.version>1.1.0</cache.version>
|
||||
<cache.version>1.1.1</cache.version>
|
||||
<flink.version>1.5.0</flink.version>
|
||||
<hazelcast.version>3.8.4</hazelcast.version>
|
||||
<hazelcast.version>5.1.1</hazelcast.version>
|
||||
<org.apache.crunch.crunch-core.version>0.15.0</org.apache.crunch.crunch-core.version>
|
||||
<org.apache.hadoop.hadoop-client>2.2.0</org.apache.hadoop.hadoop-client>
|
||||
<jmapper.version>1.6.0.1</jmapper.version>
|
||||
|
|
|
@ -6,11 +6,11 @@
|
|||
<groupId>com.baeldung.maven.plugin</groupId>
|
||||
<artifactId>host-maven-repo-example</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<url>https://github.com/sgrverma23/host-maven-repo-example.git</url>
|
||||
<url>https://github.com/${repository-owner}/${repository-name}.git</url>
|
||||
<scm>
|
||||
<url>https://github.com/sgrverma23/host-maven-repo-example.git</url>
|
||||
<connection>scm:git:git@github.com:sgrverma23/host-maven-repo-example.git</connection>
|
||||
<developerConnection>scm:git:git@github.com:sgrverma23/host-maven-repo-example.git</developerConnection>
|
||||
<url>https://github.com/${repository-owner}/${repository-name}.git</url>
|
||||
<connection>scm:git:git@github.com:${repository-owner}/${repository-name}.git</connection>
|
||||
<developerConnection>scm:git:git@github.com:${repository-owner}/${repository-name}.git</developerConnection>
|
||||
</scm>
|
||||
<distributionManagement>
|
||||
<repository>
|
||||
|
@ -43,13 +43,13 @@
|
|||
<message>Maven artifacts for ${project.version}</message>
|
||||
<noJekyll>true</noJekyll>
|
||||
<outputDirectory>${project.build.directory}</outputDirectory>
|
||||
<branch>refs/heads/main</branch>
|
||||
<branch>refs/heads/${branch-name}</branch>
|
||||
<includes>
|
||||
<include>**/*</include>
|
||||
</includes>
|
||||
<merge>true</merge>
|
||||
<repositoryName>host-maven-repo-example</repositoryName>
|
||||
<repositoryOwner>sgrverma23</repositoryOwner>
|
||||
<repositoryName>${repository-name}</repositoryName>
|
||||
<repositoryOwner>${repository-owner}</repositoryOwner>
|
||||
<server>github</server>
|
||||
</configuration>
|
||||
<executions>
|
||||
|
@ -89,7 +89,7 @@
|
|||
<repositories>
|
||||
<repository>
|
||||
<id>PROJECT-REPO-URL</id>
|
||||
<url>https://github.com/sgrverma23/host-maven-repo-example/main</url>
|
||||
<url>https://github.com/${repository-owner}/${repository-name}/${branch-name}</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>always</updatePolicy>
|
||||
|
@ -98,9 +98,13 @@
|
|||
</repositories>
|
||||
|
||||
<properties>
|
||||
<!--Put your own properties-->
|
||||
<repository-owner>Put-repo-owner</repository-owner>
|
||||
<repository-name>Put-repository-name</repository-name>
|
||||
<branch-name>Put-branch-name</branch-name>
|
||||
<github.global.server>github</github.global.server>
|
||||
<maven.compiler.source>8</maven.compiler.source>
|
||||
<maven.compiler.target>8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
</project>
|
||||
|
|
|
@ -21,7 +21,7 @@
|
|||
<executions>
|
||||
<execution>
|
||||
<id>enforce-file-exists</id>
|
||||
<phase/>
|
||||
<phase />
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
|
|
@ -13,7 +13,14 @@
|
|||
<artifactId>maven-parent-pom-resolution</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
|
||||
<modules>
|
||||
<module>plugin-enabled</module>
|
||||
<module>skip-parameter</module>
|
||||
<module>phase-none</module>
|
||||
<module>empty-phase</module>
|
||||
</modules>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -27,26 +34,19 @@
|
|||
<goal>enforce</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<rules>
|
||||
<requireFilesExist>
|
||||
<files>
|
||||
<file>${project.basedir}/src/file-that-must-exist.txt</file>
|
||||
</files>
|
||||
</requireFilesExist>
|
||||
</rules>
|
||||
<rules>
|
||||
<requireFilesExist>
|
||||
<files>
|
||||
<file>${project.basedir}/src/file-that-must-exist.txt</file>
|
||||
</files>
|
||||
</requireFilesExist>
|
||||
</rules>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<modules>
|
||||
<module>plugin-enabled</module>
|
||||
<module>skip-parameter</module>
|
||||
<module>phase-none</module>
|
||||
<module>empty-phase</module>
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
|
|
|
@ -23,4 +23,5 @@
|
|||
<properties>
|
||||
<spring-core.version>4.3.30.RELEASE</spring-core.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -33,4 +33,5 @@
|
|||
<properties>
|
||||
<spring-core.version>5.3.16</spring-core.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -5,7 +5,6 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>webapp</artifactId>
|
||||
<name>webapp</name>
|
||||
|
||||
<packaging>war</packaging>
|
||||
|
||||
<parent>
|
||||
|
@ -30,4 +29,5 @@
|
|||
<properties>
|
||||
<maven-war-plugin.version>3.3.2</maven-war-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -15,8 +15,8 @@
|
|||
</parent>
|
||||
|
||||
<modules>
|
||||
<module>animal-sniffer-mvn-plugin</module>
|
||||
<module>maven-archetype</module>
|
||||
<module>animal-sniffer-mvn-plugin</module>
|
||||
<module>maven-archetype</module>
|
||||
<!-- <module>compiler-plugin-java-9</module> --> <!-- We haven't upgraded to java 9. -->
|
||||
<module>maven-copy-files</module>
|
||||
<module>maven-custom-plugin</module>
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.mycompany</groupId>
|
||||
<artifactId>muleesb</artifactId>
|
||||
|
@ -218,4 +219,4 @@
|
|||
<mule-maven-plugin.version>2.2.1</mule-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
</project>
|
|
@ -0,0 +1,4 @@
|
|||
Username,Id,First name,Last name
|
||||
doe1,7173,John,Doe
|
||||
smith3,3722,Dana,Smith
|
||||
john22,5490,John,Wang
|
|
|
@ -1,7 +1,5 @@
|
|||
<?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">
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.core-java-persistence-2</groupId>
|
||||
<artifactId>core-java-persistence-2</artifactId>
|
||||
|
@ -41,6 +39,20 @@
|
|||
<artifactId>mssql-jdbc</artifactId>
|
||||
<version>${mssql.driver.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.jooq</groupId>
|
||||
<artifactId>jooq</artifactId>
|
||||
<version>3.11.11</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.json</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
<version>20220320</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
|
|
@ -0,0 +1,137 @@
|
|||
package com.baeldung.resultset2json;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.jooq.Record;
|
||||
import org.jooq.RecordMapper;
|
||||
import org.jooq.impl.DSL;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.json.JSONArray;
|
||||
|
||||
public class ResultSet2JSON {
|
||||
|
||||
public static void main(String... args) throws ClassNotFoundException, SQLException {
|
||||
|
||||
ResultSet2JSON testClass = new ResultSet2JSON();
|
||||
testClass.convertWithoutJOOQ();
|
||||
}
|
||||
|
||||
public void convertWithoutJOOQ() throws ClassNotFoundException, SQLException {
|
||||
Class.forName("org.h2.Driver");
|
||||
Connection dbConnection = DriverManager.getConnection("jdbc:h2:mem:rs2jdbc", "user", "password");
|
||||
|
||||
// Create a table
|
||||
Statement stmt = dbConnection.createStatement();
|
||||
stmt.execute("CREATE TABLE words AS SELECT * FROM CSVREAD('./example.csv')");
|
||||
ResultSet resultSet = stmt.executeQuery("SELECT * FROM words");
|
||||
|
||||
JSONArray result1 = resultSet2JdbcWithoutJOOQ(resultSet);
|
||||
System.out.println(result1);
|
||||
|
||||
resultSet.close();
|
||||
}
|
||||
|
||||
public void convertUsingJOOQDefaultApproach() throws ClassNotFoundException, SQLException {
|
||||
Class.forName("org.h2.Driver");
|
||||
Connection dbConnection = DriverManager.getConnection("jdbc:h2:mem:rs2jdbc", "user", "password");
|
||||
// Create a table
|
||||
Statement stmt = dbConnection.createStatement();
|
||||
stmt.execute("CREATE TABLE words AS SELECT * FROM CSVREAD('./example.csv')");
|
||||
ResultSet resultSet = stmt.executeQuery("SELECT * FROM words");
|
||||
|
||||
JSONObject result1 = resultSet2JdbcUsingJOOQDefaultApproach(resultSet, dbConnection);
|
||||
System.out.println(result1);
|
||||
|
||||
resultSet.close();
|
||||
}
|
||||
|
||||
public void convertUsingCustomisedJOOQ() throws ClassNotFoundException, SQLException {
|
||||
Class.forName("org.h2.Driver");
|
||||
Connection dbConnection = DriverManager.getConnection("jdbc:h2:mem:rs2jdbc", "user", "password");
|
||||
// Create a table
|
||||
Statement stmt = dbConnection.createStatement();
|
||||
stmt.execute("CREATE TABLE words AS SELECT * FROM CSVREAD('./example.csv')");
|
||||
ResultSet resultSet = stmt.executeQuery("SELECT * FROM words");
|
||||
|
||||
JSONArray result1 = resultSet2JdbcUsingCustomisedJOOQ(resultSet, dbConnection);
|
||||
System.out.println(result1);
|
||||
|
||||
resultSet.close();
|
||||
}
|
||||
|
||||
public static JSONArray resultSet2JdbcWithoutJOOQ(ResultSet resultSet) throws SQLException {
|
||||
ResultSetMetaData md = resultSet.getMetaData();
|
||||
int numCols = md.getColumnCount();
|
||||
List<String> colNames = IntStream.range(0, numCols)
|
||||
.mapToObj(i -> {
|
||||
try {
|
||||
return md.getColumnName(i + 1);
|
||||
} catch (SQLException e) {
|
||||
|
||||
e.printStackTrace();
|
||||
return "?";
|
||||
}
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
JSONArray result = new JSONArray();
|
||||
while (resultSet.next()) {
|
||||
JSONObject row = new JSONObject();
|
||||
colNames.forEach(cn -> {
|
||||
try {
|
||||
row.put(cn, resultSet.getObject(cn));
|
||||
} catch (JSONException | SQLException e) {
|
||||
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
result.put(row);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static JSONObject resultSet2JdbcUsingJOOQDefaultApproach(ResultSet resultSet, Connection dbConnection) throws SQLException {
|
||||
JSONObject result = new JSONObject(DSL.using(dbConnection)
|
||||
.fetch(resultSet)
|
||||
.formatJSON());
|
||||
return result;
|
||||
}
|
||||
|
||||
public static JSONArray resultSet2JdbcUsingCustomisedJOOQ(ResultSet resultSet, Connection dbConnection) throws SQLException {
|
||||
ResultSetMetaData md = resultSet.getMetaData();
|
||||
int numCols = md.getColumnCount();
|
||||
List<String> colNames = IntStream.range(0, numCols)
|
||||
.mapToObj(i -> {
|
||||
try {
|
||||
return md.getColumnName(i + 1);
|
||||
} catch (SQLException e) {
|
||||
|
||||
e.printStackTrace();
|
||||
return "?";
|
||||
}
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
List<JSONObject> json = DSL.using(dbConnection)
|
||||
.fetch(resultSet)
|
||||
.map(new RecordMapper<Record, JSONObject>() {
|
||||
|
||||
@Override
|
||||
public JSONObject map(Record r) {
|
||||
JSONObject obj = new JSONObject();
|
||||
colNames.forEach(cn -> obj.put(cn, r.get(cn)));
|
||||
return obj;
|
||||
}
|
||||
});
|
||||
return new JSONArray(json);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,75 @@
|
|||
package com.baeldung.resultset2json;
|
||||
|
||||
import static com.baeldung.resultset2json.ResultSet2JSON.resultSet2JdbcWithoutJOOQ;
|
||||
import static com.baeldung.resultset2json.ResultSet2JSON.resultSet2JdbcUsingJOOQDefaultApproach;
|
||||
import static com.baeldung.resultset2json.ResultSet2JSON.resultSet2JdbcUsingCustomisedJOOQ;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class ResultSet2JSONUnitTest {
|
||||
JSONObject object = new JSONObject(
|
||||
"{\"records\":[[\"doe1\",\"7173\",\"John\",\"Doe\"],[\"smith3\",\"3722\",\"Dana\",\"Smith\"],[\"john22\",\"5490\",\"John\",\"Wang\"]],\"fields\":[{\"schema\":\"PUBLIC\",\"name\":\"USERNAME\",\"type\":\"VARCHAR\",\"table\":\"WORDS\"},{\"schema\":\"PUBLIC\",\"name\":\"ID\",\"type\":\"VARCHAR\",\"table\":\"WORDS\"},{\"schema\":\"PUBLIC\",\"name\":\"First name\",\"type\":\"VARCHAR\",\"table\":\"WORDS\"},{\"schema\":\"PUBLIC\",\"name\":\"Last name\",\"type\":\"VARCHAR\",\"table\":\"WORDS\"}]}");
|
||||
|
||||
JSONArray array = new JSONArray(
|
||||
"[{\"USERNAME\":\"doe1\",\"First name\":\"John\",\"ID\":\"7173\",\"Last name\":\"Doe\"},{\"USERNAME\":\"smith3\",\"First name\":\"Dana\",\"ID\":\"3722\",\"Last name\":\"Smith\"},{\"USERNAME\":\"john22\",\"First name\":\"John\",\"ID\":\"5490\",\"Last name\":\"Wang\"}]");
|
||||
|
||||
@Test
|
||||
void whenResultSetConvertedWithoutJOOQ_shouldMatchJSON() throws SQLException, ClassNotFoundException {
|
||||
Class.forName("org.h2.Driver");
|
||||
Connection dbConnection = DriverManager.getConnection("jdbc:h2:mem:rs2jdbc1", "user", "password");
|
||||
|
||||
// Create a table
|
||||
Statement stmt = dbConnection.createStatement();
|
||||
stmt.execute("CREATE TABLE words AS SELECT * FROM CSVREAD('./example.csv')");
|
||||
ResultSet resultSet = stmt.executeQuery("SELECT * FROM words");
|
||||
|
||||
JSONArray result1 = resultSet2JdbcWithoutJOOQ(resultSet);
|
||||
|
||||
resultSet.close();
|
||||
|
||||
assertTrue(array.similar(result1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenResultSetConvertedUsingJOOQDefaultApproach_shouldMatchJSON() throws SQLException, ClassNotFoundException {
|
||||
Class.forName("org.h2.Driver");
|
||||
Connection dbConnection = DriverManager.getConnection("jdbc:h2:mem:rs2jdbc2", "user", "password");
|
||||
// Create a table
|
||||
Statement stmt = dbConnection.createStatement();
|
||||
stmt.execute("CREATE TABLE words AS SELECT * FROM CSVREAD('./example.csv')");
|
||||
ResultSet resultSet = stmt.executeQuery("SELECT * FROM words");
|
||||
|
||||
JSONObject result2 = resultSet2JdbcUsingJOOQDefaultApproach(resultSet, dbConnection);
|
||||
|
||||
resultSet.close();
|
||||
|
||||
assertTrue(object.similar(result2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenResultSetConvertedUsingCustomisedJOOQ_shouldMatchJSON() throws SQLException, ClassNotFoundException {
|
||||
Class.forName("org.h2.Driver");
|
||||
Connection dbConnection = DriverManager.getConnection("jdbc:h2:mem:rs2jdbc3", "user", "password");
|
||||
// Create a table
|
||||
Statement stmt = dbConnection.createStatement();
|
||||
stmt.execute("CREATE TABLE words AS SELECT * FROM CSVREAD('./example.csv')");
|
||||
ResultSet resultSet = stmt.executeQuery("SELECT * FROM words");
|
||||
|
||||
JSONArray result3 = resultSet2JdbcUsingCustomisedJOOQ(resultSet, dbConnection);
|
||||
|
||||
resultSet.close();
|
||||
|
||||
assertTrue(array.similar(result3));
|
||||
}
|
||||
|
||||
}
|
|
@ -16,7 +16,7 @@
|
|||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- Spring -->
|
||||
<!-- Spring -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
|
@ -32,7 +32,7 @@
|
|||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<version>${hsqldb.version}</version>
|
||||
|
|
|
@ -11,3 +11,4 @@ This module contains articles about use of Queries in Hibernate.
|
|||
- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache)
|
||||
- [Hibernate’s addScalar() Method](https://www.baeldung.com/hibernate-addscalar)
|
||||
- [Distinct Queries in HQL](https://www.baeldung.com/java-hql-distinct)
|
||||
- [JPA and Hibernate – Criteria vs. JPQL vs. HQL Query](https://www.baeldung.com/jpql-hql-criteria-query)
|
||||
|
|
|
@ -14,7 +14,7 @@
|
|||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- Spring -->
|
||||
<!-- Spring -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
|
@ -30,8 +30,7 @@
|
|||
<artifactId>tomcat-dbcp</artifactId>
|
||||
<version>${tomcat-dbcp.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- validation -->
|
||||
<!-- validation -->
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
|
@ -45,7 +44,6 @@
|
|||
<version>${org.springframework.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
|
@ -81,8 +79,7 @@
|
|||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-generator.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<org.springframework.version>5.0.2.RELEASE</org.springframework.version>
|
||||
|
|
|
@ -32,5 +32,4 @@ public class EmployeeCriteriaIntegrationTest {
|
|||
session.close();
|
||||
assertArrayEquals(expectedSortCritEmployeeList.toArray(), employeeCriteriaQueries.getAllEmployees().toArray());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -50,4 +50,4 @@
|
|||
<morphia.version>1.5.3</morphia.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
</project>
|
|
@ -60,6 +60,7 @@
|
|||
<module>spring-boot-persistence</module>
|
||||
<module>spring-boot-persistence-h2</module>
|
||||
<module>spring-boot-persistence-mongodb</module>
|
||||
<module>spring-boot-persistence-mongodb-2</module>
|
||||
<module>spring-data-arangodb</module>
|
||||
<module>spring-data-cassandra</module>
|
||||
<module>spring-data-cassandra-test</module>
|
||||
|
@ -108,4 +109,4 @@
|
|||
<postgresql.version>42.2.20</postgresql.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
</project>
|
|
@ -39,7 +39,7 @@
|
|||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<mysql-connector-java.version>8.0.12</mysql-connector-java.version>
|
||||
<mysql-connector-java.version>8.0.23</mysql-connector-java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,6 +1,6 @@
|
|||
spring:
|
||||
datasource:
|
||||
url: jdbc:mysql://localhost:3306/test?useLegacyDatetimeCode=false
|
||||
url: jdbc:mysql://localhost:3306/test?
|
||||
username: root
|
||||
password:
|
||||
|
||||
|
@ -9,6 +9,6 @@ spring:
|
|||
ddl-auto: update
|
||||
properties:
|
||||
hibernate:
|
||||
dialect: org.hibernate.dialect.MySQL5Dialect
|
||||
dialect: org.hibernate.dialect.MySQL8Dialect
|
||||
jdbc:
|
||||
time_zone: UTC
|
|
@ -0,0 +1,2 @@
|
|||
/.idea/
|
||||
/target/
|
|
@ -0,0 +1,4 @@
|
|||
# Relevant Articles
|
||||
|
||||
- [Logging MongoDB Queries with Spring Boot](https://www.baeldung.com/spring-boot-mongodb-logging)
|
||||
- More articles: [[<--prev]](../spring-boot-persistence-mongodb)
|
|
@ -0,0 +1,35 @@
|
|||
<?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>spring-boot-persistence-mongodb-2</artifactId>
|
||||
<name>spring-boot-persistence-mongodb-2</name>
|
||||
<packaging>war</packaging>
|
||||
<description>This is simple boot application for Spring boot persistence mongodb test</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-mongodb</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>de.flapdoodle.embed</groupId>
|
||||
<artifactId>de.flapdoodle.embed.mongo</artifactId>
|
||||
<version>${embed.mongo.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<embed.mongo.version>3.2.6</embed.mongo.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class SpringBootPersistenceApplication {
|
||||
|
||||
public static void main(String ... args) {
|
||||
SpringApplication.run(SpringBootPersistenceApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue