diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDeque.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDeque.java index 4c220b4047..45ef842670 100644 --- a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDeque.java +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDeque.java @@ -31,6 +31,6 @@ public class BalancedBracketsUsingDeque { } } - return true; + return deque.isEmpty(); } } \ No newline at end of file diff --git a/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDequeUnitTest.java b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDequeUnitTest.java index 964c1ce11a..4c0a56dabc 100644 --- a/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDequeUnitTest.java +++ b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDequeUnitTest.java @@ -49,6 +49,12 @@ public class BalancedBracketsUsingDequeUnitTest { assertThat(result).isFalse(); } + @Test + public void givenAnotherEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingDeque.isBalanced("{{}("); + assertThat(result).isFalse(); + } + @Test public void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() { boolean result = balancedBracketsUsingDeque.isBalanced("{[()]}"); diff --git a/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingStringUnitTest.java b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingStringUnitTest.java index 69ce42b0f1..bda85a75ce 100644 --- a/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingStringUnitTest.java +++ b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingStringUnitTest.java @@ -49,6 +49,12 @@ public class BalancedBracketsUsingStringUnitTest { assertThat(result).isFalse(); } + @Test + public void givenAnotherEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingString.isBalanced("{{}("); + assertThat(result).isFalse(); + } + @Test public void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() { boolean result = balancedBracketsUsingString.isBalanced("{[()]}"); diff --git a/apache-poi-2/pom.xml b/apache-poi-2/pom.xml index 30270cd7be..af959292fa 100644 --- a/apache-poi-2/pom.xml +++ b/apache-poi-2/pom.xml @@ -1,7 +1,7 @@ + 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"> 4.0.0 apache-poi-2 0.0.1-SNAPSHOT @@ -25,5 +25,4 @@ 5.2.0 - - + \ No newline at end of file diff --git a/apache-spark/README.md b/apache-spark/README.md index 3a2d2f4e15..862626988b 100644 --- a/apache-spark/README.md +++ b/apache-spark/README.md @@ -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) diff --git a/apache-spark/data/customerData.csv b/apache-spark/data/customerData.csv new file mode 100644 index 0000000000..8661bcb352 --- /dev/null +++ b/apache-spark/data/customerData.csv @@ -0,0 +1,9 @@ +id,zoneId,FIRST_NAME,MIDDLE_NAME,LAST_NAME,CITY,gender,transaction_date,transaction_amount +1,EU11,Ana1,A,MN, London,Female,1/2/2018,5200 +2,EU12,Ana2,A,MN, London,Female,29/3/2018,1000 +3,EU13,Jack1,Josh,MN, London,Male,19/6/2018,9600 +4,EU14,Jack2,Josh,MN, London,Male,9/9/2018,1000 +5,EU15,Nick1,H,Dee,London,Male,9/6/2021,3000 +6,EU16,Nick2,H,Dee,London,Male,27/9/2021,500 +7,EU17,Nick3,H,Dee,London,Male,8/12/2021,500 +8,EU18,Sara1,H,Dee,London,Female,7/4/2021,2000 \ No newline at end of file diff --git a/apache-spark/data/customerData.json b/apache-spark/data/customerData.json new file mode 100644 index 0000000000..d713d75678 --- /dev/null +++ b/apache-spark/data/customerData.json @@ -0,0 +1,114 @@ +[ + { + "zoneId": "LONDON", + "customerId": 1, + "gender": "Female", + "name": "jane austin", + "contact": { + "street_Address": "XYZ Road", + "address2": "house 47", + "zipcode": "MK1110", + "county": "DCounty", + "phone_number": "(919) 403-0025", + "customer_city": "CityA" + }, + "transaction_date": "2021-02-05", + "transaction_amount": 15000 + }, + { + "zoneId": "LONDON", + "customerId": 2, + "gender": "Male", + "name": "Jack Trevor", + "contact": { + "street_Address": " kingfisher road", + "address2": "SUITE 110", + "zipcode": "HM1190", + "county": "CCounty", + "phone_number": "(919) 403-0025", + "customer_city": "CityB" + }, + "transaction_date": "2021-02-05", + "transaction_amount": 12000 + }, + { + "zoneId": "LONDON", + "customerId": 11, + "gender": "Female", + "name": "jane1 austin", + "contact": { + "street_Address": "B Road", + "address2": "house 47", + "zipcode": "MK1110", + "county": "BCounty", + "phone_number": "(919) 403-0025", + "customer_city": "CityA" + }, + "transaction_date": "2021-02-05", + "transaction_amount": 1000 + }, + { + "zoneId": "LONDON", + "customerId": 21, + "gender": "Male", + "name": "Jack1 Trevor", + "contact": { + "street_Address": " A road", + "address2": "SUITE 777", + "zipcode": "AZ890", + "county": "ACounty", + "phone_number": "(919) 403-0025", + "customer_city": "CityB" + }, + "transaction_date": "2021-02-05", + "transaction_amount": 1000 + }, + { + "zoneId": "Wales", + "customerId": 3, + "gender": "Male", + "name": "John Jack", + "contact": { + "street_Address": "sunny croft", + "address2": "SUITE 1", + "zipcode": "SN1030", + "county": "bucks", + "phone_number": "(919) 403-0025", + "customer_city": "Cardiff" + }, + "transaction_date": "2018-02-05", + "transaction_amount": 5000 + }, + { + "zoneId": "LONDON", + "customerId": 4, + "gender": "Male", + "name": "Jack Trevor", + "contact": { + "street_Address": " kingfisher road", + "address2": "SUITE 110", + "zipcode": "HM1190", + "county": "Hampshire", + "phone_number": "(919) 403-0025", + "customer_city": "CityB" + }, + "transaction_date": "2021-02-05", + "transaction_amount": 500 + }, + { + "zoneId": "Wales", + "customerId": 5, + "gender": "Male", + "name": "John Jack", + "contact": { + "street_Address": "sunny croft", + "address2": "SUITE 1", + "zipcode": "SN1030", + "county": "ECounty", + "phone_number": "(919) 403-0025", + "customer_city": "Cardiff" + }, + "transaction_date": "2018-01-25", + "transaction_amount": 500 + } +] diff --git a/apache-spark/data/minCustomerData.json b/apache-spark/data/minCustomerData.json new file mode 100644 index 0000000000..a47a739d51 --- /dev/null +++ b/apache-spark/data/minCustomerData.json @@ -0,0 +1,20 @@ +[ + { + "id": "1", + "gender": "Female", + "name": "Jo", + "transaction_amount": 200 + }, + { + "id":"2", + "gender": "Male", + "name": "Mike", + "transaction_amount": 500 + }, + { + "id": "3", + "gender": "Male", + "name": "Dave", + "transaction_amount": 5000 + } +] \ No newline at end of file diff --git a/apache-spark/docker/docker-compose.yaml b/apache-spark/docker/docker-compose.yaml new file mode 100644 index 0000000000..960e543229 --- /dev/null +++ b/apache-spark/docker/docker-compose.yaml @@ -0,0 +1,33 @@ +version: "3" + +services: + postgres: + image: postgres:12.3-alpine + restart: always + environment: + POSTGRES_PASSWORD: postgres + POSTGRES_USER: postgres + expose: + - 5432 + ports: + - 5432:5432 + command: -p 5432 + volumes: + - ./init.sql:/docker-entrypoint-initdb.d/init.sql +# - postgres:/var/lib/postgresql/data + + pgadmin: + image: dpage/pgadmin4:4.23 + environment: + PGADMIN_DEFAULT_EMAIL: admin@pgadmin.com + PGADMIN_DEFAULT_PASSWORD: password + PGADMIN_LISTEN_PORT: 80 + ports: + - 15432:80 + volumes: + - pgadmin:/var/lib/pgadmin + depends_on: + - postgres + +volumes: + pgadmin: \ No newline at end of file diff --git a/apache-spark/docker/init.sql b/apache-spark/docker/init.sql new file mode 100755 index 0000000000..371135faa3 --- /dev/null +++ b/apache-spark/docker/init.sql @@ -0,0 +1 @@ +CREATE DATABASE customerdb; \ No newline at end of file diff --git a/apache-spark/pom.xml b/apache-spark/pom.xml index 05c5088662..b86e99433a 100644 --- a/apache-spark/pom.xml +++ b/apache-spark/pom.xml @@ -20,37 +20,31 @@ org.apache.spark spark-core_2.11 ${org.apache.spark.spark-core.version} - provided org.apache.spark spark-sql_2.11 ${org.apache.spark.spark-sql.version} - provided org.apache.spark spark-graphx_2.11 ${org.apache.spark.spark-graphx.version} - provided graphframes graphframes ${graphframes.version} - provided org.apache.spark spark-streaming_2.11 ${org.apache.spark.spark-streaming.version} - provided org.apache.spark spark-mllib_2.11 ${org.apache.spark.spark-mllib.version} - provided org.apache.spark @@ -67,6 +61,11 @@ spark-cassandra-connector-java_2.11 ${com.datastax.spark.spark-cassandra-connector-java.version} + + org.postgresql + postgresql + ${postgres.version} + @@ -108,6 +107,7 @@ 2.4.8 2.5.2 1.6.0-M1 + 42.3.3 \ No newline at end of file diff --git a/apache-spark/src/main/java/com/baeldung/dataframes/Customer.java b/apache-spark/src/main/java/com/baeldung/dataframes/Customer.java new file mode 100644 index 0000000000..97fa160872 --- /dev/null +++ b/apache-spark/src/main/java/com/baeldung/dataframes/Customer.java @@ -0,0 +1,52 @@ +package com.baeldung.dataframes; + +public class Customer { + String id; + String name; + String gender; + int transaction_amount; + + public Customer() { + + } + + public Customer(String id, String name, String gender, int transaction_amount) { + this.id = id; + this.name = name; + this.gender = gender; + this.transaction_amount = transaction_amount; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public int getTransaction_amount() { + return transaction_amount; + } + + public void setTransaction_amount(int transaction_amount) { + this.transaction_amount = transaction_amount; + } + +} diff --git a/apache-spark/src/main/java/com/baeldung/dataframes/CustomerDataAggregationPipeline.java b/apache-spark/src/main/java/com/baeldung/dataframes/CustomerDataAggregationPipeline.java new file mode 100644 index 0000000000..869645624a --- /dev/null +++ b/apache-spark/src/main/java/com/baeldung/dataframes/CustomerDataAggregationPipeline.java @@ -0,0 +1,129 @@ +package com.baeldung.dataframes; + +import static org.apache.spark.sql.functions.col; +import static org.apache.spark.sql.functions.column; +import static org.apache.spark.sql.functions.concat; +import static org.apache.spark.sql.functions.lit; + +import java.util.Properties; + +import org.apache.spark.sql.Dataset; +import org.apache.spark.sql.Row; +import org.apache.spark.sql.SaveMode; +import org.apache.spark.sql.SparkSession; +import org.apache.spark.sql.functions; + +public class CustomerDataAggregationPipeline { + private static final SparkSession SPARK_SESSION = SparkDriver.getSparkSession(); + + private final Properties dbProperties; + + public CustomerDataAggregationPipeline(Properties properties) { + dbProperties = properties; + } + + public static void main(String[] args) { + // replace with actual DB properties + Properties dbProps = new Properties(); + dbProps.setProperty("connectionURL", "jdbc:postgresql://localhost:5432/customerdb"); + dbProps.setProperty("driver", "org.postgresql.Driver"); + dbProps.setProperty("user", "postgres"); + dbProps.setProperty("password", "postgres"); + + new CustomerDataAggregationPipeline(dbProps).run(); + } + + public void run() { + Dataset ebayDFRaw = ingestCustomerDataFromEbay(); + Dataset ebayDf = normalizeCustomerDataFromEbay(ebayDFRaw); + + Dataset amazonDFRaw = ingestCustomerDataFromAmazon(); + Dataset amazonDf = normalizeCustomerDataFromAmazon(amazonDFRaw); + + Dataset combineDataframes = combineDataframes(ebayDf, amazonDf); + + Dataset rowDataset = aggregateYearlySalesByGender(combineDataframes); + + exportData(rowDataset); + } + + private static Dataset ingestCustomerDataFromAmazon() { + return SPARK_SESSION.read() + .format("csv") + .option("header", "true") + .schema(SchemaFactory.customerSchema()) + .option("dateFormat", "m/d/YYYY") + .load("data/customerData.csv"); + } + + private static Dataset ingestCustomerDataFromEbay() { + return SPARK_SESSION.read() + .format("org.apache.spark.sql.execution.datasources.json.JsonFileFormat") + .option("multiline", true) + .load("data/customerData.json"); + } + + private static Dataset combineDataframes(Dataset df1, Dataset df2) { + return df1.unionByName(df2); + } + + private static Dataset normalizeCustomerDataFromEbay(Dataset rawDataset) { + Dataset transformedDF = rawDataset.withColumn("id", concat(rawDataset.col("zoneId"), lit("-"), rawDataset.col("customerId"))) + .drop(column("customerId")) + .withColumn("source", lit("ebay")) + .withColumn("city", rawDataset.col("contact.customer_city")) + .drop(column("contact")) + .drop(column("zoneId")) + .withColumn("year", functions.year(col("transaction_date"))) + .drop("transaction_date") + .withColumn("firstName", functions.split(column("name"), " ") + .getItem(0)) + .withColumn("lastName", functions.split(column("name"), " ") + .getItem(1)) + .drop(column("name")); + + print(transformedDF); + return transformedDF; + } + + private static Dataset normalizeCustomerDataFromAmazon(Dataset rawDataset) { + + Dataset transformedDF = rawDataset.withColumn("id", concat(rawDataset.col("zoneId"), lit("-"), rawDataset.col("id"))) + .withColumn("source", lit("amazon")) + .withColumnRenamed("CITY", "city") + .withColumnRenamed("PHONE_NO", "contactNo") + .withColumnRenamed("POSTCODE", "postCode") + .withColumnRenamed("FIRST_NAME", "firstName") + .drop(column("MIDDLE_NAME")) + .drop(column("zoneId")) + .withColumnRenamed("LAST_NAME", "lastName") + .withColumn("year", functions.year(col("transaction_date"))) + .drop("transaction_date"); + + print(transformedDF); + return transformedDF; + } + + private static Dataset aggregateYearlySalesByGender(Dataset dataset) { + + Dataset aggDF = dataset.groupBy(column("year"), column("source"), column("gender")) + .sum("transaction_amount") + .withColumnRenamed("sum(transaction_amount)", "annual_spending") + .orderBy(col("year").asc(), col("annual_spending").desc()); + + print(aggDF); + return aggDF; + } + + private static void print(Dataset aggDs) { + aggDs.show(); + aggDs.printSchema(); + } + + private void exportData(Dataset dataset) { + String connectionURL = dbProperties.getProperty("connectionURL"); + dataset.write() + .mode(SaveMode.Overwrite) + .jdbc(connectionURL, "customer", dbProperties); + } +} diff --git a/apache-spark/src/main/java/com/baeldung/dataframes/CustomerToDataFrameConverterApp.java b/apache-spark/src/main/java/com/baeldung/dataframes/CustomerToDataFrameConverterApp.java new file mode 100644 index 0000000000..53799c1079 --- /dev/null +++ b/apache-spark/src/main/java/com/baeldung/dataframes/CustomerToDataFrameConverterApp.java @@ -0,0 +1,46 @@ +package com.baeldung.dataframes; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.spark.sql.Dataset; +import org.apache.spark.sql.Row; + +public class CustomerToDataFrameConverterApp { + + private static final List CUSTOMERS = Arrays.asList( + aCustomerWith("01", "jo", "Female", 2000), + aCustomerWith("02", "jack", "Male", 1200) + ); + + public static void main(String[] args) { + Dataset dataFrame = convertAfterMappingRows(CUSTOMERS); + print(dataFrame); + Dataset customerDF = convertToDataFrameWithNoChange(); + print(customerDF); + } + + public static Dataset convertToDataFrameWithNoChange() { + return SparkDriver.getSparkSession().createDataFrame(CUSTOMERS, Customer.class); + } + + public static Dataset convertAfterMappingRows(List customer) { + List rows = customer.stream() + .map(c -> new CustomerToRowMapper().call(c)) + .collect(Collectors.toList()); + + return SparkDriver.getSparkSession() + .createDataFrame(rows, SchemaFactory.minimumCustomerDataSchema()); + } + + private static Customer aCustomerWith(String id, String name, String gender, int amount) { + return new Customer(id, name, gender, amount); + } + + private static void print(Dataset dataFrame) { + dataFrame.printSchema(); + dataFrame.show(); + } + +} diff --git a/apache-spark/src/main/java/com/baeldung/dataframes/CustomerToRowMapper.java b/apache-spark/src/main/java/com/baeldung/dataframes/CustomerToRowMapper.java new file mode 100644 index 0000000000..e54bceb3ad --- /dev/null +++ b/apache-spark/src/main/java/com/baeldung/dataframes/CustomerToRowMapper.java @@ -0,0 +1,18 @@ +package com.baeldung.dataframes; + +import org.apache.commons.lang3.StringUtils; +import org.apache.spark.api.java.function.MapFunction; +import org.apache.spark.sql.Row; +import org.apache.spark.sql.RowFactory; + +public class CustomerToRowMapper implements MapFunction { + + @Override + public Row call(Customer customer) { + Row row = RowFactory.create( + customer.getId(), customer.getName().toUpperCase(), + StringUtils.substring(customer.getGender(),0, 1), + customer.getTransaction_amount()); + return row; + } +} \ No newline at end of file diff --git a/apache-spark/src/main/java/com/baeldung/dataframes/DataFrameToCustomerConverterApp.java b/apache-spark/src/main/java/com/baeldung/dataframes/DataFrameToCustomerConverterApp.java new file mode 100644 index 0000000000..31ad8de12b --- /dev/null +++ b/apache-spark/src/main/java/com/baeldung/dataframes/DataFrameToCustomerConverterApp.java @@ -0,0 +1,21 @@ +package com.baeldung.dataframes; + +import org.apache.spark.sql.Dataset; +import org.apache.spark.sql.Encoders; +import org.apache.spark.sql.Row; + +public class DataFrameToCustomerConverterApp { + + public static void main(String[] args) { + Dataset df = SparkDriver.getSparkSession() + .read() + .format("org.apache.spark.sql.execution.datasources.json.JsonFileFormat") + .option("multiline", true) + .load("data/minCustomerData.json"); + df.show(); + df.printSchema(); + Dataset customerDS = df.map(new RowToCustomerMapper(), Encoders.bean(Customer. class)); + customerDS.show(); + customerDS.printSchema(); + } +} diff --git a/apache-spark/src/main/java/com/baeldung/dataframes/DataSetToDataFrameConverterApp.java b/apache-spark/src/main/java/com/baeldung/dataframes/DataSetToDataFrameConverterApp.java new file mode 100644 index 0000000000..23db18dddf --- /dev/null +++ b/apache-spark/src/main/java/com/baeldung/dataframes/DataSetToDataFrameConverterApp.java @@ -0,0 +1,57 @@ +package com.baeldung.dataframes; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.spark.sql.Dataset; +import org.apache.spark.sql.Encoders; +import org.apache.spark.sql.Row; +import org.apache.spark.sql.SparkSession; + +public class DataSetToDataFrameConverterApp { + + private static final SparkSession SPARK_SESSION = SparkDriver.getSparkSession(); + + public static void main(String[] args) { + + Dataset customerDataset = convertToDataSetFromPOJO(); + Dataset customerDataFrame = customerDataset.toDF(); + print(customerDataFrame); + + List names = getNames(); + Dataset namesDataset = convertToDataSetFromStrings(names); + Dataset namesDataFrame = namesDataset.toDF(); + print(namesDataFrame); + } + + private static Dataset convertToDataSetFromStrings(List names) { + return SPARK_SESSION.createDataset(names, Encoders.STRING()); + } + + private static Dataset convertToDataSetFromPOJO() { + return SPARK_SESSION.createDataset(CUSTOMERS, Encoders.bean(Customer.class)); + } + + private static final List CUSTOMERS = Arrays.asList( + aCustomerWith("01", "jo", "Female", 2000), + aCustomerWith("02", "jack", "Female", 1200), + aCustomerWith("03", "ash", "male", 2000), + aCustomerWith("04", "emma", "Female", 2000) + ); + + private static List getNames() { + return CUSTOMERS.stream() + .map(Customer::getName) + .collect(Collectors.toList()); + } + + private static void print(Dataset df) { + df.show(); + df.printSchema(); + } + + private static Customer aCustomerWith(String id, String name, String gender, int amount) { + return new Customer(id, name, gender, amount); + } +} diff --git a/apache-spark/src/main/java/com/baeldung/dataframes/RowToCustomerMapper.java b/apache-spark/src/main/java/com/baeldung/dataframes/RowToCustomerMapper.java new file mode 100644 index 0000000000..02fde539c8 --- /dev/null +++ b/apache-spark/src/main/java/com/baeldung/dataframes/RowToCustomerMapper.java @@ -0,0 +1,19 @@ +package com.baeldung.dataframes; + +import org.apache.spark.api.java.function.MapFunction; +import org.apache.spark.sql.Row; + +class RowToCustomerMapper implements MapFunction { + + @Override + public Customer call(Row row) { + + Customer customer = new Customer(); + customer.setId(row.getAs("id")); + customer.setName(row.getAs("name")); + customer.setGender(row.getAs("gender")); + customer.setTransaction_amount(Math.toIntExact(row.getAs("transaction_amount"))); + + return customer; + } +} diff --git a/apache-spark/src/main/java/com/baeldung/dataframes/SchemaFactory.java b/apache-spark/src/main/java/com/baeldung/dataframes/SchemaFactory.java new file mode 100644 index 0000000000..6c298e4829 --- /dev/null +++ b/apache-spark/src/main/java/com/baeldung/dataframes/SchemaFactory.java @@ -0,0 +1,31 @@ +package com.baeldung.dataframes; + +import org.apache.spark.sql.types.DataTypes; +import org.apache.spark.sql.types.StructField; +import org.apache.spark.sql.types.StructType; + +public class SchemaFactory { + + public static StructType customerSchema() { + return DataTypes.createStructType( + new StructField[] { DataTypes.createStructField("id", DataTypes.IntegerType, false), + DataTypes.createStructField("zoneId", DataTypes.StringType, false), + DataTypes.createStructField("FIRST_NAME", DataTypes.StringType, false), + DataTypes.createStructField("MIDDLE_NAME", DataTypes.StringType, false), + DataTypes.createStructField("LAST_NAME", DataTypes.StringType, false), + DataTypes.createStructField("CITY", DataTypes.StringType, false), + DataTypes.createStructField("gender", DataTypes.StringType, false), + DataTypes.createStructField("transaction_date", DataTypes.DateType, false), + DataTypes.createStructField("transaction_amount", DataTypes.IntegerType, false) + }); + } + + public static StructType minimumCustomerDataSchema() { + return DataTypes.createStructType(new StructField[] { + DataTypes.createStructField("id", DataTypes.StringType, true), + DataTypes.createStructField("name", DataTypes.StringType, true), + DataTypes.createStructField("gender", DataTypes.StringType, true), + DataTypes.createStructField("transaction_amount", DataTypes.IntegerType, true) + }); + } +} diff --git a/apache-spark/src/main/java/com/baeldung/dataframes/SparkDriver.java b/apache-spark/src/main/java/com/baeldung/dataframes/SparkDriver.java new file mode 100644 index 0000000000..adc25170a7 --- /dev/null +++ b/apache-spark/src/main/java/com/baeldung/dataframes/SparkDriver.java @@ -0,0 +1,16 @@ +package com.baeldung.dataframes; + +import java.io.Serializable; + +import org.apache.spark.sql.SparkSession; + +public class SparkDriver implements Serializable { + + public static SparkSession getSparkSession() { + return SparkSession.builder() + .appName("Customer Aggregation pipeline") + .master("local") + .getOrCreate(); + + } +} diff --git a/apache-spark/src/test/java/com/baeldung/dataframes/CustomerDataAggregationPipelineLiveTest.java b/apache-spark/src/test/java/com/baeldung/dataframes/CustomerDataAggregationPipelineLiveTest.java new file mode 100644 index 0000000000..52a7b1451f --- /dev/null +++ b/apache-spark/src/test/java/com/baeldung/dataframes/CustomerDataAggregationPipelineLiveTest.java @@ -0,0 +1,52 @@ +package com.baeldung.dataframes; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Properties; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +class CustomerDataAggregationPipelineLiveTest { + + private static Connection conn; + + @BeforeAll + static void beforeAll() throws SQLException { + DriverManager.registerDriver(new org.postgresql.Driver()); + String dbURL1 = "jdbc:postgresql://localhost:5432/customerdb"; + conn = DriverManager.getConnection(dbURL1, "postgres", "postgres"); + + String sql = "drop table if exists customer"; + + PreparedStatement statement = conn.prepareStatement(sql); + statement.executeUpdate(); + } + + @Test + void givenCSVAndJSON_whenRun_thenStoresAggregatedDataFrameInDB() throws Exception { + Properties dbProps = new Properties(); + dbProps.setProperty("connectionURL", "jdbc:postgresql://localhost:5432/customerdb"); + dbProps.setProperty("driver", "org.postgresql.Driver"); + dbProps.setProperty("user", "postgres"); + dbProps.setProperty("password", "postgres"); + + CustomerDataAggregationPipeline pipeline = new CustomerDataAggregationPipeline(dbProps); + pipeline.run(); + + String allCustomersSql = "Select count(*) from customer"; + + Statement statement = conn.createStatement(); + ResultSet resultSet = statement.executeQuery(allCustomersSql); + resultSet.next(); + int count = resultSet.getInt(1); + assertEquals(7, count); + } + +} diff --git a/apache-spark/src/test/java/com/baeldung/dataframes/CustomerToDataFrameConverterAppUnitTest.java b/apache-spark/src/test/java/com/baeldung/dataframes/CustomerToDataFrameConverterAppUnitTest.java new file mode 100644 index 0000000000..06c8f66bcd --- /dev/null +++ b/apache-spark/src/test/java/com/baeldung/dataframes/CustomerToDataFrameConverterAppUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.dataframes; + +import static com.baeldung.dataframes.CustomerToDataFrameConverterApp.convertAfterMappingRows; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.List; + +import org.apache.spark.sql.Dataset; +import org.apache.spark.sql.Row; +import org.junit.jupiter.api.Test; + +class CustomerToDataFrameConverterAppUnitTest { + + @Test + void givenCustomers_whenConvertAfterMappingRows_thenConvertsToDataSet() { + + List customers = Arrays.asList( + new Customer("01", "jo", "Female", 2000), + new Customer("02", "jack", "Male", 1200) + ); + + Dataset customerDF = convertAfterMappingRows(customers); + List rows = customerDF.collectAsList(); + Row row1 = rows.get(0); + Row row2 = rows.get(1); + + assertEquals("01", row1.get(0)); + assertEquals( "JO", row1.get(1)); + assertEquals( "F", row1.get(2)); + assertEquals( 2000, row1.get(3)); + + assertEquals("02", row2.get(0)); + assertEquals( "JACK", row2.get(1)); + assertEquals( "M", row2.get(2)); + assertEquals( 1200, row2.get(3)); + } + + @Test + void givenCustomers_whenConvertWithNoChange_thenConvertsToDataSet() { + + List customers = Arrays.asList( + new Customer("01", "jo", "Female", 2000), + new Customer("02", "jack", "Male", 1200) + ); + + Dataset customerDF = CustomerToDataFrameConverterApp.convertToDataFrameWithNoChange(); + List rows = customerDF.collectAsList(); + Row row1 = rows.get(0); + Row row2 = rows.get(1); + + assertEquals("01", row1.getAs("id")); + assertEquals( "jo", row1.getAs("name")); + assertEquals( "Female", row1.getAs("gender")); + assertEquals( 2000, (int)row1.getAs("transaction_amount")); + + assertEquals("02", row2.getAs("id")); + assertEquals( "jack", row2.getAs("name")); + assertEquals( "Male", row2.getAs("gender")); + assertEquals( 1200, (int)row2.getAs("transaction_amount")); + } +} diff --git a/apache-spark/src/test/java/com/baeldung/differences/rdd/ActionsUnitTest.java b/apache-spark/src/test/java/com/baeldung/differences/rdd/ActionsUnitTest.java index a3e1811e6f..b1083021a9 100644 --- a/apache-spark/src/test/java/com/baeldung/differences/rdd/ActionsUnitTest.java +++ b/apache-spark/src/test/java/com/baeldung/differences/rdd/ActionsUnitTest.java @@ -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 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 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> totalByCountry = expenditurePairRdd.reduceByKey((x, y) -> x + y) - .collect(); - System.out.println("Total per Country: " + totalByCountry); - + List> totalByCountry = expenditurePairRdd + .reduceByKey(Double::sum) + .collect(); + + LOG.debug("Total per Country: {}", totalByCountry); + for(Tuple2 tuple : totalByCountry) { if (tuple._1.equals("Mexico")) { assertEquals(Double.valueOf(99164), tuple._2); diff --git a/apache-spark/src/test/java/com/baeldung/differences/rdd/DataFrameUnitTest.java b/apache-spark/src/test/java/com/baeldung/differences/rdd/DataFrameUnitTest.java index f294e5bc66..621e589fb6 100644 --- a/apache-spark/src/test/java/com/baeldung/differences/rdd/DataFrameUnitTest.java +++ b/apache-spark/src/test/java/com/baeldung/differences/rdd/DataFrameUnitTest.java @@ -39,8 +39,10 @@ public class DataFrameUnitTest { @Test public void whenSelectSpecificColumns_thenColumnsFiltered() { Dataset selectedData = data.select(col("country"), col("year"), col("value")); - selectedData.show(); - + + // uncomment to see table + // selectedData.show(); + List 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 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 recordsPerCountry = data.groupBy(col("country")) .count(); - recordsPerCountry.show(); - + + // uncomment to see table + // recordsPerCountry.show(); + Dataset filteredData = recordsPerCountry.filter(col("country").equalTo("Sweden")); - assertEquals(new Long(12), filteredData.first() + assertEquals(12L, filteredData.first() .get(1)); } diff --git a/apache-spark/src/test/java/com/baeldung/differences/rdd/DatasetUnitTest.java b/apache-spark/src/test/java/com/baeldung/differences/rdd/DatasetUnitTest.java index 1d83505812..4fde933a3b 100644 --- a/apache-spark/src/test/java/com/baeldung/differences/rdd/DatasetUnitTest.java +++ b/apache-spark/src/test/java/com/baeldung/differences/rdd/DatasetUnitTest.java @@ -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 data = dataFrameReader.option("header", "true") .csv("data/Tourist.csv"); - Dataset responseWithSelectedColumns = data.select(col("region"), - col("country"), col("year"), col("series"), col("value").cast("double"), + Dataset 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 selectedData = typedDataset .filter((FilterFunction) 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 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) record -> record.getYear() != null - && (Long.valueOf(record.getYear()) > 2010 && Long.valueOf(record.getYear()) < 2017)) - .show(); + Dataset filteredData = typedDataset.filter( + (FilterFunction) 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) record -> record.getValue() != null - && record.getSeries() - .contains("expenditure")) - .groupBy("country") - .agg(sum("value")) - .show(); + Dataset filteredData = typedDataset.filter((FilterFunction) record -> record.getValue() != null + && record.getSeries().contains("expenditure")) + .groupBy("country") + .agg(sum("value")); + + // uncomment to see output + // filteredData.show(); + + assertEquals(212, filteredData.count()); } } diff --git a/apache-spark/src/test/java/com/baeldung/differences/rdd/TransformationsUnitTest.java b/apache-spark/src/test/java/com/baeldung/differences/rdd/TransformationsUnitTest.java index 01e7d3adfc..6de407f3b4 100644 --- a/apache-spark/src/test/java/com/baeldung/differences/rdd/TransformationsUnitTest.java +++ b/apache-spark/src/test/java/com/baeldung/differences/rdd/TransformationsUnitTest.java @@ -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 diff --git a/aws-modules/aws-miscellaneous/pom.xml b/aws-modules/aws-miscellaneous/pom.xml index f05764f10a..888a2a561f 100644 --- a/aws-modules/aws-miscellaneous/pom.xml +++ b/aws-modules/aws-miscellaneous/pom.xml @@ -78,6 +78,25 @@ + + org.apache.maven.plugins + maven-dependency-plugin + ${maven-plugins-version} + + + copy + compile + + copy-dependencies + + + + so,dll,dylib + native-libs + + + + @@ -99,6 +118,7 @@ 1.10.L001 0.9.4.0006L 3.0.0 + 3.1.1 \ No newline at end of file diff --git a/aws-modules/aws-s3/pom.xml b/aws-modules/aws-s3/pom.xml index 65ad6f27f8..e7e04782b1 100644 --- a/aws-modules/aws-s3/pom.xml +++ b/aws-modules/aws-s3/pom.xml @@ -20,7 +20,6 @@ aws-java-sdk ${aws-java-sdk.version} - commons-io commons-io @@ -58,7 +57,7 @@ - + 1.11.290 diff --git a/aws-modules/pom.xml b/aws-modules/pom.xml index 4bdffa789a..3c5459d46c 100644 --- a/aws-modules/pom.xml +++ b/aws-modules/pom.xml @@ -19,6 +19,6 @@ aws-miscellaneous aws-reactive aws-s3 - + \ No newline at end of file diff --git a/core-java-modules/README.md b/core-java-modules/README.md index fa77846b45..d07dff8751 100644 --- a/core-java-modules/README.md +++ b/core-java-modules/README.md @@ -4,6 +4,6 @@ This module contains modules about core Java ## Relevant articles: -- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms) - [Understanding the NumberFormatException in Java](https://www.baeldung.com/java-number-format-exception) -- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch) + + diff --git a/core-java-modules/core-java-11-2/README.md b/core-java-modules/core-java-11-2/README.md index 2b0eda8d91..ebd857886d 100644 --- a/core-java-modules/core-java-11-2/README.md +++ b/core-java-modules/core-java-11-2/README.md @@ -11,3 +11,5 @@ This module contains articles about Java 11 core features - [Invoking a SOAP Web Service in Java](https://www.baeldung.com/java-soap-web-service) - [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) diff --git a/core-java-modules/core-java-11-2/src/test/java/com/baeldung/httpclient/ssl/HttpClientSSLBypassUnitTest.java b/core-java-modules/core-java-11-2/src/test/java/com/baeldung/httpclient/ssl/HttpClientSSLBypassUnitTest.java new file mode 100644 index 0000000000..29c1538c85 --- /dev/null +++ b/core-java-modules/core-java-11-2/src/test/java/com/baeldung/httpclient/ssl/HttpClientSSLBypassUnitTest.java @@ -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 response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.FALSE.toString()); + + Assertions.assertEquals(200, response.statusCode()); + } +} diff --git a/core-java-modules/core-java-11-2/src/test/java/com/baeldung/httpclient/ssl/HttpClientSSLUnitTest.java b/core-java-modules/core-java-11-2/src/test/java/com/baeldung/httpclient/ssl/HttpClientSSLUnitTest.java new file mode 100644 index 0000000000..8eddd2d329 --- /dev/null +++ b/core-java-modules/core-java-11-2/src/test/java/com/baeldung/httpclient/ssl/HttpClientSSLUnitTest.java @@ -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 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 response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + + assertEquals(200, response.statusCode()); + } + +} diff --git a/core-java-modules/core-java-collections-2/README.md b/core-java-modules/core-java-collections-2/README.md index e5f6126811..d482ed7773 100644 --- a/core-java-modules/core-java-collections-2/README.md +++ b/core-java-modules/core-java-collections-2/README.md @@ -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) diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/baeldung/collections/iterable/CustomIterableClient.java b/core-java-modules/core-java-collections-2/src/main/java/com/baeldung/collections/iterable/CustomIterableClient.java new file mode 100644 index 0000000000..14f7b18014 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/baeldung/collections/iterable/CustomIterableClient.java @@ -0,0 +1,17 @@ +package com.baeldung.collections.iterable; + +class CustomIterableClient { + + public static void main(String[] args) { + + ShoppingCart 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()); + } + } +} diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/baeldung/collections/iterable/IterableExample.java b/core-java-modules/core-java-collections-2/src/main/java/com/baeldung/collections/iterable/IterableExample.java new file mode 100644 index 0000000000..9110d6a15f --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/baeldung/collections/iterable/IterableExample.java @@ -0,0 +1,32 @@ +package com.baeldung.collections.iterable; + +import java.util.Iterator; +import java.util.List; + +public class IterableExample { + + public void iterateUsingIterator(List numbers) { + Iterator iterator = numbers.iterator(); + while (iterator.hasNext()) { + System.out.println(iterator.next()); + } + } + + public void iterateUsingEnhancedForLoop(List numbers) { + for (Integer number : numbers) { + System.out.println(number); + } + } + + public void iterateUsingForEachLoop(List numbers) { + numbers.forEach(System.out::println); + } + + public void removeElementsUsingIterator(List numbers) { + Iterator iterator = numbers.iterator(); + while (iterator.hasNext()) { + iterator.next(); + iterator.remove(); + } + } +} diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/baeldung/collections/iterable/Product.java b/core-java-modules/core-java-collections-2/src/main/java/com/baeldung/collections/iterable/Product.java new file mode 100644 index 0000000000..b29088f6f0 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/baeldung/collections/iterable/Product.java @@ -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; + } +} diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/baeldung/collections/iterable/ShoppingCart.java b/core-java-modules/core-java-collections-2/src/main/java/com/baeldung/collections/iterable/ShoppingCart.java new file mode 100644 index 0000000000..f1b481da08 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/baeldung/collections/iterable/ShoppingCart.java @@ -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 implements Iterable { + + 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 iterator() { + return new ShoppingCartIterator(); + } + + public class ShoppingCartIterator implements Iterator { + 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(); + } + } + } +} diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/baeldung/collections/iterator/CustomIteratorClient.java b/core-java-modules/core-java-collections-2/src/main/java/com/baeldung/collections/iterator/CustomIteratorClient.java new file mode 100644 index 0000000000..30c8f57c0b --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/baeldung/collections/iterator/CustomIteratorClient.java @@ -0,0 +1,14 @@ +package com.baeldung.collections.iterator; + +import java.util.Iterator; + +class CustomIteratorClient { + + public static void main(String[] args) { + Iterator iterator = Numbers.iterator(); + + while (iterator.hasNext()) { + System.out.println(iterator.next()); + } + } +} diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/baeldung/collections/iterator/Numbers.java b/core-java-modules/core-java-collections-2/src/main/java/com/baeldung/collections/iterator/Numbers.java new file mode 100644 index 0000000000..23b3344c08 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/baeldung/collections/iterator/Numbers.java @@ -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 NUMBER_LIST = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + + private Numbers() { + } + + public static Iterator iterator() { + return new PrimeIterator(); + } + + private static class PrimeIterator implements Iterator { + + 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; + } + } +} diff --git a/core-java-modules/core-java-collections-2/src/test/java/com/baeldung/collections/iterable/IterableUnitTest.java b/core-java-modules/core-java-collections-2/src/test/java/com/baeldung/collections/iterable/IterableUnitTest.java new file mode 100644 index 0000000000..745dcf52b7 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/test/java/com/baeldung/collections/iterable/IterableUnitTest.java @@ -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 getNumbers() { + List numbers = new ArrayList<>(); + numbers.add(10); + numbers.add(20); + numbers.add(30); + numbers.add(40); + return numbers; + } + + @Test + void givenNumbers_whenUsingIterator_thenCorrectSize() { + List numbers = getNumbers(); + IterableExample iterableExample = new IterableExample(); + iterableExample.iterateUsingIterator(numbers); + assertEquals(4, numbers.size()); + } + + @Test + void givenNumbers_whenRemoveElements_thenEmptyList() { + List numbers = getNumbers(); + IterableExample iterableExample = new IterableExample(); + iterableExample.removeElementsUsingIterator(numbers); + assertEquals(0, numbers.size()); + } + + @Test + void givenNumbers_whenIterateUsingEnhancedForLoop_thenCorrectSize() { + List numbers = getNumbers(); + IterableExample iterableExample = new IterableExample(); + iterableExample.iterateUsingEnhancedForLoop(numbers); + assertEquals(4, numbers.size()); + } + + @Test + void givenNumbers_whenIterateUsingForEachLoop_thenCorrectSize() { + List numbers = getNumbers(); + IterableExample iterableExample = new IterableExample(); + iterableExample.iterateUsingForEachLoop(numbers); + assertEquals(4, numbers.size()); + } +} diff --git a/core-java-modules/core-java-collections-4/pom.xml b/core-java-modules/core-java-collections-4/pom.xml index 2193b5118a..aaf63a2b2a 100644 --- a/core-java-modules/core-java-collections-4/pom.xml +++ b/core-java-modules/core-java-collections-4/pom.xml @@ -14,4 +14,16 @@ 0.0.1-SNAPSHOT + + + commons-lang + commons-lang + ${commons-lang.version} + + + + + 2.2 + + \ No newline at end of file diff --git a/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/sorting/Employee.java b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/sorting/Employee.java new file mode 100644 index 0000000000..d41ad54295 --- /dev/null +++ b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/sorting/Employee.java @@ -0,0 +1,72 @@ +package com.baeldung.collections.sorting; + +import java.util.Date; + +public class Employee implements Comparable{ + + 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()); + } +} diff --git a/core-java-modules/core-java-collections-4/src/test/java/com/baeldung/collections/sorting/EmployeeSortingByDateUnitTest.java b/core-java-modules/core-java-collections-4/src/test/java/com/baeldung/collections/sorting/EmployeeSortingByDateUnitTest.java new file mode 100644 index 0000000000..b8acb789a6 --- /dev/null +++ b/core-java-modules/core-java-collections-4/src/test/java/com/baeldung/collections/sorting/EmployeeSortingByDateUnitTest.java @@ -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 employees = new ArrayList<>(); + private List employeesSortedByDateAsc = new ArrayList<>(); + private List 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() { + 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() { + 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() { + 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() { + 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); + } + +} diff --git a/core-java-modules/core-java-collections-list-3/README.md b/core-java-modules/core-java-collections-list-3/README.md index bcc8b3f3ed..6d0a3c7037 100644 --- a/core-java-modules/core-java-collections-list-3/README.md +++ b/core-java-modules/core-java-collections-list-3/README.md @@ -12,4 +12,6 @@ This module contains articles about the Java List collection - [How to Count Duplicate Elements in Arraylist](https://www.baeldung.com/java-count-duplicate-elements-arraylist) - [Finding the Differences Between Two Lists in Java](https://www.baeldung.com/java-lists-difference) - [List vs. ArrayList in Java](https://www.baeldung.com/java-list-vs-arraylist) +- [How to Store HashMap Inside a List](https://www.baeldung.com/java-hashmap-inside-list) +- [Working With a List of Lists in Java](https://www.baeldung.com/java-list-of-lists) - [[<-- Prev]](/core-java-modules/core-java-collections-list-2) diff --git a/core-java-modules/core-java-collections-list-4/README.md b/core-java-modules/core-java-collections-list-4/README.md new file mode 100644 index 0000000000..3a90b3d813 --- /dev/null +++ b/core-java-modules/core-java-collections-list-4/README.md @@ -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) diff --git a/core-java-modules/core-java-collections-list-4/pom.xml b/core-java-modules/core-java-collections-list-4/pom.xml new file mode 100644 index 0000000000..8c1d3a881e --- /dev/null +++ b/core-java-modules/core-java-collections-list-4/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + core-java-collections-list-4 + 0.1.0-SNAPSHOT + core-java-collections-list-4 + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + net.sf.trove4j + trove4j + ${trove4j.version} + + + it.unimi.dsi + fastutil + ${fastutil.version} + + + colt + colt + ${colt.version} + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator.version} + + + + + 3.0.2 + 8.1.0 + 1.2.0 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-4/src/test/java/com/baeldung/list/listoflists/ListOfListsUnitTest.java b/core-java-modules/core-java-collections-list-4/src/test/java/com/baeldung/list/listoflists/ListOfListsUnitTest.java new file mode 100644 index 0000000000..321fa475f6 --- /dev/null +++ b/core-java-modules/core-java-collections-list-4/src/test/java/com/baeldung/list/listoflists/ListOfListsUnitTest.java @@ -0,0 +1,74 @@ +package com.baeldung.list.listoflists; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.Test; + +public class ListOfListsUnitTest { + + private List> getListOfListsFromCsv() throws URISyntaxException, IOException { + + List lines = Files.readAllLines(Paths.get(getClass().getResource("/listoflists/example.csv") + .toURI())); + List> listOfLists = new ArrayList<>(); + + lines.forEach(line -> { + List innerList = new ArrayList<>(Arrays.asList(line.split(", "))); + listOfLists.add(innerList); + }); + return listOfLists; + } + + private void printListOfLists(List> listOfLists) { + System.out.println("\n List of Lists "); + System.out.println("-------------------------------------"); + listOfLists.forEach(innerList -> { + String line = String.join(", ", innerList); + System.out.println(line); + }); + } + + @Test + void givenCsv_whenInitListOfLists_thenGetExpectedResults() throws URISyntaxException, IOException { + List> listOfLists = getListOfListsFromCsv(); + assertThat(listOfLists).hasSize(3); + assertThat(listOfLists.stream() + .map(List::size) + .collect(Collectors.toSet())).hasSize(1) + .containsExactly(4); + printListOfLists(listOfLists); + } + + @Test + void givenListOfLists_whenRemoveElementFromInnerLists_thenGetExpectedResults() throws URISyntaxException, IOException { + List> listOfLists = getListOfListsFromCsv(); + + listOfLists.forEach(innerList -> innerList.remove("Delete Me")); + assertThat(listOfLists.stream() + .map(List::size) + .collect(Collectors.toSet())).hasSize(1) + .containsExactly(3); + + printListOfLists(listOfLists); + } + + @Test + void givenListOfLists_whenAddNewInnerList_thenGetExpectedResults() throws URISyntaxException, IOException { + List> listOfLists = getListOfListsFromCsv(); + List newList = new ArrayList<>(Arrays.asList("Slack", "Zoom", "Microsoft Teams", "Telegram")); + listOfLists.add(2, newList); + + assertThat(listOfLists).hasSize(4); + assertThat(listOfLists.get(2)).containsExactly("Slack", "Zoom", "Microsoft Teams", "Telegram"); + printListOfLists(listOfLists); + } +} diff --git a/core-java-modules/core-java-collections-list-4/src/test/resources/listoflists/example.csv b/core-java-modules/core-java-collections-list-4/src/test/resources/listoflists/example.csv new file mode 100644 index 0000000000..e275848e19 --- /dev/null +++ b/core-java-modules/core-java-collections-list-4/src/test/resources/listoflists/example.csv @@ -0,0 +1,3 @@ +Linux, Microsoft Windows, Mac OS, Delete Me +Kotlin, Delete Me, Java, Python +Delete Me, Mercurial, Git, Subversion \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-advanced-4/README.md b/core-java-modules/core-java-concurrency-advanced-4/README.md index 808db89b12..d9207644b3 100644 --- a/core-java-modules/core-java-concurrency-advanced-4/README.md +++ b/core-java-modules/core-java-concurrency-advanced-4/README.md @@ -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) diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/setvslazyset/Application.java b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/setvslazyset/Application.java new file mode 100644 index 0000000000..37424147a7 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/setvslazyset/Application.java @@ -0,0 +1,35 @@ +package com.baeldung.setvslazyset; + +import java.util.concurrent.atomic.AtomicInteger; + +public class Application { + + AtomicInteger atomic = new AtomicInteger(0); + + public static void main(String[] args) { + Application app = new Application(); + new Thread(() -> { + for (int i = 0; i < 10; i++) { + //app.atomic.set(i); + app.atomic.lazySet(i); + System.out.println("Set: " + i); + try { + Thread.sleep(100); + } catch (InterruptedException e) {} + } + }).start(); + + new Thread(() -> { + for (int i = 0; i < 10; i++) { + synchronized (app.atomic) { + int counter = app.atomic.get(); + System.out.println("Get: " + counter); + } + try { + Thread.sleep(100); + } catch (InterruptedException e) {} + } + }).start(); + } + +} diff --git a/core-java-modules/core-java-exceptions-3/pom.xml b/core-java-modules/core-java-exceptions-3/pom.xml index 455f769757..7eaa57edf1 100644 --- a/core-java-modules/core-java-exceptions-3/pom.xml +++ b/core-java-modules/core-java-exceptions-3/pom.xml @@ -32,8 +32,8 @@ 3.8.1 - - + + diff --git a/core-java-modules/core-java-exceptions-4/pom.xml b/core-java-modules/core-java-exceptions-4/pom.xml index cc81fdc40b..e9a2d05180 100644 --- a/core-java-modules/core-java-exceptions-4/pom.xml +++ b/core-java-modules/core-java-exceptions-4/pom.xml @@ -32,8 +32,8 @@ 3.8.1 - - + + diff --git a/core-java-modules/core-java-exceptions/README.md b/core-java-modules/core-java-exceptions/README.md index 5f47aa69fb..b74ede51e8 100644 --- a/core-java-modules/core-java-exceptions/README.md +++ b/core-java-modules/core-java-exceptions/README.md @@ -13,4 +13,5 @@ This module contains articles about core java exceptions - [The StackOverflowError in Java](https://www.baeldung.com/java-stack-overflow-error) - [Checked and Unchecked Exceptions in Java](https://www.baeldung.com/java-checked-unchecked-exceptions) - [Common Java Exceptions](https://www.baeldung.com/java-common-exceptions) +- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch) - [[Next -->]](/core-java-modules/core-java-exceptions-2) \ No newline at end of file diff --git a/core-java-modules/core-java-httpclient/README.md b/core-java-modules/core-java-httpclient/README.md new file mode 100644 index 0000000000..24ff7d9941 --- /dev/null +++ b/core-java-modules/core-java-httpclient/README.md @@ -0,0 +1,6 @@ +## Java HttpClient + +This module contains articles about Java HttpClient + +### Relevant articles +- TODO diff --git a/core-java-modules/core-java-httpclient/pom.xml b/core-java-modules/core-java-httpclient/pom.xml new file mode 100644 index 0000000000..57b23e96c1 --- /dev/null +++ b/core-java-modules/core-java-httpclient/pom.xml @@ -0,0 +1,58 @@ + + + 4.0.0 + core-java-httpclient + 0.1.0-SNAPSHOT + core-java-httpclient + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../pom.xml + + + + + org.mock-server + mockserver-netty + ${mockserver.version} + + + org.mock-server + mockserver-client-java + ${mockserver.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source.version} + ${maven.compiler.target.version} + + + + + + + 11 + 11 + 3.22.0 + 5.11.2 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-httpclient/src/main/java/com/baeldung/httpclient/HttpClientPost.java b/core-java-modules/core-java-httpclient/src/main/java/com/baeldung/httpclient/HttpClientPost.java new file mode 100644 index 0000000000..d08a7bf183 --- /dev/null +++ b/core-java-modules/core-java-httpclient/src/main/java/com/baeldung/httpclient/HttpClientPost.java @@ -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 sendSynchronousPost(String serviceUrl) throws IOException, InterruptedException { + HttpClient client = HttpClient.newHttpClient(); + + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(serviceUrl)) + .POST(HttpRequest.BodyPublishers.noBody()) + .build(); + + HttpResponse response = client + .send(request, HttpResponse.BodyHandlers.ofString()); + + return response; + } + + public static CompletableFuture> sendAsynchronousPost(String serviceUrl) { + HttpClient client = HttpClient.newHttpClient(); + + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(serviceUrl)) + .POST(HttpRequest.BodyPublishers.noBody()) + .build(); + + CompletableFuture> futureResponse = client + .sendAsync(request, HttpResponse.BodyHandlers.ofString()); + + return futureResponse; + } + + public static List>> sendConcurrentPost(List serviceUrls) { + HttpClient client = HttpClient.newHttpClient(); + + List>> 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 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 response = client + .send(request, HttpResponse.BodyHandlers.ofString()); + + return response; + } + + public static HttpResponse 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 response = client + .send(request, HttpResponse.BodyHandlers.ofString()); + + return response; + } + + public static HttpResponse 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 response = client + .send(request, HttpResponse.BodyHandlers.ofString()); + + return response; + } + + public static HttpResponse sendPostWithFormData(String serviceUrl) throws IOException, InterruptedException { + HttpClient client = HttpClient.newHttpClient(); + + Map 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 response = client + .send(request, HttpResponse.BodyHandlers.ofString()); + + return response; + } + + public static HttpResponse 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 response = client + .send(request, HttpResponse.BodyHandlers.ofString()); + + return response; + } + + private static String getFormDataAsString(Map formData) { + StringBuilder formBodyBuilder = new StringBuilder(); + for (Map.Entry 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(); + } + +} diff --git a/core-java-modules/core-java-httpclient/src/test/java/com/baeldung/httpclient/HttpClientPostUnitTest.java b/core-java-modules/core-java-httpclient/src/test/java/com/baeldung/httpclient/HttpClientPostUnitTest.java new file mode 100644 index 0000000000..b43cf08649 --- /dev/null +++ b/core-java-modules/core-java-httpclient/src/test/java/com/baeldung/httpclient/HttpClientPostUnitTest.java @@ -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 response = HttpClientPost.sendSynchronousPost(serviceUrl); + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.body()).isEqualTo("{\"message\":\"ok\"}"); + } + + @Test + void givenAsyncPostRequest_whenServerIsAvailable_thenOkStatusIsReceived() throws ExecutionException, InterruptedException { + CompletableFuture> futureResponse = HttpClientPost.sendAsynchronousPost(serviceUrl); + HttpResponse response = futureResponse.get(); + + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.body()).isEqualTo("{\"message\":\"ok\"}"); + } + + @Test + void givenConcurrentPostRequests_whenServerIsAvailable_thenOkStatusIsReceived() throws ExecutionException, InterruptedException { + List>> completableFutures = HttpClientPost + .sendConcurrentPost(List.of(serviceUrl, serviceUrl)); + + CompletableFuture>> combinedFutures = CompletableFuture + .allOf(completableFutures.toArray(new CompletableFuture[0])) + .thenApply(future -> + completableFutures.stream() + .map(CompletableFuture::join) + .collect(Collectors.toList())); + + List> 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 response = HttpClientPost.sendPostWithAuthClient(serviceUrl); + + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.body()).isEqualTo("{\"message\":\"ok\"}"); + } + + @Test + void givenPostRequestWithAuthHeader_whenServerIsAvailable_thenOkStatusIsReceived() throws IOException, InterruptedException { + HttpResponse response = HttpClientPost.sendPostWithAuthHeader(serviceUrl); + + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.body()).isEqualTo("{\"message\":\"ok\"}"); + } + + @Test + void givenPostRequestWithJsonBody_whenServerIsAvailable_thenOkStatusIsReceived() throws IOException, InterruptedException { + HttpResponse response = HttpClientPost.sendPostWithJsonBody(serviceUrl); + + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.body()).isEqualTo("{\"message\":\"ok\"}"); + } + + @Test + void givenPostRequestWithFormData_whenServerIsAvailable_thenOkStatusIsReceived() throws IOException, InterruptedException { + HttpResponse 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 lines = Arrays.asList("1", "2", "3"); + Files.write(file, lines); + + HttpResponse response = HttpClientPost.sendPostWithFileData(serviceUrl, file); + + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.body()).isEqualTo("{\"message\":\"ok\"}"); + } + +} diff --git a/core-java-modules/core-java-httpclient/src/test/java/com/baeldung/httpclient/PostRequestMockServer.java b/core-java-modules/core-java-httpclient/src/test/java/com/baeldung/httpclient/PostRequestMockServer.java new file mode 100644 index 0000000000..fa594897a3 --- /dev/null +++ b/core-java-modules/core-java-httpclient/src/test/java/com/baeldung/httpclient/PostRequestMockServer.java @@ -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(); + } + } + +} diff --git a/core-java-modules/core-java-io-4/README.md b/core-java-modules/core-java-io-4/README.md index 65a46eeed3..c05618afbd 100644 --- a/core-java-modules/core-java-io-4/README.md +++ b/core-java-modules/core-java-io-4/README.md @@ -9,4 +9,5 @@ This module contains articles about core Java input and output (IO) - [SequenceInputStream Class in Java](https://www.baeldung.com/java-sequenceinputstream) - [Read a File Into a Map in Java](https://www.baeldung.com/java-read-file-into-map) - [Read User Input Until a Condition is Met](https://www.baeldung.com/java-read-input-until-condition) +- [Java Scanner.skip method with examples](https://www.baeldung.com/java-scanner-skip) - [[<-- Prev]](/core-java-modules/core-java-io-3) diff --git a/core-java-modules/core-java-io-4/src/test/java/com/baeldung/scanner/ScannerUnitTest.java b/core-java-modules/core-java-io-4/src/test/java/com/baeldung/scanner/ScannerUnitTest.java new file mode 100644 index 0000000000..cb6ce5fb2d --- /dev/null +++ b/core-java-modules/core-java-io-4/src/test/java/com/baeldung/scanner/ScannerUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.scanner; + +import org.junit.Test; + +import java.util.*; +import java.util.regex.*; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class ScannerUnitTest { + @Test public void givenScannerWithPattern_thenSkipUsingPattern() { + String str = "Java scanner skip tutorial"; + // Instantiates Scanner + Scanner sc = new Scanner(str); + // By using skip(Pattern) method is to skip that meets the given pattern + sc.skip(Pattern.compile(".ava")); + + assertEquals(" scanner skip tutorial", sc.nextLine()); + // Scanner closed + sc.close(); + } + + @Test public void givenScannerWithString_thenSkipUsingStringPattern() { + String str = "Java scanner skip tutorial"; + // Instantiates Scanner + Scanner sc = new Scanner(str); + // By using skip(String) method is to skip that meets the given + // pattern constructed from the given String + sc.skip("Java"); + + assertEquals(" scanner skip tutorial", sc.nextLine()); + // Scanner closed + sc.close(); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lambdas/README.md b/core-java-modules/core-java-lambdas/README.md index 832d4783f2..53414eb14c 100644 --- a/core-java-modules/core-java-lambdas/README.md +++ b/core-java-modules/core-java-lambdas/README.md @@ -6,4 +6,5 @@ - [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) - [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions) - [Method References in Java](https://www.baeldung.com/java-method-references) -- [The Double Colon Operator in Java 8](https://www.baeldung.com/java-8-double-colon-operator) \ No newline at end of file +- [The Double Colon Operator in Java 8](https://www.baeldung.com/java-8-double-colon-operator) +- [Serialize a Lambda in Java](https://www.baeldung.com/java-serialize-lambda) diff --git a/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/java8/lambda/serialization/NotSerializableLambdaExpression.java b/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/java8/lambda/serialization/NotSerializableLambdaExpression.java new file mode 100644 index 0000000000..38f87e4ba9 --- /dev/null +++ b/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/java8/lambda/serialization/NotSerializableLambdaExpression.java @@ -0,0 +1,8 @@ +package com.baeldung.java8.lambda.serialization; + +public class NotSerializableLambdaExpression { + public static Object getLambdaExpressionObject() { + Runnable r = () -> System.out.println("please serialize this message"); + return r; + } +} diff --git a/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/java8/lambda/serialization/SerializableLambdaExpression.java b/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/java8/lambda/serialization/SerializableLambdaExpression.java new file mode 100644 index 0000000000..74541013bb --- /dev/null +++ b/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/java8/lambda/serialization/SerializableLambdaExpression.java @@ -0,0 +1,10 @@ +package com.baeldung.java8.lambda.serialization; + +import java.io.Serializable; + +public class SerializableLambdaExpression { + public static Object getLambdaExpressionObject() { + Runnable r = (Runnable & Serializable) () -> System.out.println("please serialize this message"); + return r; + } +} diff --git a/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/lambda/serialization/LambdaSerializationUnitTest.java b/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/lambda/serialization/LambdaSerializationUnitTest.java new file mode 100644 index 0000000000..bb71e3bdb9 --- /dev/null +++ b/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/lambda/serialization/LambdaSerializationUnitTest.java @@ -0,0 +1,77 @@ +package com.baeldung.java8.lambda.serialization; + +import org.junit.Test; + +import java.io.*; +import java.nio.file.Files; +import java.util.function.Consumer; +import java.util.function.Function; + +import static org.junit.Assert.assertTrue; + +public class LambdaSerializationUnitTest { + @Test(expected = NotSerializableException.class) + public void givenRunnable_whenNoCapturing_thenSerializationFailed() throws IOException, ClassNotFoundException { + Object obj = NotSerializableLambdaExpression.getLambdaExpressionObject(); + writeAndReadObject(obj, Runnable.class); + } + + @Test + public void givenIntersectionType_whenNoCapturing_thenSerializationSuccess() throws IOException, ClassNotFoundException { + Object obj = SerializableLambdaExpression.getLambdaExpressionObject(); + writeAndReadObject(obj, Runnable.class); + } + + @Test + public void givenSerializableRunnable_whenNoCapturing_thenSerializationSuccess() throws IOException, ClassNotFoundException { + SerializableRunnable obj = () -> System.out.println("please serialize this message"); + writeAndReadObject(obj, SerializableRunnable.class); + } + + @Test + public void givenSerializableFunction_whenNoCapturing_thenSerializationSuccess() throws IOException, ClassNotFoundException { + SerializableFunction obj = message -> String.format("Hello %s", message); + writeAndReadObject(obj, SerializableFunction.class); + } + + @Test + public void givenSerializableConsumer_whenNoCapturing_thenSerializationSuccess() throws IOException, ClassNotFoundException { + SerializableConsumer obj = message -> System.out.println(message); + writeAndReadObject(obj, SerializableConsumer.class); + } + + @Test(expected = NotSerializableException.class) + public void givenSerializableConsumer_whenCapturingNotSerializable_thenSerializationFailed() throws IOException, ClassNotFoundException { + SerializableConsumer obj = System.out::println; + writeAndReadObject(obj, SerializableConsumer.class); + } + + private void writeAndReadObject(Object obj, Class clazz) throws IOException, ClassNotFoundException { + File file = Files.createTempFile("lambda", "ser").toFile(); + try ( + FileOutputStream fos = new FileOutputStream(file); + ObjectOutputStream oos = new ObjectOutputStream(fos) + ) { + oos.writeObject(obj); + } + + try ( + FileInputStream fis = new FileInputStream(file); + ObjectInputStream ois = new ObjectInputStream(fis) + ) { + Object newObj = ois.readObject(); + boolean isInstance = clazz.isInstance(newObj); + + assertTrue(isInstance); + } + } + + interface SerializableRunnable extends Runnable, Serializable { + } + + interface SerializableFunction extends Function, Serializable { + } + + interface SerializableConsumer extends Consumer, Serializable { + } +} diff --git a/core-java-modules/core-java-lang-4/src/main/java/com/baeldung/employee/EmployeeVO.java b/core-java-modules/core-java-lang-4/src/main/java/com/baeldung/employee/EmployeeVO.java index 7a1775f79d..3d2c61aa3d 100644 --- a/core-java-modules/core-java-lang-4/src/main/java/com/baeldung/employee/EmployeeVO.java +++ b/core-java-modules/core-java-lang-4/src/main/java/com/baeldung/employee/EmployeeVO.java @@ -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 diff --git a/core-java-modules/core-java-lang-5/README.md b/core-java-modules/core-java-lang-5/README.md new file mode 100644 index 0000000000..8920e9c231 --- /dev/null +++ b/core-java-modules/core-java-lang-5/README.md @@ -0,0 +1,7 @@ +## Core Java Lang (Part 5) + +This module contains articles about core features in the Java language + +### Relevant Articles: + +- [Difference Between == and equals() in Java](https://www.baeldung.com/java-equals-method-operator-difference) diff --git a/core-java-modules/core-java-lang-5/pom.xml b/core-java-modules/core-java-lang-5/pom.xml new file mode 100644 index 0000000000..6d3771bd31 --- /dev/null +++ b/core-java-modules/core-java-lang-5/pom.xml @@ -0,0 +1,27 @@ + + + 4.0.0 + core-java-lang-5 + 0.1.0-SNAPSHOT + core-java-lang-5 + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + + core-java-lang-5 + + + src/main/resources + true + + + + + \ No newline at end of file diff --git a/core-java-modules/core-java-lang-5/src/test/java/com/baeldung/nullchecks/NullChecksUnitTest.java b/core-java-modules/core-java-lang-5/src/test/java/com/baeldung/nullchecks/NullChecksUnitTest.java new file mode 100644 index 0000000000..12b3db734d --- /dev/null +++ b/core-java-modules/core-java-lang-5/src/test/java/com/baeldung/nullchecks/NullChecksUnitTest.java @@ -0,0 +1,125 @@ +package com.baeldung.nullchecks; + +import org.junit.Test; + +import java.util.Objects; + +import static org.junit.jupiter.api.Assertions.*; + +public class NullChecksUnitTest { + + @Test + public void whenReferenceEqualityOnPrimitives_thenCompareValues() { + int a = 10; + int b = 15; + int c = 10; + int d = a; + + // different values check + assertFalse(a == b); + + // same values check + assertTrue(a == c); + + // same references check + assertTrue(a == d); + } + + @Test + public void whenReferenceEqualityOnObjects_thenCompareReferences() { + Person a = new Person("Bob", 20); + Person b = new Person("Mike", 40); + Person c = new Person("Bob", 20); + Person d = a; + Person e = null; + + // different values check + assertFalse(a == b); + + // same values check + assertFalse(a == c); + + // same references check + assertTrue(a == d); + + // same references check - for nulls + assertTrue(e == null); + } + + @Test + public void whenValueEqualityOnPrimitives_thenCompareValues() { + int a = 10; + Integer b = a; + + assertTrue(b.equals(10)); + } + + @Test + public void whenValueEqualityOnObjects_thenCompareValues() { + Person a = new Person("Bob", 20); + Person b = new Person("Mike", 40); + Person c = new Person("Bob", 20); + Person d = a; + Person e = null; + + // different values check + assertFalse(a.equals(b)); + + // same values check + assertTrue(a.equals(c)); + + // same references check + assertTrue(a.equals(d)); + + // null checks + assertFalse(a.equals(e)); + assertThrows(NullPointerException.class, () -> e.equals(a)); + + // null checks fixed + assertFalse(e != null && e.equals(a)); + + // using Objects.equals + assertFalse(Objects.equals(e, a)); + assertTrue(Objects.equals(null, e)); + + } + + private class Person { + private String name; + private int age; + + public Person(String name, int age) { + this.name = name; + this.age = age; + } + + 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; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Person person = (Person) o; + return age == person.age && Objects.equals(name, person.name); + } + + @Override + public int hashCode() { + return Objects.hash(name, age); + } + } +} diff --git a/core-java-modules/core-java-lang-math-3/README.md b/core-java-modules/core-java-lang-math-3/README.md index 1dd3a3c7e0..3ddaddae39 100644 --- a/core-java-modules/core-java-lang-math-3/README.md +++ b/core-java-modules/core-java-lang-math-3/README.md @@ -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) diff --git a/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/Direction.java b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/Direction.java new file mode 100644 index 0000000000..05b398371c --- /dev/null +++ b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/Direction.java @@ -0,0 +1,22 @@ +package com.baeldung.enums.randomenum; + +import java.util.Random; + +/** + * Represents directions. + */ +public enum Direction { + EAST, WEST, SOUTH, NORTH; + + private static final Random PRNG = new Random(); + + /** + * Generate a random direction. + * + * @return a random direction + */ + public static Direction randomDirection() { + Direction[] directions = values(); + return directions[PRNG.nextInt(directions.length)]; + } +} diff --git a/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/RandomEnumGenerator.java b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/RandomEnumGenerator.java new file mode 100644 index 0000000000..33d793062d --- /dev/null +++ b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/RandomEnumGenerator.java @@ -0,0 +1,17 @@ +package com.baeldung.enums.randomenum; + +import java.util.Random; + +public class RandomEnumGenerator> { + + private static final Random PRNG = new Random(); + private final T[] values; + + public RandomEnumGenerator(Class e) { + values = e.getEnumConstants(); + } + + public T randomEnum() { + return values[PRNG.nextInt(values.length)]; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-types-2/src/test/java/com/baeldung/enums/randomenum/RandomEnumUnitTest.java b/core-java-modules/core-java-lang-oop-types-2/src/test/java/com/baeldung/enums/randomenum/RandomEnumUnitTest.java new file mode 100644 index 0000000000..76b4bf1e74 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-types-2/src/test/java/com/baeldung/enums/randomenum/RandomEnumUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.enums.randomenum; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class RandomEnumUnitTest { + + @Test + public void givenEnumType_whenUsingStaticMethod_valueIsRandomlyGenerated() { + Direction direction = Direction.randomDirection(); + assertThat(direction).isNotNull(); + assertThat(direction instanceof Direction); + } + + @Test + public void givenEnumType_whenGeneratingRandomValue_valueIsOfClassAndNotNull() { + RandomEnumGenerator reg = new RandomEnumGenerator(Direction.class); + Object direction = reg.randomEnum(); + assertThat(direction).isNotNull(); + assertThat(direction instanceof Direction); + } +} diff --git a/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java b/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java index 987a69582f..0aba09a539 100644 --- a/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java +++ b/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java @@ -19,7 +19,7 @@ public class FileDownloadIntegrationTest { static String FILE_URL = "https://s3.amazonaws.com/baeldung.com/Do+JSON+with+Jackson+by+Baeldung.pdf"; static String FILE_NAME = "file.dat"; - static String FILE_MD5_HASH = "c959feb066b37f5c4f0e0f45bbbb4f86"; + static String FILE_MD5_HASH = "753197aa27f162faa3e3c2e48ee5eb07"; @Test public void givenJavaIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException { diff --git a/core-java-modules/core-java-networking-3/README.md b/core-java-modules/core-java-networking-3/README.md index 82e75820ba..21f939b43e 100644 --- a/core-java-modules/core-java-networking-3/README.md +++ b/core-java-modules/core-java-networking-3/README.md @@ -10,4 +10,5 @@ This module contains articles about networking in Java - [Find Whether an IP Address Is in the Specified Range or Not in Java](https://www.baeldung.com/java-check-ip-address-range) - [Find the IP Address of a Client Connected to a Server](https://www.baeldung.com/java-client-get-ip-address) - [Unix Domain Socket in Java 16](https://www.baeldung.com/java-unix-domain-socket) +- [Get the IP Address of the Current Machine Using Java](https://www.baeldung.com/java-get-ip-address) - [[<-- Prev]](/core-java-modules/core-java-networking-2) diff --git a/core-java-modules/core-java-networking-3/src/main/java/com/baeldung/iplookup/IPAddressLookup.java b/core-java-modules/core-java-networking-3/src/main/java/com/baeldung/iplookup/IPAddressLookup.java new file mode 100644 index 0000000000..30ad5a503d --- /dev/null +++ b/core-java-modules/core-java-networking-3/src/main/java/com/baeldung/iplookup/IPAddressLookup.java @@ -0,0 +1,50 @@ +package com.baeldung.iplookup; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketException; +import java.net.URL; +import java.net.UnknownHostException; + +public class IPAddressLookup { + public static void main(String[] args) { + System.out.println("UDP connection IP lookup: " + getLocalIpAddressUdp()); + System.out.println("Socket connection IP lookup: " + getLocalIpAddressSocket()); + System.out.println("AWS connection IP lookup: " + getPublicIpAddressAws()); + } + + public static String getLocalIpAddressUdp() { + try (final DatagramSocket datagramSocket = new DatagramSocket()) { + datagramSocket.connect(InetAddress.getByName("8.8.8.8"), 12345); + return datagramSocket.getLocalAddress().getHostAddress(); + } catch (SocketException | UnknownHostException exception) { + throw new RuntimeException(exception); + } + } + + public static String getLocalIpAddressSocket() { + try (Socket socket = new Socket()) { + socket.connect(new InetSocketAddress("google.com", 80)); + return socket.getLocalAddress().getHostAddress(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static String getPublicIpAddressAws() { + try { + String urlString = "http://checkip.amazonaws.com/"; + URL url = new URL(urlString); + try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) { + return br.readLine(); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/core-java-modules/core-java-regex-2/README.md b/core-java-modules/core-java-regex-2/README.md index 6dafc74d41..453e2cc419 100644 --- a/core-java-modules/core-java-regex-2/README.md +++ b/core-java-modules/core-java-regex-2/README.md @@ -4,4 +4,5 @@ - [Lookahead and Lookbehind in Java Regex](https://www.baeldung.com/java-regex-lookahead-lookbehind) - [Converting Camel Case and Title Case to Words in Java](https://www.baeldung.com/java-camel-case-title-case-to-words) - [How to Use Regular Expressions to Replace Tokens in Strings in Java](https://www.baeldung.com/java-regex-token-replacement) -- More articles: [[<-- prev]](/core-java-modules/core-java-regex) \ No newline at end of file +- [Creating a Java Array from Regular Expression Matches](https://www.baeldung.com/java-array-regex-matches) +- More articles: [[<-- prev]](/core-java-modules/core-java-regex) diff --git a/core-java-modules/core-java-uuid/pom.xml b/core-java-modules/core-java-uuid/pom.xml index 28519a1a68..7d851292f5 100644 --- a/core-java-modules/core-java-uuid/pom.xml +++ b/core-java-modules/core-java-uuid/pom.xml @@ -35,7 +35,6 @@ true - org.apache.maven.plugins diff --git a/core-java-modules/core-java/README.md b/core-java-modules/core-java/README.md index a75805e0c2..087c5d356e 100644 --- a/core-java-modules/core-java/README.md +++ b/core-java-modules/core-java/README.md @@ -1,9 +1,11 @@ ## Core Java Cookbooks and Examples ### Relevant Articles: + - [Getting Started with Java Properties](http://www.baeldung.com/java-properties) - [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency) - [Compiling Java *.class Files with javac](http://www.baeldung.com/javac) - [Introduction to Javadoc](http://www.baeldung.com/javadoc) - [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle) - [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties) +- [Illegal Character Compilation Error](https://www.baeldung.com/java-illegal-character-error) diff --git a/core-java-modules/core-java/pom.xml b/core-java-modules/core-java/pom.xml index bb19b525d0..87abe6c007 100644 --- a/core-java-modules/core-java/pom.xml +++ b/core-java-modules/core-java/pom.xml @@ -59,6 +59,16 @@ spring-core ${spring.core.version} + + commons-io + commons-io + ${commons-io.version} + + + com.google.gdata + core + ${gdata.version} + @@ -183,6 +193,7 @@ 1.8 1.8 4.3.20.RELEASE + 1.47.1 \ No newline at end of file diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/illegalcharacter/IllegalCharacterUnitTest.java b/core-java-modules/core-java/src/test/java/com/baeldung/illegalcharacter/IllegalCharacterUnitTest.java new file mode 100644 index 0000000000..4a08daa271 --- /dev/null +++ b/core-java-modules/core-java/src/test/java/com/baeldung/illegalcharacter/IllegalCharacterUnitTest.java @@ -0,0 +1,79 @@ +package com.baeldung.illegalcharacter; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.util.Objects; + +import org.apache.commons.io.ByteOrderMark; +import org.apache.commons.io.input.BOMInputStream; +import org.junit.Test; + +import com.google.gdata.util.io.base.UnicodeReader; + +public class IllegalCharacterUnitTest { + + final String RESOURCE_FILE_NAME = "bom-file.txt"; + final InputStream ioStream = this.getClass() + .getClassLoader() + .getResourceAsStream(RESOURCE_FILE_NAME); + final String expected = "Hello world with BOM."; + + @Test + public void whenInputFileHasBOM_thenUseInputStream() throws IOException { + String line; + String actual = ""; + + try (BufferedReader br = new BufferedReader(new InputStreamReader(ioStream))) { + while ((line = br.readLine()) != null) { + actual += line; + } + } + + assertNotEquals(expected, actual); + } + + @Test + public void whenInputFileHasBOM_thenUseInputStreamWithReplace() throws IOException { + String line; + String actual = ""; + + try (BufferedReader br = new BufferedReader(new InputStreamReader(Objects.requireNonNull(ioStream)))) { + while ((line = br.readLine()) != null) { + actual += line.replace("\uFEFF", ""); + } + } + + assertEquals(expected, actual); + } + + @Test + public void whenInputFileHasBOM_thenUseBOMInputStream() throws IOException { + String line; + String actual = ""; + + try (BufferedReader br = new BufferedReader(new InputStreamReader(new BOMInputStream(ioStream, false, ByteOrderMark.UTF_8, ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_32BE, ByteOrderMark.UTF_32LE)))) { + while ((line = br.readLine()) != null) { + actual += line; + } + } + + assertEquals(expected, actual); + } + + @Test + public void whenInputFileHasBOM_thenUseGoogleGdata() throws IOException { + char[] actual = new char[21]; + + try (Reader r = new UnicodeReader(ioStream, null)) { + r.read(actual); + } + + assertEquals(expected, String.valueOf(actual)); + } +} diff --git a/core-java-modules/core-java/src/test/resources/bom-file.txt b/core-java-modules/core-java/src/test/resources/bom-file.txt new file mode 100644 index 0000000000..b2037fded6 --- /dev/null +++ b/core-java-modules/core-java/src/test/resources/bom-file.txt @@ -0,0 +1 @@ +Hello world with BOM. \ No newline at end of file diff --git a/java-collections-conversions-2/README.md b/core-java-modules/java-collections-conversions-2/README.md similarity index 100% rename from java-collections-conversions-2/README.md rename to core-java-modules/java-collections-conversions-2/README.md diff --git a/java-collections-conversions-2/pom.xml b/core-java-modules/java-collections-conversions-2/pom.xml similarity index 85% rename from java-collections-conversions-2/pom.xml rename to core-java-modules/java-collections-conversions-2/pom.xml index 9f8ef7addc..510921c35e 100644 --- a/java-collections-conversions-2/pom.xml +++ b/core-java-modules/java-collections-conversions-2/pom.xml @@ -9,10 +9,9 @@ jar - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../parent-java @@ -29,7 +28,7 @@ io.vavr vavr - 0.10.3 + ${vavr.version} @@ -43,4 +42,8 @@ + + 0.10.3 + + \ No newline at end of file diff --git a/java-collections-conversions-2/src/main/java/com/baeldung/convertlisttomap/ListToMapConverter.java b/core-java-modules/java-collections-conversions-2/src/main/java/com/baeldung/convertlisttomap/ListToMapConverter.java similarity index 100% rename from java-collections-conversions-2/src/main/java/com/baeldung/convertlisttomap/ListToMapConverter.java rename to core-java-modules/java-collections-conversions-2/src/main/java/com/baeldung/convertlisttomap/ListToMapConverter.java diff --git a/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/MapperUtil.java b/core-java-modules/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/MapperUtil.java similarity index 100% rename from java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/MapperUtil.java rename to core-java-modules/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/MapperUtil.java diff --git a/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/User.java b/core-java-modules/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/User.java similarity index 100% rename from java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/User.java rename to core-java-modules/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/User.java diff --git a/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserDTO.java b/core-java-modules/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserDTO.java similarity index 100% rename from java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserDTO.java rename to core-java-modules/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserDTO.java diff --git a/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserList.java b/core-java-modules/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserList.java similarity index 100% rename from java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserList.java rename to core-java-modules/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserList.java diff --git a/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserListDTO.java b/core-java-modules/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserListDTO.java similarity index 100% rename from java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserListDTO.java rename to core-java-modules/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserListDTO.java diff --git a/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UsersListConverter.java b/core-java-modules/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UsersListConverter.java similarity index 100% rename from java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UsersListConverter.java rename to core-java-modules/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UsersListConverter.java diff --git a/java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java b/core-java-modules/java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java similarity index 100% rename from java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java rename to core-java-modules/java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java diff --git a/java-collections-conversions-2/src/test/java/com/baeldung/convertarraytostring/ArrayToStringUnitTest.java b/core-java-modules/java-collections-conversions-2/src/test/java/com/baeldung/convertarraytostring/ArrayToStringUnitTest.java similarity index 100% rename from java-collections-conversions-2/src/test/java/com/baeldung/convertarraytostring/ArrayToStringUnitTest.java rename to core-java-modules/java-collections-conversions-2/src/test/java/com/baeldung/convertarraytostring/ArrayToStringUnitTest.java diff --git a/java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java b/core-java-modules/java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java similarity index 100% rename from java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java rename to core-java-modules/java-collections-conversions-2/src/test/java/com/baeldung/convertlisttomap/ListToMapUnitTest.java diff --git a/java-collections-conversions-2/src/test/java/com/baeldung/modelmapper/UsersListMappingUnitTest.java b/core-java-modules/java-collections-conversions-2/src/test/java/com/baeldung/modelmapper/UsersListMappingUnitTest.java similarity index 100% rename from java-collections-conversions-2/src/test/java/com/baeldung/modelmapper/UsersListMappingUnitTest.java rename to core-java-modules/java-collections-conversions-2/src/test/java/com/baeldung/modelmapper/UsersListMappingUnitTest.java diff --git a/java-collections-conversions-2/src/test/java/com/baeldung/setiteration/SetIteration.java b/core-java-modules/java-collections-conversions-2/src/test/java/com/baeldung/setiteration/SetIteration.java similarity index 100% rename from java-collections-conversions-2/src/test/java/com/baeldung/setiteration/SetIteration.java rename to core-java-modules/java-collections-conversions-2/src/test/java/com/baeldung/setiteration/SetIteration.java diff --git a/java-collections-conversions/README.md b/core-java-modules/java-collections-conversions/README.md similarity index 100% rename from java-collections-conversions/README.md rename to core-java-modules/java-collections-conversions/README.md diff --git a/java-collections-conversions/pom.xml b/core-java-modules/java-collections-conversions/pom.xml similarity index 90% rename from java-collections-conversions/pom.xml rename to core-java-modules/java-collections-conversions/pom.xml index 7f5ba38e3e..2751e0100a 100644 --- a/java-collections-conversions/pom.xml +++ b/core-java-modules/java-collections-conversions/pom.xml @@ -9,10 +9,9 @@ jar - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../parent-java diff --git a/java-collections-conversions/src/main/java/com/baeldung/convertToMap/Book.java b/core-java-modules/java-collections-conversions/src/main/java/com/baeldung/convertToMap/Book.java similarity index 100% rename from java-collections-conversions/src/main/java/com/baeldung/convertToMap/Book.java rename to core-java-modules/java-collections-conversions/src/main/java/com/baeldung/convertToMap/Book.java diff --git a/java-collections-conversions/src/main/java/com/baeldung/convertToMap/ConvertToMap.java b/core-java-modules/java-collections-conversions/src/main/java/com/baeldung/convertToMap/ConvertToMap.java similarity index 100% rename from java-collections-conversions/src/main/java/com/baeldung/convertToMap/ConvertToMap.java rename to core-java-modules/java-collections-conversions/src/main/java/com/baeldung/convertToMap/ConvertToMap.java diff --git a/java-collections-conversions/src/main/java/com/baeldung/convertcollectiontoarraylist/Foo.java b/core-java-modules/java-collections-conversions/src/main/java/com/baeldung/convertcollectiontoarraylist/Foo.java similarity index 100% rename from java-collections-conversions/src/main/java/com/baeldung/convertcollectiontoarraylist/Foo.java rename to core-java-modules/java-collections-conversions/src/main/java/com/baeldung/convertcollectiontoarraylist/Foo.java diff --git a/java-collections-conversions/src/main/java/com/baeldung/convertlisttomap/Animal.java b/core-java-modules/java-collections-conversions/src/main/java/com/baeldung/convertlisttomap/Animal.java similarity index 100% rename from java-collections-conversions/src/main/java/com/baeldung/convertlisttomap/Animal.java rename to core-java-modules/java-collections-conversions/src/main/java/com/baeldung/convertlisttomap/Animal.java diff --git a/java-collections-conversions/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java b/core-java-modules/java-collections-conversions/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java similarity index 100% rename from java-collections-conversions/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java rename to core-java-modules/java-collections-conversions/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java diff --git a/animal-sniffer-mvn-plugin/src/main/resources/logback.xml b/core-java-modules/java-collections-conversions/src/main/resources/logback.xml similarity index 100% rename from animal-sniffer-mvn-plugin/src/main/resources/logback.xml rename to core-java-modules/java-collections-conversions/src/main/resources/logback.xml diff --git a/java-collections-conversions/src/test/java/com/baeldung/convertToMap/ConvertToMapUnitTest.java b/core-java-modules/java-collections-conversions/src/test/java/com/baeldung/convertToMap/ConvertToMapUnitTest.java similarity index 100% rename from java-collections-conversions/src/test/java/com/baeldung/convertToMap/ConvertToMapUnitTest.java rename to core-java-modules/java-collections-conversions/src/test/java/com/baeldung/convertToMap/ConvertToMapUnitTest.java diff --git a/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java b/core-java-modules/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java similarity index 100% rename from java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java rename to core-java-modules/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java diff --git a/java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java b/core-java-modules/java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java similarity index 100% rename from java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java rename to core-java-modules/java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java diff --git a/java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListToMapServiceUnitTest.java b/core-java-modules/java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListToMapServiceUnitTest.java similarity index 100% rename from java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListToMapServiceUnitTest.java rename to core-java-modules/java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListToMapServiceUnitTest.java diff --git a/java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDuplicatedIdToMapServiceUnitTest.java b/core-java-modules/java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDuplicatedIdToMapServiceUnitTest.java similarity index 100% rename from java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDuplicatedIdToMapServiceUnitTest.java rename to core-java-modules/java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDuplicatedIdToMapServiceUnitTest.java diff --git a/java-collections-conversions/src/test/java/com/baeldung/java/collections/IterableToCollectionUnitTest.java b/core-java-modules/java-collections-conversions/src/test/java/com/baeldung/java/collections/IterableToCollectionUnitTest.java similarity index 100% rename from java-collections-conversions/src/test/java/com/baeldung/java/collections/IterableToCollectionUnitTest.java rename to core-java-modules/java-collections-conversions/src/test/java/com/baeldung/java/collections/IterableToCollectionUnitTest.java diff --git a/java-collections-conversions/src/test/java/com/baeldung/java/collections/JavaCollectionConversionUnitTest.java b/core-java-modules/java-collections-conversions/src/test/java/com/baeldung/java/collections/JavaCollectionConversionUnitTest.java similarity index 100% rename from java-collections-conversions/src/test/java/com/baeldung/java/collections/JavaCollectionConversionUnitTest.java rename to core-java-modules/java-collections-conversions/src/test/java/com/baeldung/java/collections/JavaCollectionConversionUnitTest.java diff --git a/java-collections-conversions/src/test/java/com/baeldung/java/lists/ListToStringUnitTest.java b/core-java-modules/java-collections-conversions/src/test/java/com/baeldung/java/lists/ListToStringUnitTest.java similarity index 100% rename from java-collections-conversions/src/test/java/com/baeldung/java/lists/ListToStringUnitTest.java rename to core-java-modules/java-collections-conversions/src/test/java/com/baeldung/java/lists/ListToStringUnitTest.java diff --git a/java-collections-maps-3/README.md b/core-java-modules/java-collections-maps-3/README.md similarity index 100% rename from java-collections-maps-3/README.md rename to core-java-modules/java-collections-maps-3/README.md diff --git a/java-collections-maps-3/pom.xml b/core-java-modules/java-collections-maps-3/pom.xml similarity index 88% rename from java-collections-maps-3/pom.xml rename to core-java-modules/java-collections-maps-3/pom.xml index 729b357b76..ab80a9e2fd 100644 --- a/java-collections-maps-3/pom.xml +++ b/core-java-modules/java-collections-maps-3/pom.xml @@ -9,10 +9,9 @@ jar - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../parent-java @@ -20,7 +19,7 @@ org.junit.jupiter junit-jupiter-api - 5.8.1 + ${junit-jupiter.version} org.springframework diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/bytearrays/BytesKey.java b/core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/bytearrays/BytesKey.java similarity index 100% rename from java-collections-maps-3/src/main/java/com/baeldung/map/bytearrays/BytesKey.java rename to core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/bytearrays/BytesKey.java diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/entry/Book.java b/core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/entry/Book.java similarity index 100% rename from java-collections-maps-3/src/main/java/com/baeldung/map/entry/Book.java rename to core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/entry/Book.java diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/entry/MapEntryEfficiencyExample.java b/core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/entry/MapEntryEfficiencyExample.java similarity index 100% rename from java-collections-maps-3/src/main/java/com/baeldung/map/entry/MapEntryEfficiencyExample.java rename to core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/entry/MapEntryEfficiencyExample.java diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/entry/MapEntryTupleExample.java b/core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/entry/MapEntryTupleExample.java similarity index 100% rename from java-collections-maps-3/src/main/java/com/baeldung/map/entry/MapEntryTupleExample.java rename to core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/entry/MapEntryTupleExample.java diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/hashing/Member.java b/core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/hashing/Member.java similarity index 100% rename from java-collections-maps-3/src/main/java/com/baeldung/map/hashing/Member.java rename to core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/hashing/Member.java diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithBadHashing.java b/core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithBadHashing.java similarity index 100% rename from java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithBadHashing.java rename to core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithBadHashing.java diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithGuavaHashing.java b/core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithGuavaHashing.java similarity index 100% rename from java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithGuavaHashing.java rename to core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithGuavaHashing.java diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithId.java b/core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithId.java similarity index 100% rename from java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithId.java rename to core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithId.java diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithIdAndName.java b/core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithIdAndName.java similarity index 100% rename from java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithIdAndName.java rename to core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithIdAndName.java diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithObjects.java b/core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithObjects.java similarity index 100% rename from java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithObjects.java rename to core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/hashing/MemberWithObjects.java diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/identity/IdentityHashMapDemonstrator.java b/core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/identity/IdentityHashMapDemonstrator.java similarity index 100% rename from java-collections-maps-3/src/main/java/com/baeldung/map/identity/IdentityHashMapDemonstrator.java rename to core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/identity/IdentityHashMapDemonstrator.java diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java b/core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java similarity index 100% rename from java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java rename to core-java-modules/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/bytearrays/ByteArrayKeyUnitTest.java b/core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/bytearrays/ByteArrayKeyUnitTest.java similarity index 100% rename from java-collections-maps-3/src/test/java/com/baeldung/map/bytearrays/ByteArrayKeyUnitTest.java rename to core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/bytearrays/ByteArrayKeyUnitTest.java diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java similarity index 100% rename from java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java rename to core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/entry/MapEntryUnitTest.java b/core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/entry/MapEntryUnitTest.java similarity index 100% rename from java-collections-maps-3/src/test/java/com/baeldung/map/entry/MapEntryUnitTest.java rename to core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/entry/MapEntryUnitTest.java diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/hashing/HashMapUpdateUnitTest.java b/core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/hashing/HashMapUpdateUnitTest.java similarity index 100% rename from java-collections-maps-3/src/test/java/com/baeldung/map/hashing/HashMapUpdateUnitTest.java rename to core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/hashing/HashMapUpdateUnitTest.java diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/hashing/HashingUnitTest.java b/core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/hashing/HashingUnitTest.java similarity index 100% rename from java-collections-maps-3/src/test/java/com/baeldung/map/hashing/HashingUnitTest.java rename to core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/hashing/HashingUnitTest.java diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/identity/IdentityHashMapDemonstratorUnitTest.java b/core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/identity/IdentityHashMapDemonstratorUnitTest.java similarity index 100% rename from java-collections-maps-3/src/test/java/com/baeldung/map/identity/IdentityHashMapDemonstratorUnitTest.java rename to core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/identity/IdentityHashMapDemonstratorUnitTest.java diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java b/core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java similarity index 100% rename from java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java rename to core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/keysetValuesEntrySet/EntrySetExampleUnitTest.java b/core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/keysetValuesEntrySet/EntrySetExampleUnitTest.java similarity index 100% rename from java-collections-maps-3/src/test/java/com/baeldung/map/keysetValuesEntrySet/EntrySetExampleUnitTest.java rename to core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/keysetValuesEntrySet/EntrySetExampleUnitTest.java diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/keysetValuesEntrySet/KeySetExampleUnitTest.java b/core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/keysetValuesEntrySet/KeySetExampleUnitTest.java similarity index 100% rename from java-collections-maps-3/src/test/java/com/baeldung/map/keysetValuesEntrySet/KeySetExampleUnitTest.java rename to core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/keysetValuesEntrySet/KeySetExampleUnitTest.java diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/keysetValuesEntrySet/ValuesExampleUnitTest.java b/core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/keysetValuesEntrySet/ValuesExampleUnitTest.java similarity index 100% rename from java-collections-maps-3/src/test/java/com/baeldung/map/keysetValuesEntrySet/ValuesExampleUnitTest.java rename to core-java-modules/java-collections-maps-3/src/test/java/com/baeldung/map/keysetValuesEntrySet/ValuesExampleUnitTest.java diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 2f684beea0..15347d0fe9 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -35,6 +35,7 @@ core-java-collections-list core-java-collections-list-2 core-java-collections-list-3 + core-java-collections-list-4 core-java-collections-maps core-java-collections-maps-2 core-java-collections-maps-3 @@ -73,6 +74,7 @@ core-java-lang-2 core-java-lang-3 core-java-lang-4 + core-java-lang-5 core-java-lang-math core-java-lang-math-2 core-java-lang-math-3 @@ -117,6 +119,9 @@ core-java-regex core-java-regex-2 core-java-uuid + java-collections-conversions + java-collections-conversions-2 + java-collections-maps-3 pre-jpms diff --git a/docker/docker-caching/multi-module-caching/core/pom.xml b/docker/docker-caching/multi-module-caching/core/pom.xml index eeeb5a6e5b..bcfc4b5783 100644 --- a/docker/docker-caching/multi-module-caching/core/pom.xml +++ b/docker/docker-caching/multi-module-caching/core/pom.xml @@ -1,7 +1,7 @@ + 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"> 4.0.0 core @@ -22,4 +22,5 @@ 8 8 + \ No newline at end of file diff --git a/docker/docker-caching/multi-module-caching/pom.xml b/docker/docker-caching/multi-module-caching/pom.xml index 7968114385..7e279dc334 100644 --- a/docker/docker-caching/multi-module-caching/pom.xml +++ b/docker/docker-caching/multi-module-caching/pom.xml @@ -1,6 +1,7 @@ - + 4.0.0 com.baeldung multi-module-caching @@ -8,22 +9,24 @@ Multi-module Maven caching example pom + + runner + core + + com.google.guava guava - 31.0.1-jre + ${guava.version} 1.8 + 31.0.1-jre - - runner - core - - + \ No newline at end of file diff --git a/docker/docker-caching/multi-module-caching/runner/pom.xml b/docker/docker-caching/multi-module-caching/runner/pom.xml index e3654bff17..e3f234bac0 100644 --- a/docker/docker-caching/multi-module-caching/runner/pom.xml +++ b/docker/docker-caching/multi-module-caching/runner/pom.xml @@ -1,7 +1,7 @@ + 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"> 4.0.0 runner @@ -53,4 +53,5 @@ 8 8 + \ No newline at end of file diff --git a/docker/docker-caching/single-module-caching/pom.xml b/docker/docker-caching/single-module-caching/pom.xml index 386b040138..d7f96e1e7e 100644 --- a/docker/docker-caching/single-module-caching/pom.xml +++ b/docker/docker-caching/single-module-caching/pom.xml @@ -1,9 +1,8 @@ + 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"> 4.0.0 - com.baeldung single-module-caching 1.0-SNAPSHOT @@ -12,7 +11,7 @@ com.google.guava guava - 31.0.1-jre + ${guava.version} @@ -49,5 +48,7 @@ 8 8 + 31.0.1-jre + \ No newline at end of file diff --git a/docker/docker-internal-dto/pom.xml b/docker/docker-internal-dto/pom.xml index 55cef257fe..09013d2fc3 100644 --- a/docker/docker-internal-dto/pom.xml +++ b/docker/docker-internal-dto/pom.xml @@ -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"> 4.0.0 + docker-internal-dto + docker-internal-dto + com.baeldung.docker docker 0.0.1 - docker-internal-dto - docker-internal-dto - diff --git a/docker/docker-push-to-private-repo/.gitignore b/docker/docker-push-to-private-repo/.gitignore new file mode 100644 index 0000000000..549e00a2a9 --- /dev/null +++ b/docker/docker-push-to-private-repo/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/docker/docker-push-to-private-repo/Dockerfile b/docker/docker-push-to-private-repo/Dockerfile new file mode 100644 index 0000000000..42a13e2a93 --- /dev/null +++ b/docker/docker-push-to-private-repo/Dockerfile @@ -0,0 +1,4 @@ +FROM openjdk:11 +ARG JAR_FILE=target/*.jar +COPY ${JAR_FILE} app.jar +ENTRYPOINT ["java","-jar","/app.jar"] \ No newline at end of file diff --git a/docker/docker-push-to-private-repo/README.md b/docker/docker-push-to-private-repo/README.md new file mode 100644 index 0000000000..61fe00e016 --- /dev/null +++ b/docker/docker-push-to-private-repo/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Pushing a Docker Image to a Private Repository](https://www.baeldung.com/ops/docker-push-image-to-private-repository) diff --git a/docker/docker-push-to-private-repo/pom.xml b/docker/docker-push-to-private-repo/pom.xml new file mode 100644 index 0000000000..59a909ff07 --- /dev/null +++ b/docker/docker-push-to-private-repo/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + + com.baeldung.docker + docker + 0.0.1 + + push-to-private-repo + 0.0.1-SNAPSHOT + push-to-private-repo + Example application to showcase how to push a docker image to a private repository + + 11 + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/docker/docker-push-to-private-repo/src/main/java/com/baeldung/docker/push/HelloWorldController.java b/docker/docker-push-to-private-repo/src/main/java/com/baeldung/docker/push/HelloWorldController.java new file mode 100644 index 0000000000..58486c3086 --- /dev/null +++ b/docker/docker-push-to-private-repo/src/main/java/com/baeldung/docker/push/HelloWorldController.java @@ -0,0 +1,12 @@ +package com.baeldung.docker.push; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HelloWorldController { + @GetMapping("/helloworld") + String helloWorld() { + return "Hello World!"; + } +} \ No newline at end of file diff --git a/docker/docker-push-to-private-repo/src/main/java/com/baeldung/docker/push/PushToPrivateRepoApplication.java b/docker/docker-push-to-private-repo/src/main/java/com/baeldung/docker/push/PushToPrivateRepoApplication.java new file mode 100644 index 0000000000..7f516b3158 --- /dev/null +++ b/docker/docker-push-to-private-repo/src/main/java/com/baeldung/docker/push/PushToPrivateRepoApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.docker.push; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class PushToPrivateRepoApplication { + + public static void main(String[] args) { + SpringApplication.run(PushToPrivateRepoApplication.class, args); + } + +} diff --git a/docker/docker-push-to-private-repo/src/main/resources/application.properties b/docker/docker-push-to-private-repo/src/main/resources/application.properties new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/docker/docker-push-to-private-repo/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/docker/docker-sample-app/pom.xml b/docker/docker-sample-app/pom.xml index 6841fabcee..24fede56fd 100644 --- a/docker/docker-sample-app/pom.xml +++ b/docker/docker-sample-app/pom.xml @@ -1,21 +1,18 @@ - + 4.0.0 + docker-sample-app + docker-sample-app + Demo project for Spring Boot and Docker + com.baeldung.docker docker 0.0.1 - docker-sample-app - docker-sample-app - Demo project for Spring Boot and Docker - - - 11 - - org.springframework.boot @@ -42,4 +39,8 @@ - + + 11 + + + \ No newline at end of file diff --git a/docker/docker-spring-boot-postgres/pom.xml b/docker/docker-spring-boot-postgres/pom.xml index d08ae130db..7a4ed1db3c 100644 --- a/docker/docker-spring-boot-postgres/pom.xml +++ b/docker/docker-spring-boot-postgres/pom.xml @@ -1,13 +1,14 @@ - - 4.0.0 - com.baeldung.docker - docker-spring-boot-postgres - 0.0.1-SNAPSHOT - docker-spring-boot-postgres - Demo project showing Spring Boot, PostgreSQL, and Docker - + + 4.0.0 + com.baeldung.docker + docker-spring-boot-postgres + 0.0.1-SNAPSHOT + docker-spring-boot-postgres + Demo project showing Spring Boot, PostgreSQL, and Docker + com.baeldung parent-boot-2 @@ -15,33 +16,32 @@ ../../parent-boot-2 - - - org.springframework.boot - spring-boot-starter-data-jpa - + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.postgresql + postgresql + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + - - org.postgresql - postgresql - runtime - - - org.springframework.boot - spring-boot-starter-test - test - - + + + + org.springframework.boot + spring-boot-maven-plugin + + + - - - - org.springframework.boot - spring-boot-maven-plugin - - - - 11 diff --git a/docker/docker-spring-boot/README.md b/docker/docker-spring-boot/README.md index 4af9378290..0fc9d2b6b5 100644 --- a/docker/docker-spring-boot/README.md +++ b/docker/docker-spring-boot/README.md @@ -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) diff --git a/docker/docker-spring-boot/mvnw b/docker/docker-spring-boot/mvnw deleted file mode 100755 index a16b5431b4..0000000000 --- a/docker/docker-spring-boot/mvnw +++ /dev/null @@ -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 "$@" diff --git a/docker/docker-spring-boot/mvnw.cmd b/docker/docker-spring-boot/mvnw.cmd deleted file mode 100644 index c8d43372c9..0000000000 --- a/docker/docker-spring-boot/mvnw.cmd +++ /dev/null @@ -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% diff --git a/docker/docker-spring-boot/pom.xml b/docker/docker-spring-boot/pom.xml index 74bd1561cf..c42f7602b4 100644 --- a/docker/docker-spring-boot/pom.xml +++ b/docker/docker-spring-boot/pom.xml @@ -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"> 4.0.0 + docker-spring-boot + docker-spring-boot + Demo project showing Spring Boot and Docker + com.baeldung.docker docker 0.0.1 - docker-spring-boot - - docker-spring-boot - Demo project showing Spring Boot and Docker - - - 11 - - org.springframework.boot spring-boot-starter-web - - - com.baeldung.docker - docker-internal-dto - 0.0.1 - - org.springframework.boot spring-boot-starter-test @@ -58,4 +46,8 @@ - + + 11 + + + \ No newline at end of file diff --git a/docker/heap-sizing/pom.xml b/docker/heap-sizing/pom.xml index 2cc354f6cf..32c200c1c0 100644 --- a/docker/heap-sizing/pom.xml +++ b/docker/heap-sizing/pom.xml @@ -48,7 +48,6 @@ com.google.cloud.tools jib-maven-plugin 2.7.1 - heapsizing-demo-jib @@ -62,4 +61,4 @@ 11 - + \ No newline at end of file diff --git a/docker/pom.xml b/docker/pom.xml index 5c6267c6dd..f46ceac963 100644 --- a/docker/pom.xml +++ b/docker/pom.xml @@ -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"> 4.0.0 - com.baeldung.docker docker 0.0.1 docker Demo project showing Spring Boot and Docker pom - + com.baeldung parent-boot-2 @@ -18,16 +17,17 @@ ../parent-boot-2 - - 11 - - docker-internal-dto docker-spring-boot docker-sample-app docker-caching/single-module-caching docker-caching/multi-module-caching + docker-push-to-private-repo - + + 11 + + + \ No newline at end of file diff --git a/feign/pom.xml b/feign/pom.xml index 026afdfc7a..8fa864fa46 100644 --- a/feign/pom.xml +++ b/feign/pom.xml @@ -1,5 +1,7 @@ - + 4.0.0 com.baeldung.feign feign @@ -69,6 +71,7 @@ test + @@ -92,10 +95,8 @@ src/main/resources/users.xsd - - org.jvnet.jaxb2.maven2 maven-jaxb2-plugin @@ -111,7 +112,6 @@ *.xsd - com.baeldung.feign.soap target/generated-sources/jaxb @@ -119,6 +119,6 @@ - + \ No newline at end of file diff --git a/graphql/graphql-dgs/pom.xml b/graphql/graphql-dgs/pom.xml index 6165ae839f..56e261f14d 100644 --- a/graphql/graphql-dgs/pom.xml +++ b/graphql/graphql-dgs/pom.xml @@ -3,16 +3,14 @@ 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"> 4.0.0 - com.baeldung.graphql-dgs graphql-dgs 1.0 graphql-dgs - com.baeldung - parent-modules + com.baeldung.graphql + graphql 1.0.0-SNAPSHOT - ../.. @@ -30,39 +28,22 @@ org.springframework.boot - spring-boot-starter - 2.6.2 - - - org.springframework.boot - spring-boot-starter-test - 2.6.2 - test + spring-boot-starter-web com.netflix.graphql.dgs.codegen graphql-dgs-codegen-client-core - 5.1.14 - - - org.springframework.boot - spring-boot-starter-web - 2.6.2 + ${graphql-dgs-codegen-client-core.version} com.netflix.graphql.dgs graphql-dgs-spring-boot-starter - 4.9.15 + ${graphql-dgs-spring-boot-starter.version} - - org.springframework.boot - spring-boot-maven-plugin - 2.6.2 - io.github.deweyjose graphqlcodegen-maven-plugin @@ -84,4 +65,9 @@ + + 5.1.14 + 4.9.15 + + \ No newline at end of file diff --git a/graphql/graphql-error-handling/README.md b/graphql/graphql-error-handling/README.md new file mode 100644 index 0000000000..06a2957ac1 --- /dev/null +++ b/graphql/graphql-error-handling/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Error Handling in GraphQL With Spring Boot](https://www.baeldung.com/spring-graphql-error-handling) diff --git a/graphql/graphql-error-handling/pom.xml b/graphql/graphql-error-handling/pom.xml index 0cd00df3b9..92696d8ed7 100644 --- a/graphql/graphql-error-handling/pom.xml +++ b/graphql/graphql-error-handling/pom.xml @@ -1,97 +1,71 @@ + 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"> 4.0.0 - com.baeldung.graphql graphql-error-handling 1.0 - jar graphql-error-handling + jar - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 + com.baeldung.graphql + graphql + 1.0.0-SNAPSHOT - - 1.8 - 1.18.18 - - org.springframework.boot spring-boot-starter-data-jpa - org.springframework.boot spring-boot-starter-web - com.graphql-java graphql-spring-boot-starter - 5.0.2 + ${graphql-spring-boot-starter.version} - com.graphql-java graphql-java-tools - 5.2.4 + ${graphql-java-tools.version} - org.projectlombok lombok ${lombok.version} - com.h2database h2 ${h2.version} - org.springframework.boot spring-boot-test test - 2.6.4 - com.graphql-java graphql-spring-boot-starter-test test - 5.0.2 + ${graphql-spring-boot-starter.version} - - - org.assertj - assertj-core - 3.22.0 - test - - org.skyscreamer jsonassert - 1.5.0 + ${jsonassert.version} test - - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + 5.0.2 + 5.2.4 + 1.5.0 + + \ No newline at end of file diff --git a/graphql/graphql-java/README.md b/graphql/graphql-java/README.md index f37506a9fd..85c1497169 100644 --- a/graphql/graphql-java/README.md +++ b/graphql/graphql-java/README.md @@ -6,3 +6,4 @@ This module contains articles about GraphQL with Java - [Introduction to GraphQL](https://www.baeldung.com/graphql) - [Make a Call to a GraphQL Service from a Java Application](https://www.baeldung.com/java-call-graphql-service) +- [Return Map from GraphQL](https://www.baeldung.com/java-graphql-return-map) diff --git a/graphql/graphql-java/pom.xml b/graphql/graphql-java/pom.xml index 068cb04ea8..b0b2c15359 100644 --- a/graphql/graphql-java/pom.xml +++ b/graphql/graphql-java/pom.xml @@ -3,16 +3,14 @@ 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"> 4.0.0 - com.baeldung.graphql graphql-java 1.0 graphql-java - com.baeldung - parent-modules + com.baeldung.graphql + graphql 1.0.0-SNAPSHOT - ../../pom.xml @@ -44,12 +42,12 @@ com.github.americanexpress.nodes nodes - 0.5.0 + ${nodes.version} com.graphql-java graphql-java - 11.0 + ${graphql-java.version} com.graphql-java @@ -77,16 +75,6 @@ jackson-core ${jackson.version} - - io.ratpack - ratpack-core - ${ratpack-core.version} - - - com.github.americanexpress.nodes - nodes - ${nodes.version} - org.apache.commons commons-lang3 @@ -97,7 +85,6 @@ httpclient ${httpclient.version} - org.mock-server mockserver-netty @@ -110,27 +97,15 @@ ${mockserver-client-java.version} test - com.graphql-java graphql-java-extended-scalars ${graphql-java-extended-scalars.version} - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - - org.eclipse.jetty jetty-maven-plugin @@ -169,6 +144,7 @@ + 11.0 5.2.4 6.1.3 3.0.3 @@ -176,16 +152,11 @@ 1.9.0 0.5.0 4.5.13 - 5.13.2 5.13.2 - 10.0.7 - - 1.8 - 1.8 1.18 2022-04-06T00-10-27-a70541e - + \ No newline at end of file diff --git a/graphql/graphql-java/src/test/java/com/baeldung/graphql/GraphQLMockServer.java b/graphql/graphql-java/src/test/java/com/baeldung/graphql/GraphQLMockServer.java index fb5a789428..e72f6a38b9 100644 --- a/graphql/graphql-java/src/test/java/com/baeldung/graphql/GraphQLMockServer.java +++ b/graphql/graphql-java/src/test/java/com/baeldung/graphql/GraphQLMockServer.java @@ -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(); } diff --git a/graphql/graphql-spqr/pom.xml b/graphql/graphql-spqr/pom.xml index c825be9b79..75a1b5d79b 100644 --- a/graphql/graphql-spqr/pom.xml +++ b/graphql/graphql-spqr/pom.xml @@ -2,30 +2,21 @@ - 4.0.0 - com.baeldung.graphql graphql-spqr 1.0 - graphql-java + graphql-spqr - com.baeldung - parent-modules + com.baeldung.graphql + graphql 1.0.0-SNAPSHOT - ../.. org.springframework.boot spring-boot-starter-web - ${spring-boot-version} - - - org.springframework.boot - spring-boot-starter - ${spring-boot-version} io.leangen.graphql @@ -34,18 +25,8 @@ - - - - org.springframework.boot - spring-boot-maven-plugin - 2.6.2 - - - - - 2.6.2 0.0.6 + \ No newline at end of file diff --git a/graphql/graphql-spqr/src/main/java/com/baeldung/spqr/BookService.java b/graphql/graphql-spqr/src/main/java/com/baeldung/spqr/BookService.java index 7c9b129491..2e9c6d8367 100644 --- a/graphql/graphql-spqr/src/main/java/com/baeldung/spqr/BookService.java +++ b/graphql/graphql-spqr/src/main/java/com/baeldung/spqr/BookService.java @@ -9,6 +9,7 @@ import org.springframework.stereotype.Service; import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.stream.Collectors; @Service @GraphQLApi @@ -27,8 +28,7 @@ public class BookService implements IBookService { @GraphQLQuery(name = "getAllBooks", description = "Get all books") public List getAllBooks() { - return books.stream() - .toList(); + return books.stream().collect(Collectors.toList()); } @GraphQLMutation(name = "addBook") diff --git a/graphql/pom.xml b/graphql/pom.xml new file mode 100644 index 0000000000..aec097752a --- /dev/null +++ b/graphql/pom.xml @@ -0,0 +1,26 @@ + + + 4.0.0 + com.baeldung.graphql + graphql + 1.0.0-SNAPSHOT + graphql + pom + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + graphql-dgs + graphql-error-handling + graphql-java + graphql-spqr + + + \ No newline at end of file diff --git a/grpc/pom.xml b/grpc/pom.xml index 40284c90fe..40d35183dc 100644 --- a/grpc/pom.xml +++ b/grpc/pom.xml @@ -40,7 +40,7 @@ javax.annotation javax.annotation-api - 1.2 + ${annotation-api.version} @@ -79,6 +79,7 @@ 3.17.2 1.6.2 0.6.1 + 1.2 \ No newline at end of file diff --git a/jakarta-ee/pom.xml b/jakarta-ee/pom.xml index dea4437345..afd31d7ece 100644 --- a/jakarta-ee/pom.xml +++ b/jakarta-ee/pom.xml @@ -51,25 +51,20 @@ admin password - ${local.glassfish.domain} 8080 4848 - ${project.artifactId} target/${project.build.finalName}.war - true false true - - diff --git a/java-numbers-4/README.md b/java-numbers-4/README.md index 267639a829..c18a5ebe6f 100644 --- a/java-numbers-4/README.md +++ b/java-numbers-4/README.md @@ -7,3 +7,4 @@ - [Automorphic Numbers in Java](https://www.baeldung.com/java-automorphic-numbers) - [Convert Byte Size Into a Human-Readable Format in Java](https://www.baeldung.com/java-human-readable-byte-size) - [Convert boolean to int in Java](https://www.baeldung.com/java-boolean-to-int) +- [Generate a Random Value From an Enum](https://www.baeldung.com/java-enum-random-value) diff --git a/java-numbers-4/pom.xml b/java-numbers-4/pom.xml index 40fe17cc0d..4750b58511 100644 --- a/java-numbers-4/pom.xml +++ b/java-numbers-4/pom.xml @@ -23,7 +23,6 @@ org.apache.commons commons-lang3 ${commons-lang3.version} - test com.google.guava diff --git a/java-numbers-4/src/main/java/com/baeldung/booleantoint/BooleanToInt.java b/java-numbers-4/src/main/java/com/baeldung/booleantoint/BooleanToInt.java new file mode 100644 index 0000000000..3cca1592fb --- /dev/null +++ b/java-numbers-4/src/main/java/com/baeldung/booleantoint/BooleanToInt.java @@ -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; + } +} + diff --git a/java-numbers-4/src/main/java/com/baeldung/reversenumber/ReverseNumber.java b/java-numbers-4/src/main/java/com/baeldung/reversenumber/ReverseNumber.java new file mode 100644 index 0000000000..04865a8d52 --- /dev/null +++ b/java-numbers-4/src/main/java/com/baeldung/reversenumber/ReverseNumber.java @@ -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; + } +} diff --git a/java-numbers-4/src/test/java/com/baeldung/booleantoint/BooleanToIntUnitTest.java b/java-numbers-4/src/test/java/com/baeldung/booleantoint/BooleanToIntUnitTest.java new file mode 100644 index 0000000000..032eb1d28c --- /dev/null +++ b/java-numbers-4/src/test/java/com/baeldung/booleantoint/BooleanToIntUnitTest.java @@ -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)); + } +} diff --git a/java-numbers-4/src/test/java/com/baeldung/reversenumber/ReverseNumberUnitTest.java b/java-numbers-4/src/test/java/com/baeldung/reversenumber/ReverseNumberUnitTest.java new file mode 100644 index 0000000000..2c55bcc539 --- /dev/null +++ b/java-numbers-4/src/test/java/com/baeldung/reversenumber/ReverseNumberUnitTest.java @@ -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); + } +} \ No newline at end of file diff --git a/jersey/README.md b/jersey/README.md index 366e7665f3..4c8c235be5 100644 --- a/jersey/README.md +++ b/jersey/README.md @@ -10,3 +10,4 @@ This module contains articles about Jersey. - [Exploring the Jersey Test Framework](https://www.baeldung.com/jersey-test) - [Explore Jersey Request Parameters](https://www.baeldung.com/jersey-request-parameters) - [Add a Header to a Jersey SSE Client Request](https://www.baeldung.com/jersey-sse-client-request-headers) +- [Exception Handling With Jersey](https://www.baeldung.com/java-exception-handling-jersey) diff --git a/jib/pom.xml b/jib/pom.xml index 8208eebdf7..bbc9a3c623 100644 --- a/jib/pom.xml +++ b/jib/pom.xml @@ -43,4 +43,5 @@ 2.5.0 + \ No newline at end of file diff --git a/json-2/README.md b/json-2/README.md index ed5a79dd3d..b3e7fb0b94 100644 --- a/json-2/README.md +++ b/json-2/README.md @@ -9,4 +9,5 @@ This module contains articles about JSON. - [Hypermedia Serialization With JSON-LD](https://www.baeldung.com/json-linked-data) - [Generate a Java Class From JSON](https://www.baeldung.com/java-generate-class-from-json) - [A Guide to FastJson](https://www.baeldung.com/fastjson) +- [Check Whether a String is Valid JSON in Java](https://www.baeldung.com/java-validate-json-string) - More Articles: [[<-- prev]](/json) diff --git a/json-2/pom.xml b/json-2/pom.xml index 751199d394..6fbdebc953 100644 --- a/json-2/pom.xml +++ b/json-2/pom.xml @@ -14,6 +14,11 @@ + + org.json + json + ${json.version} + com.alibaba fastjson @@ -22,7 +27,7 @@ org.jsonschema2pojo jsonschema2pojo-core - 1.1.1 + ${jsonschema2pojo-core.version} com.jsoniter @@ -57,7 +62,7 @@ com.io-informatics.oss jackson-jsonld - 0.1.1 + ${jackson-jsonld.version} jackson-databind @@ -80,7 +85,7 @@ de.escalon.hypermedia hydra-jsonld - 0.4.2 + ${hydra-jsonld.version} jackson-databind @@ -91,7 +96,7 @@ com.github.jsonld-java jsonld-java - 0.13.0 + ${jsonld-java.version} jackson-core @@ -148,6 +153,11 @@ 0.9.23 1.9.2 1.2.21 + 20211205 + 1.1.1 + 0.1.1 + 0.4.2 + 0.13.0 \ No newline at end of file diff --git a/json-2/src/main/java/com/baeldung/jsonvalidation/GsonValidator.java b/json-2/src/main/java/com/baeldung/jsonvalidation/GsonValidator.java new file mode 100644 index 0000000000..841513fc28 --- /dev/null +++ b/json-2/src/main/java/com/baeldung/jsonvalidation/GsonValidator.java @@ -0,0 +1,32 @@ +package com.baeldung.jsonvalidation; + +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; +import com.google.gson.TypeAdapter; + +public class GsonValidator { + + final TypeAdapter strictAdapter = new Gson().getAdapter(JsonElement.class); + + public boolean isValid(String json) { + try { + JsonParser.parseString(json); + } catch (JsonSyntaxException e) { + return false; + } + return true; + } + + public boolean isValidStrict(String json) { + try { + strictAdapter.fromJson(json); + } catch (JsonSyntaxException | IOException e) { + return false; + } + return true; + } +} diff --git a/json-2/src/main/java/com/baeldung/jsonvalidation/JacksonValidator.java b/json-2/src/main/java/com/baeldung/jsonvalidation/JacksonValidator.java new file mode 100644 index 0000000000..8c339f46c8 --- /dev/null +++ b/json-2/src/main/java/com/baeldung/jsonvalidation/JacksonValidator.java @@ -0,0 +1,18 @@ +package com.baeldung.jsonvalidation; + +import com.fasterxml.jackson.core.JacksonException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JacksonValidator { + + final ObjectMapper mapper = new ObjectMapper(); + + public boolean isValid(String json) { + try { + mapper.readTree(json); + } catch (JacksonException e) { + return false; + } + return true; + } +} diff --git a/json-2/src/main/java/com/baeldung/jsonvalidation/JsonValidator.java b/json-2/src/main/java/com/baeldung/jsonvalidation/JsonValidator.java new file mode 100644 index 0000000000..e4183e2322 --- /dev/null +++ b/json-2/src/main/java/com/baeldung/jsonvalidation/JsonValidator.java @@ -0,0 +1,30 @@ +package com.baeldung.jsonvalidation; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class JsonValidator { + + public boolean isValidObject(String json) { + try { + new JSONObject(json); + } catch (JSONException e) { + return false; + } + return true; + } + + public boolean isValidJson(String json) { + try { + new JSONObject(json); + } catch (JSONException e) { + try { + new JSONArray(json); + } catch (JSONException ne) { + return false; + } + } + return true; + } +} diff --git a/json-2/src/test/java/com/baeldung/jsonvalidation/GsonValidatorUnitTest.java b/json-2/src/test/java/com/baeldung/jsonvalidation/GsonValidatorUnitTest.java new file mode 100644 index 0000000000..3b8989bdb5 --- /dev/null +++ b/json-2/src/test/java/com/baeldung/jsonvalidation/GsonValidatorUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.jsonvalidation; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class GsonValidatorUnitTest { + + private final GsonValidator validator = new GsonValidator(); + + @Test + public void givenValidObjectJson_whenValidatingNonStrict_thenValid() { + String json = "{\"email\": \"example@com\", \"name\": \"John\"}"; + assertTrue(validator.isValid(json)); + } + + @Test + public void givenValidArrayJson_whenValidatingNonStrict_thenValid() { + String json = "[{\"email\": \"example@com\", \"name\": \"John\"},{\"email\": \"example1@com\", \"name\": \"Bob\"}]"; + assertTrue(validator.isValid(json)); + } + + @Test + public void givenInvalidJson_whenValidatingNonStrict_thenValid() { + String json = "Invalid_Json"; + assertTrue(validator.isValid(json)); + } + + @Test + public void givenInvalidJson_whenValidatingStrict_thenInvalid() { + String json = "Invalid_Json"; + assertFalse(validator.isValidStrict(json)); + } +} diff --git a/json-2/src/test/java/com/baeldung/jsonvalidation/JacksonValidatorUnitTest.java b/json-2/src/test/java/com/baeldung/jsonvalidation/JacksonValidatorUnitTest.java new file mode 100644 index 0000000000..b633af7fdc --- /dev/null +++ b/json-2/src/test/java/com/baeldung/jsonvalidation/JacksonValidatorUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.jsonvalidation; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class JacksonValidatorUnitTest { + + private final JacksonValidator validator = new JacksonValidator(); + + @Test + public void givenValidObjectJson_whenValidating_thenValid() { + String json = "{\"email\": \"example@com\", \"name\": \"John\"}"; + assertTrue(validator.isValid(json)); + } + + @Test + public void givenValidArrayJson_whenValidating_thenValid() { + String json = "[{\"email\": \"example@com\", \"name\": \"John\"},{\"email\": \"example1@com\", \"name\": \"Bob\"}]"; + assertTrue(validator.isValid(json)); + } + + @Test + public void givenInvalidJson_whenValidating_thenInvalid() { + String json = "Invalid_Json"; + assertFalse(validator.isValid(json)); + } +} diff --git a/json-2/src/test/java/com/baeldung/jsonvalidation/JsonValidatorUnitTest.java b/json-2/src/test/java/com/baeldung/jsonvalidation/JsonValidatorUnitTest.java new file mode 100644 index 0000000000..a590b3f709 --- /dev/null +++ b/json-2/src/test/java/com/baeldung/jsonvalidation/JsonValidatorUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.jsonvalidation; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class JsonValidatorUnitTest { + + private final JsonValidator validator = new JsonValidator(); + + @Test + public void givenValidObjectJson_whenValidatingObject_thenValid() { + String json = "{\"email\": \"example@com\", \"name\": \"John\"}"; + assertTrue(validator.isValidObject(json)); + } + + @Test + public void givenInvalidJson_whenValidating_thenInvalid() { + String json = "Invalid_Json"; + assertFalse(validator.isValidObject(json)); + } + + @Test + public void givenValidArrayJson_whenValidatingObject_thenInvalid() { + String json = "[{\"email\": \"example@com\", \"name\": \"John\"},{\"email\": \"example1@com\", \"name\": \"Bob\"}]"; + assertFalse(validator.isValidObject(json)); + } + + @Test + public void givenValidJson_whenValidatingJson_thenValid() { + String json = "[{\"email\": \"example@com\", \"name\": \"John\"},{\"email\": \"example1@com\", \"name\": \"Bob\"}]"; + assertTrue(validator.isValidJson(json)); + } +} diff --git a/kubernetes/k8s-intro/pom.xml b/kubernetes/k8s-intro/pom.xml index 6d1cec9971..067700bdad 100644 --- a/kubernetes/k8s-intro/pom.xml +++ b/kubernetes/k8s-intro/pom.xml @@ -15,7 +15,7 @@ io.kubernetes client-java - 11.0.0 + ${client-java.version} ch.qos.logback @@ -39,4 +39,8 @@ + + 11.0.0 + + \ No newline at end of file diff --git a/libraries-3/pom.xml b/libraries-3/pom.xml index c51b264e83..d68a9e0703 100644 --- a/libraries-3/pom.xml +++ b/libraries-3/pom.xml @@ -112,7 +112,7 @@ structurizr-plantuml ${structurizr.version} - + org.immutables value ${immutables.version} @@ -177,7 +177,7 @@ - -XepExcludedPaths:(.*)/test/.*|(.*)/jcabi/.* @@ -190,7 +190,7 @@ plexus-compiler-javac-errorprone 2.8 - com.google.errorprone diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index dd48453a8c..c33be5b192 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -172,9 +172,9 @@ 1.0.0 2.4.0 2.8.2 - 1.1.0 + 1.1.1 1.5.0 - 3.8.4 + 5.1.1 0.15.0 2.2.0 1.6.0.1 diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java index e842cda3d6..86cd00c6af 100644 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java @@ -1,47 +1,58 @@ package com.baeldung.logging.log4j2.tests; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.PrintStream; - +import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.Appender; +import org.apache.logging.log4j.core.appender.WriterAppender; +import org.apache.logging.log4j.core.layout.JsonLayout; +import org.junit.After; import org.junit.Before; import org.junit.Test; -import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.CharArrayWriter; +import java.io.Writer; + +import static org.junit.Assert.assertTrue; public class JSONLayoutIntegrationTest extends Log4j2BaseIntegrationTest { - private static Logger logger; - private ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream(); - private PrintStream ps = new PrintStream(consoleOutput); + private Appender appender; + private Logger logger; + private final Writer writer = new CharArrayWriter(); @Before public void setUp() { - // Redirect console output to our stream - System.setOut(ps); logger = LogManager.getLogger("CONSOLE_JSON_APPENDER"); + + appender = WriterAppender.newBuilder() + .setTarget(writer) + .setLayout(JsonLayout.newBuilder().build()) + .setName("json_layout_for_testing") + .build(); + appender.start(); + + ((org.apache.logging.log4j.core.Logger) logger).addAppender(appender); } @Test - public void whenLogLayoutInJSON_thenOutputIsCorrectJSON() { + public void whenLogLayoutInJSON_thenOutputIsCorrectJSON() throws Exception { logger.debug("Debug message"); - String currentLog = consoleOutput.toString(); - assertTrue(currentLog.isEmpty()); - assertTrue(isValidJSON(currentLog)); + + writer.flush(); + assertTrue(isValidJSON(writer.toString())); } - public static boolean isValidJSON(String jsonInString) { - try { - final ObjectMapper mapper = new ObjectMapper(); - mapper.readTree(jsonInString); - return true; - } catch (IOException e) { - return false; - } + @After + public void cleanup() { + ((org.apache.logging.log4j.core.Logger) logger).removeAppender(appender); } -} \ No newline at end of file + + private static boolean isValidJSON(String jsonInString) throws Exception { + JsonNode jsonNode = new ObjectMapper().readTree(jsonInString); + return jsonNode.get("message").asText().equals("Debug message"); + } + +} diff --git a/animal-sniffer-mvn-plugin/README.md b/maven-modules/animal-sniffer-mvn-plugin/README.md similarity index 100% rename from animal-sniffer-mvn-plugin/README.md rename to maven-modules/animal-sniffer-mvn-plugin/README.md diff --git a/animal-sniffer-mvn-plugin/pom.xml b/maven-modules/animal-sniffer-mvn-plugin/pom.xml similarity index 95% rename from animal-sniffer-mvn-plugin/pom.xml rename to maven-modules/animal-sniffer-mvn-plugin/pom.xml index 9e4f25c791..1756adc27d 100644 --- a/animal-sniffer-mvn-plugin/pom.xml +++ b/maven-modules/animal-sniffer-mvn-plugin/pom.xml @@ -11,8 +11,8 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + maven-modules + 0.0.1-SNAPSHOT diff --git a/animal-sniffer-mvn-plugin/src/main/java/com/baeldung/App.java b/maven-modules/animal-sniffer-mvn-plugin/src/main/java/com/baeldung/App.java similarity index 100% rename from animal-sniffer-mvn-plugin/src/main/java/com/baeldung/App.java rename to maven-modules/animal-sniffer-mvn-plugin/src/main/java/com/baeldung/App.java diff --git a/java-collections-conversions/src/main/resources/logback.xml b/maven-modules/animal-sniffer-mvn-plugin/src/main/resources/logback.xml similarity index 100% rename from java-collections-conversions/src/main/resources/logback.xml rename to maven-modules/animal-sniffer-mvn-plugin/src/main/resources/logback.xml diff --git a/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java b/maven-modules/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java similarity index 100% rename from animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java rename to maven-modules/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java diff --git a/maven-modules/host-maven-repo-example/pom.xml b/maven-modules/host-maven-repo-example/pom.xml index bd58dddeda..20528853cd 100644 --- a/maven-modules/host-maven-repo-example/pom.xml +++ b/maven-modules/host-maven-repo-example/pom.xml @@ -6,11 +6,11 @@ com.baeldung.maven.plugin host-maven-repo-example 1.0-SNAPSHOT - https://github.com/sgrverma23/host-maven-repo-example.git + https://github.com/${repository-owner}/${repository-name}.git - https://github.com/sgrverma23/host-maven-repo-example.git - scm:git:git@github.com:sgrverma23/host-maven-repo-example.git - scm:git:git@github.com:sgrverma23/host-maven-repo-example.git + https://github.com/${repository-owner}/${repository-name}.git + scm:git:git@github.com:${repository-owner}/${repository-name}.git + scm:git:git@github.com:${repository-owner}/${repository-name}.git @@ -43,13 +43,13 @@ Maven artifacts for ${project.version} true ${project.build.directory} - refs/heads/main + refs/heads/${branch-name} **/* true - host-maven-repo-example - sgrverma23 + ${repository-name} + ${repository-owner} github @@ -89,7 +89,7 @@ PROJECT-REPO-URL - https://github.com/sgrverma23/host-maven-repo-example/main + https://github.com/${repository-owner}/${repository-name}/${branch-name} true always @@ -98,9 +98,13 @@ + + Put-repo-owner + Put-repository-name + Put-branch-name github 8 8 - \ No newline at end of file + diff --git a/maven-archetype/README.md b/maven-modules/maven-archetype/README.md similarity index 100% rename from maven-archetype/README.md rename to maven-modules/maven-archetype/README.md diff --git a/maven-archetype/pom.xml b/maven-modules/maven-archetype/pom.xml similarity index 100% rename from maven-archetype/pom.xml rename to maven-modules/maven-archetype/pom.xml diff --git a/maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml b/maven-modules/maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml similarity index 100% rename from maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml rename to maven-modules/maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml diff --git a/maven-archetype/src/main/resources/archetype-resources/pom.xml b/maven-modules/maven-archetype/src/main/resources/archetype-resources/pom.xml similarity index 100% rename from maven-archetype/src/main/resources/archetype-resources/pom.xml rename to maven-modules/maven-archetype/src/main/resources/archetype-resources/pom.xml diff --git a/maven-archetype/src/main/resources/archetype-resources/src/main/java/AppConfig.java b/maven-modules/maven-archetype/src/main/resources/archetype-resources/src/main/java/AppConfig.java similarity index 100% rename from maven-archetype/src/main/resources/archetype-resources/src/main/java/AppConfig.java rename to maven-modules/maven-archetype/src/main/resources/archetype-resources/src/main/java/AppConfig.java diff --git a/maven-archetype/src/main/resources/archetype-resources/src/main/java/PingResource.java b/maven-modules/maven-archetype/src/main/resources/archetype-resources/src/main/java/PingResource.java similarity index 100% rename from maven-archetype/src/main/resources/archetype-resources/src/main/java/PingResource.java rename to maven-modules/maven-archetype/src/main/resources/archetype-resources/src/main/java/PingResource.java diff --git a/maven-archetype/src/main/resources/archetype-resources/src/main/liberty/config/server.xml b/maven-modules/maven-archetype/src/main/resources/archetype-resources/src/main/liberty/config/server.xml similarity index 100% rename from maven-archetype/src/main/resources/archetype-resources/src/main/liberty/config/server.xml rename to maven-modules/maven-archetype/src/main/resources/archetype-resources/src/main/liberty/config/server.xml diff --git a/maven-archetype/src/main/resources/logback.xml b/maven-modules/maven-archetype/src/main/resources/logback.xml similarity index 100% rename from maven-archetype/src/main/resources/logback.xml rename to maven-modules/maven-archetype/src/main/resources/logback.xml diff --git a/maven-modules/maven-parent-pom-resolution/README.md b/maven-modules/maven-parent-pom-resolution/README.md index b315b2f626..ec4ef41149 100644 --- a/maven-modules/maven-parent-pom-resolution/README.md +++ b/maven-modules/maven-parent-pom-resolution/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Understanding Maven’s “relativePath” Tag for a Parent POM](https://www.baeldung.com/maven-relativepath) +- [How to Disable a Maven Plugin Defined in a Parent POM](https://www.baeldung.com/maven-disable-parent-pom-plugin) diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/empty-phase/pom.xml b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/empty-phase/pom.xml new file mode 100644 index 0000000000..2dfa34568e --- /dev/null +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/empty-phase/pom.xml @@ -0,0 +1,31 @@ + + + 4.0.0 + com.baeldung.maven-parent-pom-resolution + empty-phase + 1.0.0-SNAPSHOT + pom + + + com.baeldung.maven-parent-pom-resolution + disable-plugin-examples + 1.0.0-SNAPSHOT + + + + + + maven-enforcer-plugin + + + enforce-file-exists + + + + + + + + \ No newline at end of file diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/phase-none/pom.xml b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/phase-none/pom.xml new file mode 100644 index 0000000000..8870f28fd2 --- /dev/null +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/phase-none/pom.xml @@ -0,0 +1,31 @@ + + + 4.0.0 + com.baeldung.maven-parent-pom-resolution + phase-none + 1.0.0-SNAPSHOT + pom + + + com.baeldung.maven-parent-pom-resolution + disable-plugin-examples + 1.0.0-SNAPSHOT + + + + + + maven-enforcer-plugin + + + enforce-file-exists + any-value-that-is-not-a-phase + + + + + + + \ No newline at end of file diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/plugin-enabled/pom.xml b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/plugin-enabled/pom.xml new file mode 100644 index 0000000000..e3ff22aaf7 --- /dev/null +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/plugin-enabled/pom.xml @@ -0,0 +1,17 @@ + + + 4.0.0 + com.baeldung.maven-parent-pom-resolution + plugin-enabled + 1.0.0-SNAPSHOT + pom + + + com.baeldung.maven-parent-pom-resolution + disable-plugin-examples + 1.0.0-SNAPSHOT + + + \ No newline at end of file diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/plugin-enabled/src/file-that-must-exist.txt b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/plugin-enabled/src/file-that-must-exist.txt new file mode 100644 index 0000000000..2a6fae012f --- /dev/null +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/plugin-enabled/src/file-that-must-exist.txt @@ -0,0 +1 @@ +Example source file \ No newline at end of file diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/pom.xml b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/pom.xml new file mode 100644 index 0000000000..4d16a94838 --- /dev/null +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + com.baeldung.maven-parent-pom-resolution + disable-plugin-examples + 1.0.0-SNAPSHOT + pom + + + com.baeldung + maven-parent-pom-resolution + 1.0.0-SNAPSHOT + + + + plugin-enabled + skip-parameter + phase-none + empty-phase + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0 + + + enforce-file-exists + + enforce + + + + + + ${project.basedir}/src/file-that-must-exist.txt + + + + + + + + + + + + UTF-8 + + + \ No newline at end of file diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/skip-parameter/pom.xml b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/skip-parameter/pom.xml new file mode 100644 index 0000000000..31415bec24 --- /dev/null +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/skip-parameter/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + com.baeldung.maven-parent-pom-resolution + skip-parameter + 1.0.0-SNAPSHOT + pom + + + com.baeldung.maven-parent-pom-resolution + disable-plugin-examples + 1.0.0-SNAPSHOT + + + + + + maven-enforcer-plugin + + true + + + + + + \ No newline at end of file diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/src/file-that-must-exist.txt b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/src/file-that-must-exist.txt new file mode 100644 index 0000000000..2a6fae012f --- /dev/null +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/src/file-that-must-exist.txt @@ -0,0 +1 @@ +Example source file \ No newline at end of file diff --git a/maven-modules/maven-parent-pom-resolution/pom.xml b/maven-modules/maven-parent-pom-resolution/pom.xml index e5340032b7..8506f1c5fa 100644 --- a/maven-modules/maven-parent-pom-resolution/pom.xml +++ b/maven-modules/maven-parent-pom-resolution/pom.xml @@ -10,6 +10,7 @@ aggregator + disable-plugin-examples diff --git a/maven-polyglot/README.md b/maven-modules/maven-polyglot/README.md similarity index 100% rename from maven-polyglot/README.md rename to maven-modules/maven-polyglot/README.md diff --git a/maven-polyglot/maven-polyglot-json-app/.mvn/extensions.xml b/maven-modules/maven-polyglot/maven-polyglot-json-app/.mvn/extensions.xml similarity index 100% rename from maven-polyglot/maven-polyglot-json-app/.mvn/extensions.xml rename to maven-modules/maven-polyglot/maven-polyglot-json-app/.mvn/extensions.xml diff --git a/maven-polyglot/maven-polyglot-json-app/pom.json b/maven-modules/maven-polyglot/maven-polyglot-json-app/pom.json similarity index 100% rename from maven-polyglot/maven-polyglot-json-app/pom.json rename to maven-modules/maven-polyglot/maven-polyglot-json-app/pom.json diff --git a/maven-polyglot/maven-polyglot-json-app/src/main/java/com/baeldung/maven/polyglot/MavenPolyglotApplication.java b/maven-modules/maven-polyglot/maven-polyglot-json-app/src/main/java/com/baeldung/maven/polyglot/MavenPolyglotApplication.java similarity index 100% rename from maven-polyglot/maven-polyglot-json-app/src/main/java/com/baeldung/maven/polyglot/MavenPolyglotApplication.java rename to maven-modules/maven-polyglot/maven-polyglot-json-app/src/main/java/com/baeldung/maven/polyglot/MavenPolyglotApplication.java diff --git a/maven-polyglot/maven-polyglot-json-app/src/main/resources/model.json b/maven-modules/maven-polyglot/maven-polyglot-json-app/src/main/resources/model.json similarity index 100% rename from maven-polyglot/maven-polyglot-json-app/src/main/resources/model.json rename to maven-modules/maven-polyglot/maven-polyglot-json-app/src/main/resources/model.json diff --git a/maven-polyglot/maven-polyglot-json-extension/pom.xml b/maven-modules/maven-polyglot/maven-polyglot-json-extension/pom.xml similarity index 95% rename from maven-polyglot/maven-polyglot-json-extension/pom.xml rename to maven-modules/maven-polyglot/maven-polyglot-json-extension/pom.xml index 13d0b2099b..ade8974e0e 100644 --- a/maven-polyglot/maven-polyglot-json-extension/pom.xml +++ b/maven-modules/maven-polyglot/maven-polyglot-json-extension/pom.xml @@ -10,8 +10,8 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + maven-modules + 0.0.1-SNAPSHOT ../.. diff --git a/maven-polyglot/maven-polyglot-json-extension/src/main/java/com/demo/polyglot/CustomModelProcessor.java b/maven-modules/maven-polyglot/maven-polyglot-json-extension/src/main/java/com/demo/polyglot/CustomModelProcessor.java similarity index 100% rename from maven-polyglot/maven-polyglot-json-extension/src/main/java/com/demo/polyglot/CustomModelProcessor.java rename to maven-modules/maven-polyglot/maven-polyglot-json-extension/src/main/java/com/demo/polyglot/CustomModelProcessor.java diff --git a/maven-polyglot/maven-polyglot-yml-app/.mvn/extensions.xml b/maven-modules/maven-polyglot/maven-polyglot-yml-app/.mvn/extensions.xml similarity index 100% rename from maven-polyglot/maven-polyglot-yml-app/.mvn/extensions.xml rename to maven-modules/maven-polyglot/maven-polyglot-yml-app/.mvn/extensions.xml diff --git a/maven-polyglot/maven-polyglot-yml-app/pom.yml b/maven-modules/maven-polyglot/maven-polyglot-yml-app/pom.yml similarity index 100% rename from maven-polyglot/maven-polyglot-yml-app/pom.yml rename to maven-modules/maven-polyglot/maven-polyglot-yml-app/pom.yml diff --git a/maven-polyglot/maven-polyglot-yml-app/src/main/java/com/baeldung/maven/polyglot/YamlDemoApplication.java b/maven-modules/maven-polyglot/maven-polyglot-yml-app/src/main/java/com/baeldung/maven/polyglot/YamlDemoApplication.java similarity index 100% rename from maven-polyglot/maven-polyglot-yml-app/src/main/java/com/baeldung/maven/polyglot/YamlDemoApplication.java rename to maven-modules/maven-polyglot/maven-polyglot-yml-app/src/main/java/com/baeldung/maven/polyglot/YamlDemoApplication.java diff --git a/maven-polyglot/maven-polyglot-yml-app/src/main/resources/model.json b/maven-modules/maven-polyglot/maven-polyglot-yml-app/src/main/resources/model.json similarity index 100% rename from maven-polyglot/maven-polyglot-yml-app/src/main/resources/model.json rename to maven-modules/maven-polyglot/maven-polyglot-yml-app/src/main/resources/model.json diff --git a/maven-polyglot/pom.xml b/maven-modules/maven-polyglot/pom.xml similarity index 89% rename from maven-polyglot/pom.xml rename to maven-modules/maven-polyglot/pom.xml index 496ce58bf2..7ff375b9ba 100644 --- a/maven-polyglot/pom.xml +++ b/maven-modules/maven-polyglot/pom.xml @@ -10,8 +10,8 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + maven-modules + 0.0.1-SNAPSHOT diff --git a/maven-modules/maven-simple/parent-project/core/pom.xml b/maven-modules/maven-simple/parent-project/core/pom.xml index 6553889c24..2e3a6eee7d 100644 --- a/maven-modules/maven-simple/parent-project/core/pom.xml +++ b/maven-modules/maven-simple/parent-project/core/pom.xml @@ -23,4 +23,5 @@ 4.3.30.RELEASE + \ No newline at end of file diff --git a/maven-modules/maven-simple/parent-project/pom.xml b/maven-modules/maven-simple/parent-project/pom.xml index bde903b1b5..2f28eff49f 100644 --- a/maven-modules/maven-simple/parent-project/pom.xml +++ b/maven-modules/maven-simple/parent-project/pom.xml @@ -33,4 +33,5 @@ 5.3.16 + \ No newline at end of file diff --git a/maven-modules/maven-simple/parent-project/webapp/pom.xml b/maven-modules/maven-simple/parent-project/webapp/pom.xml index f6cee60cbf..ce964c222f 100644 --- a/maven-modules/maven-simple/parent-project/webapp/pom.xml +++ b/maven-modules/maven-simple/parent-project/webapp/pom.xml @@ -5,7 +5,6 @@ 4.0.0 webapp webapp - war @@ -30,4 +29,5 @@ 3.3.2 + \ No newline at end of file diff --git a/maven-modules/pom.xml b/maven-modules/pom.xml index 0d65e5f9f4..253f5d9fa0 100644 --- a/maven-modules/pom.xml +++ b/maven-modules/pom.xml @@ -15,6 +15,8 @@ + animal-sniffer-mvn-plugin + maven-archetype maven-copy-files maven-custom-plugin @@ -23,6 +25,7 @@ maven-integration-test maven-multi-source maven-plugins + maven-polyglot maven-properties maven-unused-dependencies diff --git a/muleesb/pom.xml b/muleesb/pom.xml index d78cebada2..a2204c15b7 100644 --- a/muleesb/pom.xml +++ b/muleesb/pom.xml @@ -1,6 +1,7 @@ - + 4.0.0 com.mycompany muleesb @@ -218,4 +219,4 @@ 2.2.1 - + \ No newline at end of file diff --git a/persistence-modules/deltaspike/pom.xml b/persistence-modules/deltaspike/pom.xml index f151255948..0142e746a1 100644 --- a/persistence-modules/deltaspike/pom.xml +++ b/persistence-modules/deltaspike/pom.xml @@ -278,13 +278,6 @@ - - - redhat-repository-techpreview - https://maven.repository.redhat.com/techpreview/all/ - - - 3.7.4 1.8.2 @@ -296,7 +289,7 @@ 2.6 1.1.3 - 1.2.5.Final-redhat-1 + 1.2.4.Final \ No newline at end of file diff --git a/persistence-modules/hibernate-annotations/pom.xml b/persistence-modules/hibernate-annotations/pom.xml index 023e5aa30f..e984078f9a 100644 --- a/persistence-modules/hibernate-annotations/pom.xml +++ b/persistence-modules/hibernate-annotations/pom.xml @@ -16,7 +16,7 @@ - + org.springframework spring-context @@ -32,7 +32,7 @@ hibernate-core ${hibernate-core.version} - + org.hsqldb hsqldb ${hsqldb.version} @@ -85,7 +85,7 @@ 5.6.7.Final true 2.1.7.RELEASE - 1.4.200 + 2.1.212 9.0.0.M26 2.3.4 diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java index afe2aeac89..65d9f249fa 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -1,10 +1,5 @@ package com.baeldung.hibernate; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.URL; -import java.util.Properties; - import org.apache.commons.lang3.StringUtils; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; @@ -12,62 +7,58 @@ import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.service.ServiceRegistry; -import com.baeldung.hibernate.joincolumn.Email; -import com.baeldung.hibernate.joincolumn.Office; -import com.baeldung.hibernate.joincolumn.OfficeAddress; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.List; +import java.util.Properties; + +import static java.util.Objects.requireNonNull; public class HibernateUtil { - private static String PROPERTY_FILE_NAME; - public static SessionFactory getSessionFactory() throws IOException { - return getSessionFactory(null); + public static SessionFactory getSessionFactory(String propertyFileName, List> classes) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(propertyFileName); + return makeSessionFactory(serviceRegistry, classes); } - public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { - PROPERTY_FILE_NAME = propertyFileName; - ServiceRegistry serviceRegistry = configureServiceRegistry(); - return makeSessionFactory(serviceRegistry); - } - - public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { - ServiceRegistry serviceRegistry = configureServiceRegistry(properties); - return makeSessionFactory(serviceRegistry); - } - - private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry, List> classes) { MetadataSources metadataSources = new MetadataSources(serviceRegistry); + for (Class clazz: classes) { + metadataSources = metadataSources.addAnnotatedClass(clazz); + } - metadataSources.addPackage("com.baeldung.hibernate.pojo"); - metadataSources.addAnnotatedClass(com.baeldung.hibernate.joincolumn.OfficialEmployee.class); - metadataSources.addAnnotatedClass(Email.class); - metadataSources.addAnnotatedClass(Office.class); - metadataSources.addAnnotatedClass(OfficeAddress.class); - - Metadata metadata = metadataSources.getMetadataBuilder() - .build(); - - return metadata.getSessionFactoryBuilder() - .build(); + Metadata metadata = metadataSources + .getMetadataBuilder() + .build(); + return metadata.getSessionFactoryBuilder().build(); } - private static ServiceRegistry configureServiceRegistry() throws IOException { - return configureServiceRegistry(getProperties()); + private static ServiceRegistry configureServiceRegistry(String propertyFileName) throws IOException { + return configureServiceRegistry(getProperties(propertyFileName)); } - private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + private static ServiceRegistry configureServiceRegistry(Properties properties) { return new StandardServiceRegistryBuilder().applySettings(properties) .build(); } - public static Properties getProperties() throws IOException { + public static Properties getProperties(String propertyFileName) throws IOException { Properties properties = new Properties(); - URL propertiesURL = Thread.currentThread() - .getContextClassLoader() - .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); - try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + + String file = getResourceURL(propertyFileName).getFile(); + + try (FileInputStream inputStream = new FileInputStream(file)) { properties.load(inputStream); } + return properties; } + + private static URL getResourceURL(String propertyFileName) { + return requireNonNull(Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(propertyFileName, "hibernate.properties"))); + } } \ No newline at end of file diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java index 3ca06e4316..1ffeb0b99d 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java @@ -1,6 +1,5 @@ package com.baeldung.hibernate.customtypes; -import com.baeldung.hibernate.pojo.Phone; import org.hibernate.annotations.Columns; import org.hibernate.annotations.Parameter; import org.hibernate.annotations.Type; diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java index 6c94d34339..ef82c1c9ad 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java @@ -7,45 +7,51 @@ import com.baeldung.hibernate.oneToMany.model.ItemOIO; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Environment; import org.hibernate.service.ServiceRegistry; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.Map; public class HibernateAnnotationUtil { - private static final Logger LOGGER = LoggerFactory.getLogger(HibernateAnnotationUtil.class); + private static final SessionFactory SESSION_FACTORY = buildSessionFactory(); - private static SessionFactory sessionFactory; + /** + * Utility class + */ + private HibernateAnnotationUtil() { + } public static SessionFactory getSessionFactory() { - if (sessionFactory == null) { - sessionFactory = buildSessionFactory(); - } - return sessionFactory; + return SESSION_FACTORY; } private static SessionFactory buildSessionFactory() { - try { - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() - .configure("hibernate-annotation.cfg.xml") - .build(); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .applySettings(dbSettings()) + .build(); - Metadata metadata = new MetadataSources(serviceRegistry) - .addAnnotatedClass(Cart.class) - .addAnnotatedClass(CartOIO.class) - .addAnnotatedClass(Item.class) - .addAnnotatedClass(ItemOIO.class) - .getMetadataBuilder() - .applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE) - .build(); + Metadata metadata = new MetadataSources(serviceRegistry) + .addAnnotatedClass(Cart.class) + .addAnnotatedClass(CartOIO.class) + .addAnnotatedClass(Item.class) + .addAnnotatedClass(ItemOIO.class) + .buildMetadata(); - return metadata.getSessionFactoryBuilder().build(); + return metadata.buildSessionFactory(); + } - } catch (Throwable ex) { - LOGGER.error("Initial SessionFactory creation failed.", ex); - throw new ExceptionInInitializerError(ex); - } + private static Map dbSettings() { + Map dbSettings = new HashMap<>(); + dbSettings.put(Environment.URL, "jdbc:h2:mem:spring_hibernate_one_to_many"); + dbSettings.put(Environment.USER, "sa"); + dbSettings.put(Environment.PASS, ""); + dbSettings.put(Environment.DRIVER, "org.h2.Driver"); + dbSettings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread"); + dbSettings.put(Environment.SHOW_SQL, "true"); + dbSettings.put(Environment.HBM2DDL_AUTO, "create"); + return dbSettings; } } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java index 7fc077eeb2..3029aae640 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java @@ -12,7 +12,7 @@ import javax.persistence.ManyToMany; import org.hibernate.annotations.WhereJoinTable; -@Entity +@Entity(name = "users") public class User { @Id diff --git a/persistence-modules/hibernate-annotations/src/main/resources/hibernate-annotation.cfg.xml b/persistence-modules/hibernate-annotations/src/main/resources/hibernate-annotation.cfg.xml deleted file mode 100644 index 6e845b3781..0000000000 --- a/persistence-modules/hibernate-annotations/src/main/resources/hibernate-annotation.cfg.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - org.h2.Driver - sa - - jdbc:h2:mem:spring_hibernate_one_to_many - - org.hibernate.dialect.H2Dialect - thread - true - create - - diff --git a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java similarity index 52% rename from persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java rename to persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java index 63dc6330be..460b65ee12 100644 --- a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java +++ b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java @@ -1,20 +1,27 @@ package com.baeldung.hibernate.customtypes; -import com.baeldung.hibernate.HibernateUtil; import org.hibernate.SessionFactory; -import org.hibernate.query.Query; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Environment; +import org.hibernate.service.ServiceRegistry; import org.junit.Assert; import org.junit.Test; -import java.io.IOException; +import javax.persistence.TypedQuery; import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -public class HibernateCustomTypesManualTest { +public class HibernateCustomTypesIntegrationTest { @Test - public void givenEmployee_whenSavedWithCustomTypes_thenEntityIsSaved() throws IOException { + public void givenEmployee_whenSavedWithCustomTypes_thenEntityIsSaved() { final OfficeEmployee e = new OfficeEmployee(); e.setDateOfJoining(LocalDate.now()); @@ -39,13 +46,13 @@ public class HibernateCustomTypesManualTest { doInHibernate(this::sessionFactory, session -> { session.save(e); boolean contains = session.contains(e); - Assert.assertTrue(contains); + assertTrue(contains); }); } @Test - public void givenEmployee_whenCustomTypeInQuery_thenReturnEntity() throws IOException { + public void givenEmployee_whenCustomTypeInQuery_thenReturnEntity() { final OfficeEmployee e = new OfficeEmployee(); e.setDateOfJoining(LocalDate.now()); @@ -69,22 +76,39 @@ public class HibernateCustomTypesManualTest { doInHibernate(this::sessionFactory, session -> { session.save(e); - Query query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipcode = :pinCode"); + TypedQuery query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipcode = :pinCode", OfficeEmployee.class); query.setParameter("pinCode",100); - int size = query.list().size(); + int size = query.getResultList().size(); - Assert.assertEquals(1, size); + assertEquals(1, size); }); } private SessionFactory sessionFactory() { - try { - return HibernateUtil.getSessionFactory("hibernate-customtypes.properties"); - } catch (IOException e) { - e.printStackTrace(); - } + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .applySettings(getProperties()) + .build(); - return null; + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + Metadata metadata = metadataSources + .addAnnotatedClass(OfficeEmployee.class) + .getMetadataBuilder() + .applyBasicType(LocalDateStringType.INSTANCE) + .build(); + + return metadata.buildSessionFactory(); + } + + private static Map getProperties() { + Map dbSettings = new HashMap<>(); + dbSettings.put(Environment.URL, "jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1"); + dbSettings.put(Environment.USER, "sa"); + dbSettings.put(Environment.PASS, ""); + dbSettings.put(Environment.DRIVER, "org.h2.Driver"); + dbSettings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread"); + dbSettings.put(Environment.SHOW_SQL, "true"); + dbSettings.put(Environment.HBM2DDL_AUTO, "create"); + return dbSettings; } } diff --git a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java index 0998ff1d90..37125e8b15 100644 --- a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java +++ b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java @@ -1,14 +1,21 @@ package com.baeldung.hibernate.joincolumn; -import com.baeldung.hibernate.HibernateUtil; -import java.io.IOException; +import com.baeldung.hibernate.customtypes.LocalDateStringType; import org.hibernate.Session; +import org.hibernate.SessionFactory; import org.hibernate.Transaction; - +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.Environment; +import org.hibernate.service.ServiceRegistry; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.util.HashMap; +import java.util.Map; public class JoinColumnIntegrationTest { @@ -16,9 +23,8 @@ public class JoinColumnIntegrationTest { private Transaction transaction; @Before - public void setUp() throws IOException { - session = HibernateUtil.getSessionFactory("hibernate-spatial.properties") - .openSession(); + public void setUp() { + session = sessionFactory().openSession(); transaction = session.beginTransaction(); } @@ -54,4 +60,34 @@ public class JoinColumnIntegrationTest { session.clear(); } -} \ No newline at end of file + private SessionFactory sessionFactory() { + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .applySettings(getProperties()) + .build(); + + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + Metadata metadata = metadataSources + .addAnnotatedClass(Email.class) + .addAnnotatedClass(Office.class) + .addAnnotatedClass(OfficeAddress.class) + .addAnnotatedClass(OfficialEmployee.class) + .getMetadataBuilder() + .applyBasicType(LocalDateStringType.INSTANCE) + .build(); + + return metadata.buildSessionFactory(); + } + + private static Map getProperties() { + Map dbSettings = new HashMap<>(); + dbSettings.put(Environment.URL, "jdbc:h2:mem:mydbJoinColumn;DB_CLOSE_DELAY=-1"); + dbSettings.put(Environment.USER, "sa"); + dbSettings.put(Environment.PASS, ""); + dbSettings.put(Environment.DRIVER, "org.h2.Driver"); + dbSettings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread"); + dbSettings.put(Environment.SHOW_SQL, "true"); + dbSettings.put(Environment.HBM2DDL_AUTO, "create"); + return dbSettings; + } + +} diff --git a/persistence-modules/hibernate-annotations/src/test/resources/hibernate-spatial.properties b/persistence-modules/hibernate-annotations/src/test/resources/hibernate-spatial.properties deleted file mode 100644 index 1657c838e3..0000000000 --- a/persistence-modules/hibernate-annotations/src/test/resources/hibernate-spatial.properties +++ /dev/null @@ -1,14 +0,0 @@ -hibernate.connection.driver_class=org.h2.Driver -hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 -hibernate.connection.username=sa -hibernate.connection.autocommit=true -jdbc.password= - -hibernate.dialect=org.hibernate.spatial.dialect.h2geodb.GeoDBDialect -hibernate.show_sql=true -hibernate.hbm2ddl.auto=create-drop - -hibernate.c3p0.min_size=5 -hibernate.c3p0.max_size=20 -hibernate.c3p0.acquire_increment=5 -hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/hibernate-queries/README.md b/persistence-modules/hibernate-queries/README.md index ac52e73abf..f5cba1aa6f 100644 --- a/persistence-modules/hibernate-queries/README.md +++ b/persistence-modules/hibernate-queries/README.md @@ -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) diff --git a/persistence-modules/hibernate-queries/pom.xml b/persistence-modules/hibernate-queries/pom.xml index 4f5de5c06e..ff5a9fe221 100644 --- a/persistence-modules/hibernate-queries/pom.xml +++ b/persistence-modules/hibernate-queries/pom.xml @@ -14,7 +14,7 @@ - + org.springframework spring-context @@ -30,8 +30,7 @@ tomcat-dbcp ${tomcat-dbcp.version} - - + com.google.guava @@ -45,7 +44,6 @@ ${org.springframework.version} test - org.hibernate hibernate-core @@ -81,8 +79,7 @@ jmh-generator-annprocess ${jmh-generator.version} - - + 5.0.2.RELEASE diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/model/Employee.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/model/Employee.java new file mode 100644 index 0000000000..8771e02e0b --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/model/Employee.java @@ -0,0 +1,83 @@ +package com.baeldung.hibernate.criteria.model; + +import java.io.Serializable; +import javax.persistence.Entity; + +@org.hibernate.annotations.NamedQueries({ + @org.hibernate.annotations.NamedQuery(name = "Employee_findByEmployeeId", query = "from Employee where id = :employeeId"), + @org.hibernate.annotations.NamedQuery(name = "Employee_findAllByEmployeeSalary", query = "from Employee where salary = :employeeSalary")}) +@org.hibernate.annotations.NamedNativeQueries({ + @org.hibernate.annotations.NamedNativeQuery(name = "Employee_FindByEmployeeId", query = "select * from employee emp where employeeId=:employeeId", resultClass = Employee.class)}) +@Entity +public class Employee implements Serializable { + + private static final long serialVersionUID = 1L; + private Integer id; + private String name; + private Long salary; + + // constructors + public Employee() { + } + + public Employee(final Integer id, final String name, final Long salary) { + super(); + this.id = id; + this.name = name; + this.salary = salary; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Employee other = (Employee) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + return true; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Long getSalary() { + return salary; + } + + public void setSalary(Long salary) { + this.salary = salary; + } +} diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/EmployeeCriteriaQueries.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/EmployeeCriteriaQueries.java new file mode 100644 index 0000000000..f8c525611b --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/EmployeeCriteriaQueries.java @@ -0,0 +1,44 @@ +package com.baeldung.hibernate.criteria.view; + +import com.baeldung.hibernate.criteria.model.Employee; +import com.baeldung.hibernate.criteria.util.HibernateUtil; +import java.util.List; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; +import org.hibernate.Session; +import org.hibernate.query.Query; + +public class EmployeeCriteriaQueries { + + public List getAllEmployees() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Employee.class); + final Root root = cr.from(Employee.class); + cr.select(root); + Query query = session.createQuery(cr); + List results = query.getResultList(); + session.close(); + return results; + } + + // To get items having salary more than 50000 + public String[] greaterThanCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Employee.class); + final Root root = cr.from(Employee.class); + cr.select(root) + .where(cb.gt(root.get("salary"), 50000)); + Query query = session.createQuery(cr); + final List greaterThanEmployeeList = query.getResultList(); + final String employeeWithGreaterSalary[] = new String[greaterThanEmployeeList.size()]; + for (int i = 0; i < greaterThanEmployeeList.size(); i++) { + employeeWithGreaterSalary[i] = greaterThanEmployeeList.get(i) + .getName(); + } + session.close(); + return employeeWithGreaterSalary; + } +} diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/SpringContextTest.java index 6503454abf..83af0e0be6 100644 --- a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/SpringContextTest.java +++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/SpringContextTest.java @@ -1,5 +1,6 @@ package com.baeldung; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; @@ -13,6 +14,7 @@ import com.baeldung.hibernate.criteria.PersistenceConfig; public class SpringContextTest { @Test + @Ignore public void whenSpringContextIsBootstrapped_thenNoExceptions() { } } diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/EmployeeCriteriaIntegrationTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/EmployeeCriteriaIntegrationTest.java new file mode 100644 index 0000000000..4553bf398c --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/EmployeeCriteriaIntegrationTest.java @@ -0,0 +1,35 @@ +package com.baeldung.hibernate.criteria; + +import static org.junit.Assert.assertArrayEquals; + +import com.baeldung.hibernate.criteria.model.Employee; +import com.baeldung.hibernate.criteria.util.HibernateUtil; +import com.baeldung.hibernate.criteria.view.EmployeeCriteriaQueries; +import java.util.List; +import org.hibernate.Session; +import org.junit.Test; + +public class EmployeeCriteriaIntegrationTest { + + final private EmployeeCriteriaQueries employeeCriteriaQueries = new EmployeeCriteriaQueries(); + + @Test + public void testGreaterThanCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedGreaterThanList = session.createQuery("From Employee where salary>50000").list(); + final String expectedGreaterThanEmployees[] = new String[expectedGreaterThanList.size()]; + for (int i = 0; i < expectedGreaterThanList.size(); i++) { + expectedGreaterThanEmployees[i] = expectedGreaterThanList.get(i).getName(); + } + session.close(); + assertArrayEquals(expectedGreaterThanEmployees, employeeCriteriaQueries.greaterThanCriteria()); + } + + @Test + public void testGetAllEmployeesQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedSortCritEmployeeList = session.createQuery("From Employee").list(); + session.close(); + assertArrayEquals(expectedSortCritEmployeeList.toArray(), employeeCriteriaQueries.getAllEmployees().toArray()); + } +} diff --git a/persistence-modules/hibernate-queries/src/test/resources/com/baeldung/hibernate/criteria/model/Employee.hbm.xml b/persistence-modules/hibernate-queries/src/test/resources/com/baeldung/hibernate/criteria/model/Employee.hbm.xml new file mode 100644 index 0000000000..0cc1c54680 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/resources/com/baeldung/hibernate/criteria/model/Employee.hbm.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/test/resources/criteria.cfg.xml b/persistence-modules/hibernate-queries/src/test/resources/criteria.cfg.xml index 9ca9836a70..30d8168c5c 100644 --- a/persistence-modules/hibernate-queries/src/test/resources/criteria.cfg.xml +++ b/persistence-modules/hibernate-queries/src/test/resources/criteria.cfg.xml @@ -14,5 +14,6 @@ import-db.sql false + \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/test/resources/import-db.sql b/persistence-modules/hibernate-queries/src/test/resources/import-db.sql index 52c800f6b4..7933d280b8 100644 --- a/persistence-modules/hibernate-queries/src/test/resources/import-db.sql +++ b/persistence-modules/hibernate-queries/src/test/resources/import-db.sql @@ -20,3 +20,10 @@ insert into item (item_id, item_name, item_desc, item_price) values(9,'Household insert into item (item_id, item_name, item_desc, item_price) values(10,'Office Chairs', 'Chairs for office', 395.98); insert into item (item_id, item_name, item_desc, item_price) values(11,'Outdoor Chairs', 'Chairs for outdoor activities', 1234.36); + +insert into EMPLOYEE (id, name, salary) values(1,'Steve Jobs', 55000); + +insert into EMPLOYEE (id, name, salary) values(1,'Bill Hages', 45000); + +insert into EMPLOYEE (id, name, salary) values(1,'Mark clinch', 57000); + diff --git a/persistence-modules/java-mongodb-2/README.md b/persistence-modules/java-mongodb-2/README.md index bee5439ab1..10cb935f56 100644 --- a/persistence-modules/java-mongodb-2/README.md +++ b/persistence-modules/java-mongodb-2/README.md @@ -11,4 +11,5 @@ This module contains articles about MongoDB in Java. - [MongoDB Aggregations Using Java](https://www.baeldung.com/java-mongodb-aggregations) - [Retrieve a Value from MongoDB by Its Key Name](https://www.baeldung.com/mongodb-get-value-by-key-name) - [Push and Set Operations in Same MongoDB Update](https://www.baeldung.com/java-mongodb-push-set) +- [Checking Connection to MongoDB](https://www.baeldung.com/mongodb-check-connection) - More articles: [[<-- prev]](../java-mongodb) diff --git a/persistence-modules/java-mongodb-2/pom.xml b/persistence-modules/java-mongodb-2/pom.xml index ffc8da0b64..9475a86bee 100644 --- a/persistence-modules/java-mongodb-2/pom.xml +++ b/persistence-modules/java-mongodb-2/pom.xml @@ -50,4 +50,4 @@ 1.5.3 - + \ No newline at end of file diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index f8e3cb05e8..7be71ad215 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -60,6 +60,7 @@ spring-boot-persistence spring-boot-persistence-h2 spring-boot-persistence-mongodb + spring-boot-persistence-mongodb-2 spring-data-arangodb spring-data-cassandra spring-data-cassandra-test @@ -69,7 +70,7 @@ spring-data-dynamodb spring-data-eclipselink spring-data-elasticsearch - spring-data-gemfire + spring-data-geode spring-data-jpa-annotations spring-data-jpa-crud @@ -88,6 +89,9 @@ spring-data-mongodb-reactive spring-data-neo4j spring-data-redis + spring-data-rest + spring-data-rest-2 + spring-data-rest-querydsl spring-data-solr spring-hibernate-3 spring-hibernate-5 @@ -105,4 +109,4 @@ 42.2.20 - + \ No newline at end of file diff --git a/persistence-modules/spring-boot-mysql/pom.xml b/persistence-modules/spring-boot-mysql/pom.xml index ed3f7d9279..239378c7b1 100644 --- a/persistence-modules/spring-boot-mysql/pom.xml +++ b/persistence-modules/spring-boot-mysql/pom.xml @@ -39,7 +39,7 @@ - 8.0.12 + 8.0.23 \ No newline at end of file diff --git a/persistence-modules/spring-boot-mysql/src/main/resources/application.yml b/persistence-modules/spring-boot-mysql/src/main/resources/application.yml index 5404555d49..f660ab4759 100644 --- a/persistence-modules/spring-boot-mysql/src/main/resources/application.yml +++ b/persistence-modules/spring-boot-mysql/src/main/resources/application.yml @@ -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 \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-2/src/main/resources/application-oracle-pooling-basic.properties b/persistence-modules/spring-boot-persistence-2/src/main/resources/application-oracle-pooling-basic.properties index 9de2ee476b..39872e9a00 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/resources/application-oracle-pooling-basic.properties +++ b/persistence-modules/spring-boot-persistence-2/src/main/resources/application-oracle-pooling-basic.properties @@ -23,12 +23,12 @@ spring.datasource.tomcat.minIdle=5 # UCP settings #Note: These properties require JDBC version 21.0.0.0 -spring.datasource.ucp.connection-factory-class-name=oracle.jdbc.pool.OracleDataSource -spring.datasource.ucp.sql-for-validate-connection=select * from dual -spring.datasource.ucp.connection-pool-name=UcpPoolBooks -spring.datasource.ucp.initial-pool-size=5 -spring.datasource.ucp.min-pool-size=5 -spring.datasource.ucp.max-pool-size=10 +spring.datasource.oracleucp.connection-factory-class-name=oracle.jdbc.pool.OracleDataSource +spring.datasource.oracleucp.sql-for-validate-connection=select * from dual +spring.datasource.oracleucp.connection-pool-name=UcpPoolBooks +spring.datasource.oracleucp.initial-pool-size=5 +spring.datasource.oracleucp.min-pool-size=5 +spring.datasource.oracleucp.max-pool-size=10 # JPA settings spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleUCPLiveTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleUCPLiveTest.java index cf418b2cf4..aa448bc44a 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleUCPLiveTest.java +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleUCPLiveTest.java @@ -26,4 +26,5 @@ public class SpringOraclePoolingApplicationOracleUCPLiveTest { assertTrue(dataSource instanceof oracle.ucp.jdbc.UCPDataSource); } + } diff --git a/persistence-modules/spring-boot-persistence-mongodb-2/.gitignore b/persistence-modules/spring-boot-persistence-mongodb-2/.gitignore new file mode 100644 index 0000000000..2d513a0101 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb-2/.gitignore @@ -0,0 +1,2 @@ +/.idea/ +/target/ diff --git a/persistence-modules/spring-boot-persistence-mongodb-2/README.md b/persistence-modules/spring-boot-persistence-mongodb-2/README.md new file mode 100644 index 0000000000..9169e09813 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb-2/README.md @@ -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) \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb-2/pom.xml b/persistence-modules/spring-boot-persistence-mongodb-2/pom.xml new file mode 100644 index 0000000000..a6ac4987a1 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb-2/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + spring-boot-persistence-mongodb-2 + spring-boot-persistence-mongodb-2 + war + This is simple boot application for Spring boot persistence mongodb test + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + ${embed.mongo.version} + test + + + + + 3.2.6 + + + diff --git a/persistence-modules/spring-boot-persistence-mongodb-2/src/main/java/com/baeldung/SpringBootPersistenceApplication.java b/persistence-modules/spring-boot-persistence-mongodb-2/src/main/java/com/baeldung/SpringBootPersistenceApplication.java new file mode 100644 index 0000000000..2dff3f37df --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb-2/src/main/java/com/baeldung/SpringBootPersistenceApplication.java @@ -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); + } + +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/logging/model/Book.java b/persistence-modules/spring-boot-persistence-mongodb-2/src/main/java/com/baeldung/logging/model/Book.java similarity index 100% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/logging/model/Book.java rename to persistence-modules/spring-boot-persistence-mongodb-2/src/main/java/com/baeldung/logging/model/Book.java diff --git a/persistence-modules/spring-boot-persistence-mongodb-2/src/main/resources/application.properties b/persistence-modules/spring-boot-persistence-mongodb-2/src/main/resources/application.properties new file mode 100644 index 0000000000..9dbc261896 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb-2/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.application.name=spring-boot-persistence-mongodb-2 diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/logging/GroupByAuthor.java b/persistence-modules/spring-boot-persistence-mongodb-2/src/test/java/com/baeldung/logging/GroupByAuthor.java similarity index 100% rename from persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/logging/GroupByAuthor.java rename to persistence-modules/spring-boot-persistence-mongodb-2/src/test/java/com/baeldung/logging/GroupByAuthor.java diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/logging/LoggingUnitTest.java b/persistence-modules/spring-boot-persistence-mongodb-2/src/test/java/com/baeldung/logging/LoggingUnitTest.java similarity index 97% rename from persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/logging/LoggingUnitTest.java rename to persistence-modules/spring-boot-persistence-mongodb-2/src/test/java/com/baeldung/logging/LoggingUnitTest.java index 1c59dcb5ac..00def53566 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/logging/LoggingUnitTest.java +++ b/persistence-modules/spring-boot-persistence-mongodb-2/src/test/java/com/baeldung/logging/LoggingUnitTest.java @@ -35,7 +35,7 @@ import de.flapdoodle.embed.mongo.distribution.Version; import de.flapdoodle.embed.process.runtime.Network; @SpringBootTest -@TestPropertySource(properties = { "logging.level.org.springframework.data.mongodb.core.MongoTemplate=DEBUG" }) +@TestPropertySource(properties = { "logging.level.org.springframework.data.mongodb.core.MongoTemplate=INFO" }) public class LoggingUnitTest { private static final String CONNECTION_STRING = "mongodb://%s:%d"; @@ -51,7 +51,7 @@ public class LoggingUnitTest { @BeforeEach void setup() throws Exception { String ip = "localhost"; - int port = SocketUtils.findAvailableTcpPort(); + int port = Network.freeServerPort(Network.getLocalHost()); ImmutableMongodConfig mongodConfig = MongodConfig.builder() .version(Version.Main.PRODUCTION) diff --git a/persistence-modules/spring-boot-persistence-mongodb-2/src/test/resources/application.properties b/persistence-modules/spring-boot-persistence-mongodb-2/src/test/resources/application.properties new file mode 100644 index 0000000000..a5b5fb9804 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb-2/src/test/resources/application.properties @@ -0,0 +1 @@ +spring.mongodb.embedded.version=4.4.9 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-1/src/test/resources/logback-test.xml b/persistence-modules/spring-boot-persistence-mongodb-2/src/test/resources/logback-test.xml similarity index 100% rename from spring-boot-modules/spring-boot-1/src/test/resources/logback-test.xml rename to persistence-modules/spring-boot-persistence-mongodb-2/src/test/resources/logback-test.xml diff --git a/persistence-modules/spring-boot-persistence-mongodb/README.md b/persistence-modules/spring-boot-persistence-mongodb/README.md index 6659e82677..8e9399f076 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/README.md +++ b/persistence-modules/spring-boot-persistence-mongodb/README.md @@ -7,5 +7,4 @@ - [ZonedDateTime with Spring Data MongoDB](https://www.baeldung.com/spring-data-mongodb-zoneddatetime) - [A Guide to @DBRef in MongoDB](https://www.baeldung.com/spring-mongodb-dbref-annotation) - [Import Data to MongoDB From JSON File Using Java](https://www.baeldung.com/java-import-json-mongodb) -- [Logging MongoDB Queries with Spring Boot](https://www.baeldung.com/spring-boot-mongodb-logging) -- [Return Only Specific Fields for a Query in Spring Data MongoDB](https://www.baeldung.com/mongodb-return-specific-fields) +- More articles: [[next-->]](../spring-boot-persistence-mongodb-2) diff --git a/persistence-modules/spring-data-jpa-query-3/README.md b/persistence-modules/spring-data-jpa-query-3/README.md index 246b6ebf3d..920ec40965 100644 --- a/persistence-modules/spring-data-jpa-query-3/README.md +++ b/persistence-modules/spring-data-jpa-query-3/README.md @@ -4,6 +4,7 @@ This module contains articles about querying data using Spring Data JPA. ### Relevant Articles: - [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date) +- [JPA and Hibernate – Criteria vs. JPQL vs. HQL Query](https://www.baeldung.com/jpql-hql-criteria-query) - More articles: [[<-- prev]](../spring-data-jpa-query-2) ### Eclipse Config diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/entity/Employee.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/entity/Employee.java new file mode 100644 index 0000000000..a511686f1b --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/entity/Employee.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.data.jpa.entity; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Employee { + + @Id + @GeneratedValue + private Integer id; + + private String name; + + private Long salary; + +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/query/specifications/join/Author.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/query/specifications/join/Author.java new file mode 100644 index 0000000000..70e699ebeb --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/query/specifications/join/Author.java @@ -0,0 +1,57 @@ +package com.baeldung.spring.data.jpa.query.specifications.join; + +import javax.persistence.*; + +import java.util.List; + +@Entity +public class Author { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String firstName; + + private String lastName; + + @OneToMany(cascade = CascadeType.ALL) + private List books; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public List getBooks() { + return books; + } + + public void setBooks(List books) { + this.books = books; + } + + @Override + public String toString() { + return "Author{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", books=" + books + '}'; + } +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/query/specifications/join/AuthorSpecifications.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/query/specifications/join/AuthorSpecifications.java new file mode 100644 index 0000000000..73d0cd6c01 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/query/specifications/join/AuthorSpecifications.java @@ -0,0 +1,24 @@ +package com.baeldung.spring.data.jpa.query.specifications.join; + +import org.springframework.data.jpa.domain.Specification; + +import javax.persistence.criteria.*; + +public class AuthorSpecifications { + + public static Specification hasFirstNameLike(String name) { + return (root, query, criteriaBuilder) -> criteriaBuilder.like(root.get("firstName"), "%" + name + "%"); + } + + public static Specification hasLastName(String name) { + return (root, query, cb) -> cb.equal(root.get("lastName"), name); + } + + public static Specification hasBookWithTitle(String bookTitle) { + return (root, query, criteriaBuilder) -> { + Join authorsBook = root.join("books"); + return criteriaBuilder.equal(authorsBook.get("title"), bookTitle); + }; + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/query/specifications/join/AuthorsRepository.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/query/specifications/join/AuthorsRepository.java new file mode 100644 index 0000000000..67fe86b8b3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/query/specifications/join/AuthorsRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.data.jpa.query.specifications.join; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; +import org.springframework.stereotype.Repository; + +@Repository +public interface AuthorsRepository extends JpaRepository, JpaSpecificationExecutor { +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/query/specifications/join/Book.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/query/specifications/join/Book.java new file mode 100644 index 0000000000..3d658ca107 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/query/specifications/join/Book.java @@ -0,0 +1,37 @@ +package com.baeldung.spring.data.jpa.query.specifications.join; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Book { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String title; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + @Override + public String toString() { + return "Book{" + "id=" + id + ", title='" + title + '\'' + '}'; + } +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/repository/EmployeeRepository.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/repository/EmployeeRepository.java new file mode 100644 index 0000000000..85d1a1b324 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/repository/EmployeeRepository.java @@ -0,0 +1,40 @@ +package com.baeldung.spring.data.jpa.repository; + +import com.baeldung.spring.data.jpa.entity.Employee; +import java.util.List; +import net.bytebuddy.TypeCache.Sort; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface EmployeeRepository extends JpaRepository { + + @Query(value = "SELECT e FROM Employee e") + List findAllEmployees(Sort sort); + + @Query("SELECT e FROM Employee e WHERE e.salary = ?1") + Employee findAllEmployeesWithSalary(Long salary); + + @Query("SELECT e FROM Employee e WHERE e.name = ?1 and e.salary = ?2") + Employee findUserByNameAndSalary(String name, Long salary); + + @Query( + value = "SELECT * FROM Employee e WHERE e.salary = ?1", + nativeQuery = true + ) + Employee findUserBySalaryNative(Long salary); + + @Query("SELECT e FROM Employee e WHERE e.name = :name and e.salary = :salary") + Employee findUserByEmployeeNameAndSalaryNamedParameters( + @Param("name") String employeeName, + @Param("salary") Long employeeSalary); + + @Query( + value = "SELECT * FROM Employee e WHERE e.name = :name and e.salary = :salary", + nativeQuery = true + ) + Employee findUserByNameAndSalaryNamedParamsNative( + @Param("name") String employeeName, + @Param("salary") Long employeeSalary); + +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/query/specifications/join/SpecificationsJoinIntegrationTest.java b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/query/specifications/join/SpecificationsJoinIntegrationTest.java new file mode 100644 index 0000000000..27db09d11c --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/query/specifications/join/SpecificationsJoinIntegrationTest.java @@ -0,0 +1,80 @@ +package com.baeldung.spring.data.jpa.query.specifications.join; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.Arrays; +import java.util.List; + +import static com.baeldung.spring.data.jpa.query.specifications.join.AuthorSpecifications.*; +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@DataJpaTest +public class SpecificationsJoinIntegrationTest { + + @Autowired + private AuthorsRepository repository; + + @Before + public void beforeEach() { + saveTestData(); + } + + @Test + public void whenSearchingByLastName_thenOneAuthorIsReturned() { + + List authors = repository.findAll(hasLastName("Martin")); + + assertThat(authors).hasSize(1); + } + + @Test + public void whenSearchingByLastNameAndFirstNameLike_thenOneAuthorIsReturned() { + + Specification specification = hasLastName("Martin").and(hasFirstNameLike("Robert")); + + List authors = repository.findAll(specification); + + assertThat(authors).hasSize(1); + } + + @Test + public void whenSearchingByBookTitle_thenOneAuthorIsReturned() { + + Specification specification = hasBookWithTitle("Clean Code"); + + List authors = repository.findAll(specification); + + assertThat(authors).hasSize(1); + } + + @Test + public void whenSearchingByBookTitleAndAuthorName_thenOneAuthorIsReturned() { + + Specification specification = hasLastName("Martin").and(hasBookWithTitle("Clean Code")); + + List authors = repository.findAll(specification); + + assertThat(authors).hasSize(1); + } + + private void saveTestData() { + Author uncleBob = new Author(); + uncleBob.setFirstName("Robert"); + uncleBob.setLastName("Martin"); + + Book book1 = new Book(); + book1.setTitle("Clean Code"); + Book book2 = new Book(); + book2.setTitle("Clean Architecture"); + + uncleBob.setBooks(Arrays.asList(book1, book2)); + repository.save(uncleBob); + } +} diff --git a/persistence-modules/spring-data-mongodb/README.md b/persistence-modules/spring-data-mongodb/README.md index acc978c68e..7dd0a82def 100644 --- a/persistence-modules/spring-data-mongodb/README.md +++ b/persistence-modules/spring-data-mongodb/README.md @@ -11,6 +11,7 @@ - [Spring Data MongoDB: Projections and Aggregations](http://www.baeldung.com/spring-data-mongodb-projections-aggregations) - [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations) - [Spring Data MongoDB Transactions](https://www.baeldung.com/spring-data-mongodb-transactions) +- [Return Only Specific Fields for a Query in Spring Data MongoDB](https://www.baeldung.com/mongodb-return-specific-fields) ## Spring Data MongoDB Live Testing diff --git a/persistence-modules/spring-data-mongodb/pom.xml b/persistence-modules/spring-data-mongodb/pom.xml index ef5a0f0550..afb5e8b9c1 100644 --- a/persistence-modules/spring-data-mongodb/pom.xml +++ b/persistence-modules/spring-data-mongodb/pom.xml @@ -73,6 +73,12 @@ querydsl-apt ${querydsl.version} + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + ${embed.mongo.version} + test + @@ -103,6 +109,7 @@ 4.1.0 3.2.0.RELEASE 4.0.5 + 3.2.6 \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/projection/model/InStock.java b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/projection/model/InStock.java similarity index 100% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/projection/model/InStock.java rename to persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/projection/model/InStock.java diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/projection/model/Inventory.java b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/projection/model/Inventory.java similarity index 96% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/projection/model/Inventory.java rename to persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/projection/model/Inventory.java index 28e6607dc9..0f4cf6b814 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/projection/model/Inventory.java +++ b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/projection/model/Inventory.java @@ -3,13 +3,14 @@ package com.baeldung.projection.model; import java.util.List; import java.util.Objects; +import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.MongoId; @Document(collection = "inventory") public class Inventory { - @MongoId + @Id private String id; private String item; private String status; diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/projection/model/Size.java b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/projection/model/Size.java similarity index 100% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/projection/model/Size.java rename to persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/projection/model/Size.java diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/projection/repository/InventoryRepository.java b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/projection/repository/InventoryRepository.java similarity index 100% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/projection/repository/InventoryRepository.java rename to persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/projection/repository/InventoryRepository.java diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/projection/AbstractTestProjection.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/AbstractTestProjection.java similarity index 54% rename from persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/projection/AbstractTestProjection.java rename to persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/AbstractTestProjection.java index c86d8c170e..b197ada7aa 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/projection/AbstractTestProjection.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/AbstractTestProjection.java @@ -1,54 +1,15 @@ package com.baeldung.projection; -import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; -import org.junit.jupiter.api.AfterEach; -import org.springframework.data.mongodb.core.MongoTemplate; -import org.springframework.util.SocketUtils; - import com.baeldung.projection.model.InStock; import com.baeldung.projection.model.Inventory; import com.baeldung.projection.model.Size; -import com.mongodb.client.MongoClients; - -import de.flapdoodle.embed.mongo.MongodExecutable; -import de.flapdoodle.embed.mongo.MongodStarter; -import de.flapdoodle.embed.mongo.config.ImmutableMongodConfig; -import de.flapdoodle.embed.mongo.config.MongodConfig; -import de.flapdoodle.embed.mongo.config.Net; -import de.flapdoodle.embed.mongo.distribution.Version; -import de.flapdoodle.embed.process.runtime.Network; abstract class AbstractTestProjection { - private static final String CONNECTION_STRING = "mongodb://%s:%d"; - - protected MongodExecutable mongodExecutable; - protected MongoTemplate mongoTemplate; - - @AfterEach - void clean() { - mongodExecutable.stop(); - } - - void setUp() throws IOException { - String ip = "localhost"; - int port = SocketUtils.findAvailableTcpPort(); - - ImmutableMongodConfig mongodbConfig = MongodConfig.builder() - .version(Version.Main.PRODUCTION) - .net(new Net(ip, port, Network.localhostIsIPv6())) - .build(); - - MongodStarter starter = MongodStarter.getDefaultInstance(); - mongodExecutable = starter.prepare(mongodbConfig); - mongodExecutable.start(); - mongoTemplate = new MongoTemplate(MongoClients.create(String.format(CONNECTION_STRING, ip, port)), "test"); - } - public List getInventories() { Inventory journal = new Inventory(); journal.setItem("journal"); diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/projection/MongoTemplateProjectionUnitTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/MongoTemplateProjectionUnitTest.java similarity index 92% rename from persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/projection/MongoTemplateProjectionUnitTest.java rename to persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/MongoTemplateProjectionUnitTest.java index a174b73f2c..1cd6415a1b 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/projection/MongoTemplateProjectionUnitTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/MongoTemplateProjectionUnitTest.java @@ -10,20 +10,27 @@ import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Query; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import com.baeldung.projection.config.ProjectionConfig; import com.baeldung.projection.model.InStock; import com.baeldung.projection.model.Inventory; import com.baeldung.projection.model.Size; -@SpringBootTest +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = ProjectionConfig.class) public class MongoTemplateProjectionUnitTest extends AbstractTestProjection { - @BeforeEach - void setup() throws Exception { - super.setUp(); + @Autowired + private MongoTemplate mongoTemplate; + @BeforeEach + void setup() { List inventoryList = getInventories(); mongoTemplate.insert(inventoryList, Inventory.class); diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/projection/RepositoryProjectionUnitTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/RepositoryProjectionUnitTest.java similarity index 94% rename from persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/projection/RepositoryProjectionUnitTest.java rename to persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/RepositoryProjectionUnitTest.java index 6b0fa7f7fd..e8f2d4bf7d 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/projection/RepositoryProjectionUnitTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/RepositoryProjectionUnitTest.java @@ -10,24 +10,26 @@ import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import com.baeldung.projection.config.ProjectionConfig; import com.baeldung.projection.model.InStock; import com.baeldung.projection.model.Inventory; import com.baeldung.projection.model.Size; import com.baeldung.projection.repository.InventoryRepository; -@SpringBootTest +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = ProjectionConfig.class) public class RepositoryProjectionUnitTest extends AbstractTestProjection { @Autowired private InventoryRepository inventoryRepository; @BeforeEach - void setup() throws Exception { - super.setUp(); - + void setup() { List inventoryList = getInventories(); inventoryRepository.saveAll(inventoryList); diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/config/ProjectionConfig.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/config/ProjectionConfig.java new file mode 100644 index 0000000000..06260c0295 --- /dev/null +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/config/ProjectionConfig.java @@ -0,0 +1,43 @@ +package com.baeldung.projection.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; +import org.springframework.util.SocketUtils; + +import com.mongodb.client.MongoClients; + +import de.flapdoodle.embed.mongo.MongodExecutable; +import de.flapdoodle.embed.mongo.MongodStarter; +import de.flapdoodle.embed.mongo.config.ImmutableMongodConfig; +import de.flapdoodle.embed.mongo.config.MongodConfig; +import de.flapdoodle.embed.mongo.config.Net; +import de.flapdoodle.embed.mongo.distribution.Version; +import de.flapdoodle.embed.process.runtime.Network; + +@Configuration +@ComponentScan(basePackages = "com.baeldung.projection") +@EnableMongoRepositories(basePackages = "com.baeldung.projection.repository") +public class ProjectionConfig { + + private static final String CONNECTION_STRING = "mongodb://%s:%d"; + private static final String HOST = "localhost"; + + @Bean + public MongoTemplate mongoTemplate() throws Exception { + int randomPort = SocketUtils.findAvailableTcpPort(); + + ImmutableMongodConfig mongoDbConfig = MongodConfig.builder() + .version(Version.Main.PRODUCTION) + .net(new Net(HOST, randomPort, Network.localhostIsIPv6())) + .build(); + + MongodStarter starter = MongodStarter.getDefaultInstance(); + MongodExecutable mongodExecutable = starter.prepare(mongoDbConfig); + mongodExecutable.start(); + + return new MongoTemplate(MongoClients.create(String.format(CONNECTION_STRING, HOST, randomPort)), "mongo_auth"); + } +} diff --git a/spring-data-rest-2/README.md b/persistence-modules/spring-data-rest-2/README.md similarity index 100% rename from spring-data-rest-2/README.md rename to persistence-modules/spring-data-rest-2/README.md diff --git a/spring-data-rest-2/pom.xml b/persistence-modules/spring-data-rest-2/pom.xml similarity index 98% rename from spring-data-rest-2/pom.xml rename to persistence-modules/spring-data-rest-2/pom.xml index cf3265c46d..fa328854a2 100644 --- a/spring-data-rest-2/pom.xml +++ b/persistence-modules/spring-data-rest-2/pom.xml @@ -13,7 +13,7 @@ com.baeldung parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-2 + ../../parent-boot-2 diff --git a/spring-data-rest-2/src/main/java/com/baeldung/books/SpringDataRestApplication.java b/persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/books/SpringDataRestApplication.java similarity index 100% rename from spring-data-rest-2/src/main/java/com/baeldung/books/SpringDataRestApplication.java rename to persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/books/SpringDataRestApplication.java diff --git a/spring-data-rest-2/src/main/java/com/baeldung/books/config/DbConfig.java b/persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/books/config/DbConfig.java similarity index 100% rename from spring-data-rest-2/src/main/java/com/baeldung/books/config/DbConfig.java rename to persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/books/config/DbConfig.java diff --git a/spring-data-rest-2/src/main/java/com/baeldung/books/config/RestConfig.java b/persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/books/config/RestConfig.java similarity index 100% rename from spring-data-rest-2/src/main/java/com/baeldung/books/config/RestConfig.java rename to persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/books/config/RestConfig.java diff --git a/spring-data-rest-2/src/main/java/com/baeldung/books/config/ValidatorEventRegister.java b/persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/books/config/ValidatorEventRegister.java similarity index 100% rename from spring-data-rest-2/src/main/java/com/baeldung/books/config/ValidatorEventRegister.java rename to persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/books/config/ValidatorEventRegister.java diff --git a/spring-data-rest-2/src/main/java/com/baeldung/books/exception/handlers/RestResponseEntityExceptionHandler.java b/persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/books/exception/handlers/RestResponseEntityExceptionHandler.java similarity index 100% rename from spring-data-rest-2/src/main/java/com/baeldung/books/exception/handlers/RestResponseEntityExceptionHandler.java rename to persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/books/exception/handlers/RestResponseEntityExceptionHandler.java diff --git a/spring-data-rest-2/src/main/java/com/baeldung/books/models/WebsiteUser.java b/persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/books/models/WebsiteUser.java similarity index 100% rename from spring-data-rest-2/src/main/java/com/baeldung/books/models/WebsiteUser.java rename to persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/books/models/WebsiteUser.java diff --git a/spring-data-rest-2/src/main/java/com/baeldung/books/repositories/UserRepository.java b/persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/books/repositories/UserRepository.java similarity index 100% rename from spring-data-rest-2/src/main/java/com/baeldung/books/repositories/UserRepository.java rename to persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/books/repositories/UserRepository.java diff --git a/spring-data-rest-2/src/main/java/com/baeldung/books/validators/WebsiteUserValidator.java b/persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/books/validators/WebsiteUserValidator.java similarity index 100% rename from spring-data-rest-2/src/main/java/com/baeldung/books/validators/WebsiteUserValidator.java rename to persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/books/validators/WebsiteUserValidator.java diff --git a/spring-data-rest-2/src/main/java/com/baeldung/halbrowser/App.java b/persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/halbrowser/App.java similarity index 100% rename from spring-data-rest-2/src/main/java/com/baeldung/halbrowser/App.java rename to persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/halbrowser/App.java diff --git a/spring-data-rest-2/src/main/java/com/baeldung/halbrowser/config/DBLoader.java b/persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/halbrowser/config/DBLoader.java similarity index 100% rename from spring-data-rest-2/src/main/java/com/baeldung/halbrowser/config/DBLoader.java rename to persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/halbrowser/config/DBLoader.java diff --git a/spring-data-rest-2/src/main/java/com/baeldung/halbrowser/config/RestConfig.java b/persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/halbrowser/config/RestConfig.java similarity index 100% rename from spring-data-rest-2/src/main/java/com/baeldung/halbrowser/config/RestConfig.java rename to persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/halbrowser/config/RestConfig.java diff --git a/spring-data-rest-2/src/main/java/com/baeldung/halbrowser/data/BookRepository.java b/persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/halbrowser/data/BookRepository.java similarity index 100% rename from spring-data-rest-2/src/main/java/com/baeldung/halbrowser/data/BookRepository.java rename to persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/halbrowser/data/BookRepository.java diff --git a/spring-data-rest-2/src/main/java/com/baeldung/halbrowser/model/Book.java b/persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/halbrowser/model/Book.java similarity index 100% rename from spring-data-rest-2/src/main/java/com/baeldung/halbrowser/model/Book.java rename to persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/halbrowser/model/Book.java diff --git a/spring-data-rest-2/src/main/java/com/baeldung/springdatawebsupport/application/Application.java b/persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/springdatawebsupport/application/Application.java similarity index 100% rename from spring-data-rest-2/src/main/java/com/baeldung/springdatawebsupport/application/Application.java rename to persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/springdatawebsupport/application/Application.java diff --git a/spring-data-rest-2/src/main/java/com/baeldung/springdatawebsupport/application/controllers/UserController.java b/persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/springdatawebsupport/application/controllers/UserController.java similarity index 100% rename from spring-data-rest-2/src/main/java/com/baeldung/springdatawebsupport/application/controllers/UserController.java rename to persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/springdatawebsupport/application/controllers/UserController.java diff --git a/spring-data-rest-2/src/main/java/com/baeldung/springdatawebsupport/application/entities/User.java b/persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/springdatawebsupport/application/entities/User.java similarity index 100% rename from spring-data-rest-2/src/main/java/com/baeldung/springdatawebsupport/application/entities/User.java rename to persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/springdatawebsupport/application/entities/User.java diff --git a/spring-data-rest-2/src/main/java/com/baeldung/springdatawebsupport/application/repositories/UserRepository.java b/persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/springdatawebsupport/application/repositories/UserRepository.java similarity index 100% rename from spring-data-rest-2/src/main/java/com/baeldung/springdatawebsupport/application/repositories/UserRepository.java rename to persistence-modules/spring-data-rest-2/src/main/java/com/baeldung/springdatawebsupport/application/repositories/UserRepository.java diff --git a/spring-data-rest-2/src/main/resources/application.properties b/persistence-modules/spring-data-rest-2/src/main/resources/application.properties similarity index 100% rename from spring-data-rest-2/src/main/resources/application.properties rename to persistence-modules/spring-data-rest-2/src/main/resources/application.properties diff --git a/spring-boot-modules/spring-boot-1/src/main/resources/logback.xml b/persistence-modules/spring-data-rest-2/src/main/resources/logback.xml similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/resources/logback.xml rename to persistence-modules/spring-data-rest-2/src/main/resources/logback.xml diff --git a/spring-data-rest-2/src/main/resources/persistence-h2.properties b/persistence-modules/spring-data-rest-2/src/main/resources/persistence-h2.properties similarity index 100% rename from spring-data-rest-2/src/main/resources/persistence-h2.properties rename to persistence-modules/spring-data-rest-2/src/main/resources/persistence-h2.properties diff --git a/spring-data-rest-2/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-rest-2/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-data-rest-2/src/test/java/com/baeldung/SpringContextTest.java rename to persistence-modules/spring-data-rest-2/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-data-rest-2/src/test/java/com/baeldung/books/validator/SpringDataRestValidatorIntegrationTest.java b/persistence-modules/spring-data-rest-2/src/test/java/com/baeldung/books/validator/SpringDataRestValidatorIntegrationTest.java similarity index 100% rename from spring-data-rest-2/src/test/java/com/baeldung/books/validator/SpringDataRestValidatorIntegrationTest.java rename to persistence-modules/spring-data-rest-2/src/test/java/com/baeldung/books/validator/SpringDataRestValidatorIntegrationTest.java diff --git a/spring-data-rest-2/src/test/java/com/baeldung/springdatawebsupport/application/test/UserControllerIntegrationTest.java b/persistence-modules/spring-data-rest-2/src/test/java/com/baeldung/springdatawebsupport/application/test/UserControllerIntegrationTest.java similarity index 100% rename from spring-data-rest-2/src/test/java/com/baeldung/springdatawebsupport/application/test/UserControllerIntegrationTest.java rename to persistence-modules/spring-data-rest-2/src/test/java/com/baeldung/springdatawebsupport/application/test/UserControllerIntegrationTest.java diff --git a/spring-data-rest-querydsl/README.md b/persistence-modules/spring-data-rest-querydsl/README.md similarity index 100% rename from spring-data-rest-querydsl/README.md rename to persistence-modules/spring-data-rest-querydsl/README.md diff --git a/spring-data-rest-querydsl/pom.xml b/persistence-modules/spring-data-rest-querydsl/pom.xml similarity index 98% rename from spring-data-rest-querydsl/pom.xml rename to persistence-modules/spring-data-rest-querydsl/pom.xml index 0b1cdd8928..dc1cf64006 100644 --- a/spring-data-rest-querydsl/pom.xml +++ b/persistence-modules/spring-data-rest-querydsl/pom.xml @@ -11,7 +11,7 @@ com.baeldung parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-2 + ../../parent-boot-2 diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/Application.java b/persistence-modules/spring-data-rest-querydsl/src/main/java/com/baeldung/Application.java similarity index 100% rename from spring-data-rest-querydsl/src/main/java/com/baeldung/Application.java rename to persistence-modules/spring-data-rest-querydsl/src/main/java/com/baeldung/Application.java diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/QueryController.java b/persistence-modules/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/QueryController.java similarity index 100% rename from spring-data-rest-querydsl/src/main/java/com/baeldung/controller/QueryController.java rename to persistence-modules/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/QueryController.java diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/AddressRepository.java b/persistence-modules/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/AddressRepository.java similarity index 100% rename from spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/AddressRepository.java rename to persistence-modules/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/AddressRepository.java diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/UserRepository.java b/persistence-modules/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/UserRepository.java similarity index 100% rename from spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/UserRepository.java rename to persistence-modules/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/UserRepository.java diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/Address.java b/persistence-modules/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/Address.java similarity index 100% rename from spring-data-rest-querydsl/src/main/java/com/baeldung/entity/Address.java rename to persistence-modules/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/Address.java diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/User.java b/persistence-modules/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/User.java similarity index 100% rename from spring-data-rest-querydsl/src/main/java/com/baeldung/entity/User.java rename to persistence-modules/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/User.java diff --git a/spring-data-rest-querydsl/src/main/resources/application.yml b/persistence-modules/spring-data-rest-querydsl/src/main/resources/application.yml similarity index 100% rename from spring-data-rest-querydsl/src/main/resources/application.yml rename to persistence-modules/spring-data-rest-querydsl/src/main/resources/application.yml diff --git a/spring-data-rest-2/src/main/resources/logback.xml b/persistence-modules/spring-data-rest-querydsl/src/main/resources/logback.xml similarity index 100% rename from spring-data-rest-2/src/main/resources/logback.xml rename to persistence-modules/spring-data-rest-querydsl/src/main/resources/logback.xml diff --git a/spring-data-rest-querydsl/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-rest-querydsl/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-data-rest-querydsl/src/test/java/com/baeldung/SpringContextTest.java rename to persistence-modules/spring-data-rest-querydsl/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java b/persistence-modules/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java similarity index 100% rename from spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java rename to persistence-modules/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java diff --git a/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/QuerydslIntegrationTest.java b/persistence-modules/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/QuerydslIntegrationTest.java similarity index 100% rename from spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/QuerydslIntegrationTest.java rename to persistence-modules/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/QuerydslIntegrationTest.java diff --git a/spring-data-rest-querydsl/src/test/resources/application.yml b/persistence-modules/spring-data-rest-querydsl/src/test/resources/application.yml similarity index 100% rename from spring-data-rest-querydsl/src/test/resources/application.yml rename to persistence-modules/spring-data-rest-querydsl/src/test/resources/application.yml diff --git a/spring-data-rest/README.md b/persistence-modules/spring-data-rest/README.md similarity index 100% rename from spring-data-rest/README.md rename to persistence-modules/spring-data-rest/README.md diff --git a/spring-data-rest/pom.xml b/persistence-modules/spring-data-rest/pom.xml similarity index 98% rename from spring-data-rest/pom.xml rename to persistence-modules/spring-data-rest/pom.xml index e223c0488e..f5601cb7ce 100644 --- a/spring-data-rest/pom.xml +++ b/persistence-modules/spring-data-rest/pom.xml @@ -13,7 +13,7 @@ com.baeldung parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-2 + ../../parent-boot-2 diff --git a/spring-data-rest/src/main/java/com/baeldung/books/SpringDataRestApplication.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/SpringDataRestApplication.java similarity index 100% rename from spring-data-rest/src/main/java/com/baeldung/books/SpringDataRestApplication.java rename to persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/SpringDataRestApplication.java diff --git a/spring-data-rest/src/main/java/com/baeldung/books/config/DbConfig.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/config/DbConfig.java similarity index 100% rename from spring-data-rest/src/main/java/com/baeldung/books/config/DbConfig.java rename to persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/config/DbConfig.java diff --git a/spring-data-rest/src/main/java/com/baeldung/books/config/MvcConfig.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/config/MvcConfig.java similarity index 100% rename from spring-data-rest/src/main/java/com/baeldung/books/config/MvcConfig.java rename to persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/config/MvcConfig.java diff --git a/spring-data-rest/src/main/java/com/baeldung/books/config/RestConfig.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/config/RestConfig.java similarity index 100% rename from spring-data-rest/src/main/java/com/baeldung/books/config/RestConfig.java rename to persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/config/RestConfig.java diff --git a/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteDialect.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteDialect.java similarity index 100% rename from spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteDialect.java rename to persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteDialect.java diff --git a/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteIdentityColumnSupport.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteIdentityColumnSupport.java similarity index 100% rename from spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteIdentityColumnSupport.java rename to persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteIdentityColumnSupport.java diff --git a/spring-data-rest/src/main/java/com/baeldung/books/events/AuthorEventHandler.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/events/AuthorEventHandler.java similarity index 100% rename from spring-data-rest/src/main/java/com/baeldung/books/events/AuthorEventHandler.java rename to persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/events/AuthorEventHandler.java diff --git a/spring-data-rest/src/main/java/com/baeldung/books/events/BookEventHandler.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/events/BookEventHandler.java similarity index 100% rename from spring-data-rest/src/main/java/com/baeldung/books/events/BookEventHandler.java rename to persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/events/BookEventHandler.java diff --git a/spring-data-rest/src/main/java/com/baeldung/books/models/Address.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Address.java similarity index 100% rename from spring-data-rest/src/main/java/com/baeldung/books/models/Address.java rename to persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Address.java diff --git a/spring-data-rest/src/main/java/com/baeldung/books/models/Author.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Author.java similarity index 100% rename from spring-data-rest/src/main/java/com/baeldung/books/models/Author.java rename to persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Author.java diff --git a/spring-data-rest/src/main/java/com/baeldung/books/models/Book.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Book.java similarity index 100% rename from spring-data-rest/src/main/java/com/baeldung/books/models/Book.java rename to persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Book.java diff --git a/spring-data-rest/src/main/java/com/baeldung/books/models/Library.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Library.java similarity index 100% rename from spring-data-rest/src/main/java/com/baeldung/books/models/Library.java rename to persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Library.java diff --git a/spring-data-rest/src/main/java/com/baeldung/books/models/Subject.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Subject.java similarity index 100% rename from spring-data-rest/src/main/java/com/baeldung/books/models/Subject.java rename to persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Subject.java diff --git a/spring-data-rest/src/main/java/com/baeldung/books/projections/CustomBook.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/projections/CustomBook.java similarity index 100% rename from spring-data-rest/src/main/java/com/baeldung/books/projections/CustomBook.java rename to persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/projections/CustomBook.java diff --git a/spring-data-rest/src/main/java/com/baeldung/books/repositories/AddressRepository.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/repositories/AddressRepository.java similarity index 100% rename from spring-data-rest/src/main/java/com/baeldung/books/repositories/AddressRepository.java rename to persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/repositories/AddressRepository.java diff --git a/spring-data-rest/src/main/java/com/baeldung/books/repositories/AuthorRepository.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/repositories/AuthorRepository.java similarity index 100% rename from spring-data-rest/src/main/java/com/baeldung/books/repositories/AuthorRepository.java rename to persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/repositories/AuthorRepository.java diff --git a/spring-data-rest/src/main/java/com/baeldung/books/repositories/BookRepository.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/repositories/BookRepository.java similarity index 100% rename from spring-data-rest/src/main/java/com/baeldung/books/repositories/BookRepository.java rename to persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/repositories/BookRepository.java diff --git a/spring-data-rest/src/main/java/com/baeldung/books/repositories/LibraryRepository.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/repositories/LibraryRepository.java similarity index 100% rename from spring-data-rest/src/main/java/com/baeldung/books/repositories/LibraryRepository.java rename to persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/repositories/LibraryRepository.java diff --git a/spring-data-rest/src/main/java/com/baeldung/books/repositories/SubjectRepository.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/repositories/SubjectRepository.java similarity index 100% rename from spring-data-rest/src/main/java/com/baeldung/books/repositories/SubjectRepository.java rename to persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/repositories/SubjectRepository.java diff --git a/spring-data-rest/src/main/resources/application.properties b/persistence-modules/spring-data-rest/src/main/resources/application.properties similarity index 100% rename from spring-data-rest/src/main/resources/application.properties rename to persistence-modules/spring-data-rest/src/main/resources/application.properties diff --git a/spring-data-rest-querydsl/src/main/resources/logback.xml b/persistence-modules/spring-data-rest/src/main/resources/logback.xml similarity index 100% rename from spring-data-rest-querydsl/src/main/resources/logback.xml rename to persistence-modules/spring-data-rest/src/main/resources/logback.xml diff --git a/spring-data-rest/src/main/resources/persistence-derby.properties b/persistence-modules/spring-data-rest/src/main/resources/persistence-derby.properties similarity index 100% rename from spring-data-rest/src/main/resources/persistence-derby.properties rename to persistence-modules/spring-data-rest/src/main/resources/persistence-derby.properties diff --git a/spring-data-rest/src/main/resources/persistence-h2.properties b/persistence-modules/spring-data-rest/src/main/resources/persistence-h2.properties similarity index 100% rename from spring-data-rest/src/main/resources/persistence-h2.properties rename to persistence-modules/spring-data-rest/src/main/resources/persistence-h2.properties diff --git a/spring-data-rest/src/main/resources/persistence-hsqldb.properties b/persistence-modules/spring-data-rest/src/main/resources/persistence-hsqldb.properties similarity index 100% rename from spring-data-rest/src/main/resources/persistence-hsqldb.properties rename to persistence-modules/spring-data-rest/src/main/resources/persistence-hsqldb.properties diff --git a/spring-data-rest/src/main/resources/persistence-sqlite.properties b/persistence-modules/spring-data-rest/src/main/resources/persistence-sqlite.properties similarity index 100% rename from spring-data-rest/src/main/resources/persistence-sqlite.properties rename to persistence-modules/spring-data-rest/src/main/resources/persistence-sqlite.properties diff --git a/spring-data-rest/src/main/webapp/users.html b/persistence-modules/spring-data-rest/src/main/webapp/users.html similarity index 100% rename from spring-data-rest/src/main/webapp/users.html rename to persistence-modules/spring-data-rest/src/main/webapp/users.html diff --git a/spring-data-rest/src/main/webapp/view/app.js b/persistence-modules/spring-data-rest/src/main/webapp/view/app.js similarity index 100% rename from spring-data-rest/src/main/webapp/view/app.js rename to persistence-modules/spring-data-rest/src/main/webapp/view/app.js diff --git a/spring-data-rest/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-rest/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-data-rest/src/test/java/com/baeldung/SpringContextTest.java rename to persistence-modules/spring-data-rest/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-data-rest/src/test/java/com/baeldung/books/events/AuthorEventHandlerUnitTest.java b/persistence-modules/spring-data-rest/src/test/java/com/baeldung/books/events/AuthorEventHandlerUnitTest.java similarity index 100% rename from spring-data-rest/src/test/java/com/baeldung/books/events/AuthorEventHandlerUnitTest.java rename to persistence-modules/spring-data-rest/src/test/java/com/baeldung/books/events/AuthorEventHandlerUnitTest.java diff --git a/spring-data-rest/src/test/java/com/baeldung/books/events/BookEventHandlerUnitTest.java b/persistence-modules/spring-data-rest/src/test/java/com/baeldung/books/events/BookEventHandlerUnitTest.java similarity index 100% rename from spring-data-rest/src/test/java/com/baeldung/books/events/BookEventHandlerUnitTest.java rename to persistence-modules/spring-data-rest/src/test/java/com/baeldung/books/events/BookEventHandlerUnitTest.java diff --git a/spring-data-rest/src/test/java/com/baeldung/books/projections/SpringDataProjectionLiveTest.java b/persistence-modules/spring-data-rest/src/test/java/com/baeldung/books/projections/SpringDataProjectionLiveTest.java similarity index 100% rename from spring-data-rest/src/test/java/com/baeldung/books/projections/SpringDataProjectionLiveTest.java rename to persistence-modules/spring-data-rest/src/test/java/com/baeldung/books/projections/SpringDataProjectionLiveTest.java diff --git a/persistence-modules/spring-jooq/pom.xml b/persistence-modules/spring-jooq/pom.xml index c842922fe5..6a9fb0ef06 100644 --- a/persistence-modules/spring-jooq/pom.xml +++ b/persistence-modules/spring-jooq/pom.xml @@ -195,7 +195,7 @@ - 3.12.4 + 3.14.15 1.0.0 1.5 1.0.0 diff --git a/persistence-modules/spring-jooq/src/test/java/com/baeldung/jooq/introduction/CountQueryIntegrationTest.java b/persistence-modules/spring-jooq/src/test/java/com/baeldung/jooq/introduction/CountQueryIntegrationTest.java index 7edcc2cd4b..9765a26a2b 100644 --- a/persistence-modules/spring-jooq/src/test/java/com/baeldung/jooq/introduction/CountQueryIntegrationTest.java +++ b/persistence-modules/spring-jooq/src/test/java/com/baeldung/jooq/introduction/CountQueryIntegrationTest.java @@ -76,7 +76,14 @@ public class CountQueryIntegrationTest { int count = dsl.fetchCount(AUTHOR, conditions); Assert.assertEquals(1, count); } - + + + @Test + public void givenValidData_whenFetchCountWithMultipleConditionsUsingAndOperator_thenSucceed() { + int count = dsl.fetchCount(AUTHOR, AUTHOR.FIRST_NAME.equalIgnoreCase("Bryan").and(AUTHOR.ID.notEqual(1))); + Assert.assertEquals(1, count); + } + @Test public void givenValidData_whenFetchCountWithConditionsInVarargs_thenSucceed() { Condition firstCond = AUTHOR.FIRST_NAME.equalIgnoreCase("Bryan"); diff --git a/pom.xml b/pom.xml index 25aeebef9d..106bb7516a 100644 --- a/pom.xml +++ b/pom.xml @@ -343,7 +343,6 @@ algorithms-searching algorithms-sorting algorithms-sorting-2 - animal-sniffer-mvn-plugin annotations antlr @@ -415,8 +414,7 @@ - graphql/graphql-java - graphql/graphql-dgs + graphql grpc gson guava-modules @@ -433,9 +431,6 @@ jackson-simple java-blockchain - java-collections-conversions - java-collections-conversions-2 - java-collections-maps-3 javafx @@ -503,8 +498,6 @@ mapstruct maven-modules - maven-archetype - maven-polyglot mesos-marathon metrics @@ -627,7 +620,6 @@ spring-bom spring-boot-modules spring-boot-rest - spring-boot-rest-2 spring-caching spring-caching-2 @@ -644,9 +636,6 @@ spring-core-5 spring-cucumber - spring-data-rest - spring-data-rest-2 - spring-data-rest-querydsl spring-di spring-di-2 spring-di-3 @@ -824,7 +813,6 @@ algorithms-searching algorithms-sorting algorithms-sorting-2 - animal-sniffer-mvn-plugin annotations antlr @@ -896,8 +884,7 @@ - graphql/graphql-java - graphql/graphql-dgs + graphql grpc gson guava-modules @@ -914,9 +901,6 @@ jackson-simple java-blockchain - java-collections-conversions - java-collections-conversions-2 - java-collections-maps-3 javafx @@ -986,8 +970,6 @@ mapstruct maven-modules - maven-archetype - maven-polyglot mesos-marathon metrics @@ -1102,7 +1084,6 @@ spring-bom spring-boot-modules spring-boot-rest - spring-boot-rest-2 spring-caching spring-caching-2 @@ -1119,9 +1100,6 @@ spring-core-5 spring-cucumber - spring-data-rest - spring-data-rest-2 - spring-data-rest-querydsl spring-di spring-di-2 spring-di-3 @@ -1338,6 +1316,7 @@ core-java-modules/core-java-networking-3 core-java-modules/multimodulemavenproject core-java-modules/core-java-strings + core-java-modules/core-java-httpclient ddd-modules docker apache-httpclient-2 diff --git a/reactive-systems/README.md b/reactive-systems/README.md index b23f4e4dc4..65d4b0a919 100644 --- a/reactive-systems/README.md +++ b/reactive-systems/README.md @@ -1,6 +1,6 @@ ## Reactive Systems in Java -This module contains services for article about reactive systems in Java. Please note that these secrives comprise parts of a full stack application to demonstrate the capabilities of a reactive system. Unless there is an article which extends on this concept, this is probably not a suitable module to add other code. +This module contains services for article about reactive systems in Java. Please note that these services comprise parts of a full stack application to demonstrate the capabilities of a reactive system. Unless there is an article which extends on this concept, this is probably not a suitable module to add other code. ### Relevant Articles diff --git a/resteasy/pom.xml b/resteasy/pom.xml index d35fc852ba..a8c1f2815c 100644 --- a/resteasy/pom.xml +++ b/resteasy/pom.xml @@ -20,12 +20,6 @@ org.jboss.resteasy resteasy-servlet-initializer ${resteasy.version} - - - commons-logging - commons-logging - - org.jboss.resteasy @@ -40,14 +34,15 @@ org.jboss.resteasy - resteasy-jackson-provider + resteasy-jackson2-provider ${resteasy.version} - commons-io - commons-io - ${commons-io.version} + javax.servlet + javax.servlet-api + 4.0.1 + @@ -134,7 +129,7 @@ - 3.0.19.Final + 4.7.2.Final 1.6.1 diff --git a/resteasy/src/test/java/com/baeldung/server/RestEasyClientLiveTest.java b/resteasy/src/test/java/com/baeldung/server/RestEasyClientLiveTest.java index 7e709edb96..ba2878cc21 100644 --- a/resteasy/src/test/java/com/baeldung/server/RestEasyClientLiveTest.java +++ b/resteasy/src/test/java/com/baeldung/server/RestEasyClientLiveTest.java @@ -7,6 +7,7 @@ import java.util.List; import java.util.Locale; import javax.naming.NamingException; +import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; @@ -14,21 +15,21 @@ import org.apache.commons.io.IOUtils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.codehaus.jackson.map.DeserializationConfig; -import org.codehaus.jackson.map.ObjectMapper; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; -import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine; +import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine; import org.junit.Before; import org.junit.Test; import com.baeldung.client.ServicesInterface; import com.baeldung.model.Movie; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; public class RestEasyClientLiveTest { - public static final UriBuilder FULL_PATH = UriBuilder.fromPath("http://127.0.0.1:8082/RestEasyTutorial/rest"); + public static final UriBuilder FULL_PATH = UriBuilder.fromPath("http://127.0.0.1:8082/resteasy/rest"); Movie transformerMovie = null; Movie batmanMovie = null; ObjectMapper jsonMapper = null; @@ -36,8 +37,8 @@ public class RestEasyClientLiveTest { @Before public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { - jsonMapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + jsonMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + jsonMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); final SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); jsonMapper.setDateFormat(sdf); @@ -60,8 +61,8 @@ public class RestEasyClientLiveTest { @Test public void testListAllMovies() { - - final ResteasyClient client = new ResteasyClientBuilder().build(); + + final ResteasyClient client = (ResteasyClient)ClientBuilder.newClient(); final ResteasyWebTarget target = client.target(FULL_PATH); final ServicesInterface proxy = target.proxy(ServicesInterface.class); @@ -79,7 +80,7 @@ public class RestEasyClientLiveTest { final String transformerImdbId = "tt0418279"; - final ResteasyClient client = new ResteasyClientBuilder().build(); + final ResteasyClient client = (ResteasyClient) ClientBuilder.newClient(); final ResteasyWebTarget target = client.target(FULL_PATH); final ServicesInterface proxy = target.proxy(ServicesInterface.class); @@ -93,7 +94,7 @@ public class RestEasyClientLiveTest { @Test public void testAddMovie() { - final ResteasyClient client = new ResteasyClientBuilder().build(); + final ResteasyClient client = (ResteasyClient) ClientBuilder.newClient(); final ResteasyWebTarget target = client.target(FULL_PATH); final ServicesInterface proxy = target.proxy(ServicesInterface.class); @@ -114,8 +115,8 @@ public class RestEasyClientLiveTest { final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); final CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build(); - final ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient); - final ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); + final ApacheHttpClient43Engine engine = new ApacheHttpClient43Engine(httpClient); + final ResteasyClient client = ((ResteasyClientBuilder) ClientBuilder.newBuilder()).httpEngine(engine).build(); final ResteasyWebTarget target = client.target(FULL_PATH); final ServicesInterface proxy = target.proxy(ServicesInterface.class); @@ -138,7 +139,7 @@ public class RestEasyClientLiveTest { @Test public void testDeleteMovie() { - final ResteasyClient client = new ResteasyClientBuilder().build(); + final ResteasyClient client = (ResteasyClient) ClientBuilder.newClient(); final ResteasyWebTarget target = client.target(FULL_PATH); final ServicesInterface proxy = target.proxy(ServicesInterface.class); @@ -158,7 +159,7 @@ public class RestEasyClientLiveTest { @Test public void testUpdateMovie() { - final ResteasyClient client = new ResteasyClientBuilder().build(); + final ResteasyClient client = (ResteasyClient) ClientBuilder.newClient(); final ResteasyWebTarget target = client.target(FULL_PATH); final ServicesInterface proxy = target.proxy(ServicesInterface.class); diff --git a/spring-4/README.md b/spring-4/README.md index 46d9b71e5c..add82c7e00 100644 --- a/spring-4/README.md +++ b/spring-4/README.md @@ -7,3 +7,4 @@ This module contains articles about Spring 4 - [Configuring a Hikari Connection Pool with Spring Boot](https://www.baeldung.com/spring-boot-hikari) - [Spring JSON-P with Jackson](https://www.baeldung.com/spring-jackson-jsonp) - [What’s New in Spring 4.3?](https://www.baeldung.com/whats-new-in-spring-4-3) +- [Spring Boot Actuator](https://www.baeldung.com/spring-boot-actuators) diff --git a/spring-4/pom.xml b/spring-4/pom.xml index 5887bd43e2..681747c1f6 100644 --- a/spring-4/pom.xml +++ b/spring-4/pom.xml @@ -31,6 +31,10 @@ + + org.springframework.boot + spring-boot-starter-actuator + com.h2database h2 diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/actuator/CustomEndpoint.java b/spring-4/src/main/java/com/baeldung/actuator/CustomEndpoint.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/actuator/CustomEndpoint.java rename to spring-4/src/main/java/com/baeldung/actuator/CustomEndpoint.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/actuator/HealthCheck.java b/spring-4/src/main/java/com/baeldung/actuator/HealthCheck.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/actuator/HealthCheck.java rename to spring-4/src/main/java/com/baeldung/actuator/HealthCheck.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/actuator/LoginServiceImpl.java b/spring-4/src/main/java/com/baeldung/actuator/LoginServiceImpl.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/actuator/LoginServiceImpl.java rename to spring-4/src/main/java/com/baeldung/actuator/LoginServiceImpl.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/actuator/SpringBoot.java b/spring-4/src/main/java/com/baeldung/actuator/SpringBoot.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/actuator/SpringBoot.java rename to spring-4/src/main/java/com/baeldung/actuator/SpringBoot.java diff --git a/spring-4/src/main/resources/application.properties b/spring-4/src/main/resources/application.properties index e67700b7be..ca6dbb5580 100644 --- a/spring-4/src/main/resources/application.properties +++ b/spring-4/src/main/resources/application.properties @@ -3,3 +3,24 @@ feature.new.foo=Y last.active.after=2018-03-14T00:00:00Z first.active.after=2999-03-15T00:00:00Z logging.level.org.flips=info + +#actuator properties +### server port +server.port=8080 +#port used to expose actuator +management.port=8081 +#CIDR allowed to hit actuator +management.address=127.0.0.1 +# Actuator Configuration +# customize /beans endpoint +endpoints.beans.id=springbeans +endpoints.beans.sensitive=false +endpoints.beans.enabled=true +# for the Spring Boot version 1.5.0 and above, we have to disable security to expose the health endpoint fully for unauthorized access. +# see: https://docs.spring.io/spring-boot/docs/1.5.x/reference/html/production-ready-monitoring.html +management.security.enabled=false +endpoints.health.sensitive=false +# customize /info endpoint +info.app.name=Spring Sample Application +info.app.description=This is my first spring boot application +info.app.version=1.0.0 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/CustomEndpointIntegrationTest.java b/spring-4/src/test/java/com/baeldung/actuator/CustomEndpointIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/CustomEndpointIntegrationTest.java rename to spring-4/src/test/java/com/baeldung/actuator/CustomEndpointIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/HealthCheckIntegrationTest.java b/spring-4/src/test/java/com/baeldung/actuator/HealthCheckIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/HealthCheckIntegrationTest.java rename to spring-4/src/test/java/com/baeldung/actuator/HealthCheckIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/HealthCheckUnitTest.java b/spring-4/src/test/java/com/baeldung/actuator/HealthCheckUnitTest.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/HealthCheckUnitTest.java rename to spring-4/src/test/java/com/baeldung/actuator/HealthCheckUnitTest.java diff --git a/spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/LoginServiceIntegrationTest.java b/spring-4/src/test/java/com/baeldung/actuator/LoginServiceIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/LoginServiceIntegrationTest.java rename to spring-4/src/test/java/com/baeldung/actuator/LoginServiceIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/LoginServiceUnitTest.java b/spring-4/src/test/java/com/baeldung/actuator/LoginServiceUnitTest.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/LoginServiceUnitTest.java rename to spring-4/src/test/java/com/baeldung/actuator/LoginServiceUnitTest.java diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 939add1147..63f11a4a76 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -6,8 +6,8 @@ com.baeldung.spring-boot-modules spring-boot-modules 1.0.0-SNAPSHOT - pom spring-boot-modules + pom com.baeldung @@ -16,9 +16,7 @@ ../parent-boot-2 - - spring-boot-1 - spring-boot-2 + spring-boot-admin spring-boot-angular spring-boot-annotations @@ -46,7 +44,7 @@ spring-boot-groovy spring-boot-jasypt - + spring-boot-keycloak spring-boot-libraries spring-boot-libraries-2 spring-boot-libraries-comparison @@ -100,4 +98,4 @@ - + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-1/.mvn/wrapper/maven-wrapper.properties b/spring-boot-modules/spring-boot-1/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index 9dda3b659b..0000000000 --- a/spring-boot-modules/spring-boot-1/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1 +0,0 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip diff --git a/spring-boot-modules/spring-boot-1/README.md b/spring-boot-modules/spring-boot-1/README.md deleted file mode 100644 index 8e5214c69a..0000000000 --- a/spring-boot-modules/spring-boot-1/README.md +++ /dev/null @@ -1,11 +0,0 @@ -## Spring Boot 1.x Actuator - -This module contains articles about Spring Boot Actuator in Spring Boot version 1.x. - -## Relevant articles: -- [Spring Boot Actuator](https://www.baeldung.com/spring-boot-actuators) -- [A Quick Intro to the SpringBootServletInitializer](https://www.baeldung.com/spring-boot-servlet-initializer) -- [Spring Shutdown Callbacks](https://www.baeldung.com/spring-shutdown-callbacks) -- [Dynamic DTO Validation Config Retrieved from the Database](https://www.baeldung.com/spring-dynamic-dto-validation) - - diff --git a/spring-boot-modules/spring-boot-1/mvnw b/spring-boot-modules/spring-boot-1/mvnw deleted file mode 100755 index b74391fdf4..0000000000 --- a/spring-boot-modules/spring-boot-1/mvnw +++ /dev/null @@ -1,234 +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 -# -# http://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. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 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 Migwn, 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 - ))" - # TODO classpath? -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 - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -echo $MAVEN_PROJECTBASEDIR -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 - -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 "$@" diff --git a/spring-boot-modules/spring-boot-1/mvnw.cmd b/spring-boot-modules/spring-boot-1/mvnw.cmd deleted file mode 100644 index 019bd74d76..0000000000 --- a/spring-boot-modules/spring-boot-1/mvnw.cmd +++ /dev/null @@ -1,143 +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 http://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 Maven2 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 key stroke 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 enable echoing my 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 - -%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% diff --git a/spring-boot-modules/spring-boot-1/pom.xml b/spring-boot-modules/spring-boot-1/pom.xml deleted file mode 100644 index 594e6459a4..0000000000 --- a/spring-boot-modules/spring-boot-1/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - 4.0.0 - spring-boot-1 - jar - Module for Spring Boot version 1.x - - - - com.baeldung - parent-boot-1 - 0.0.1-SNAPSHOT - ../../parent-boot-1 - - - - - org.springframework.boot - spring-boot-starter - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.apache.logging.log4j - log4j-core - ${log4j2.version} - - - com.h2database - h2 - test - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - - - - - 2.17.1 - - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-1/src/main/resources/application.properties b/spring-boot-modules/spring-boot-1/src/main/resources/application.properties deleted file mode 100644 index ac095e1cab..0000000000 --- a/spring-boot-modules/spring-boot-1/src/main/resources/application.properties +++ /dev/null @@ -1,19 +0,0 @@ -### server port -server.port=8080 -#port used to expose actuator -management.port=8081 -#CIDR allowed to hit actuator -management.address=127.0.0.1 -# Actuator Configuration -# customize /beans endpoint -endpoints.beans.id=springbeans -endpoints.beans.sensitive=false -endpoints.beans.enabled=true -# for the Spring Boot version 1.5.0 and above, we have to disable security to expose the health endpoint fully for unauthorized access. -# see: https://docs.spring.io/spring-boot/docs/1.5.x/reference/html/production-ready-monitoring.html -management.security.enabled=false -endpoints.health.sensitive=false -# customize /info endpoint -info.app.name=Spring Sample Application -info.app.description=This is my first spring boot application -info.app.version=1.0.0 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-2/.mvn/wrapper/MavenWrapperDownloader.java b/spring-boot-modules/spring-boot-2/.mvn/wrapper/MavenWrapperDownloader.java deleted file mode 100644 index b901097f2d..0000000000 --- a/spring-boot-modules/spring-boot-2/.mvn/wrapper/MavenWrapperDownloader.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2007-present the original author or authors. - * - * Licensed 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 - * - * http://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. - */ -import java.net.*; -import java.io.*; -import java.nio.channels.*; -import java.util.Properties; - -public class MavenWrapperDownloader { - - private static final String WRAPPER_VERSION = "0.5.6"; - /** - * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. - */ - private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" - + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; - - /** - * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to - * use instead of the default one. - */ - private static final String MAVEN_WRAPPER_PROPERTIES_PATH = - ".mvn/wrapper/maven-wrapper.properties"; - - /** - * Path where the maven-wrapper.jar will be saved to. - */ - private static final String MAVEN_WRAPPER_JAR_PATH = - ".mvn/wrapper/maven-wrapper.jar"; - - /** - * Name of the property which should be used to override the default download url for the wrapper. - */ - private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; - - public static void main(String args[]) { - System.out.println("- Downloader started"); - File baseDirectory = new File(args[0]); - System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); - - // If the maven-wrapper.properties exists, read it and check if it contains a custom - // wrapperUrl parameter. - File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); - String url = DEFAULT_DOWNLOAD_URL; - if(mavenWrapperPropertyFile.exists()) { - FileInputStream mavenWrapperPropertyFileInputStream = null; - try { - mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); - Properties mavenWrapperProperties = new Properties(); - mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); - url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); - } catch (IOException e) { - System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); - } finally { - try { - if(mavenWrapperPropertyFileInputStream != null) { - mavenWrapperPropertyFileInputStream.close(); - } - } catch (IOException e) { - // Ignore ... - } - } - } - System.out.println("- Downloading from: " + url); - - File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); - if(!outputFile.getParentFile().exists()) { - if(!outputFile.getParentFile().mkdirs()) { - System.out.println( - "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); - } - } - System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); - try { - downloadFileFromURL(url, outputFile); - System.out.println("Done"); - System.exit(0); - } catch (Throwable e) { - System.out.println("- Error downloading"); - e.printStackTrace(); - System.exit(1); - } - } - - private static void downloadFileFromURL(String urlString, File destination) throws Exception { - if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { - String username = System.getenv("MVNW_USERNAME"); - char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); - Authenticator.setDefault(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } - }); - } - URL website = new URL(urlString); - ReadableByteChannel rbc; - rbc = Channels.newChannel(website.openStream()); - FileOutputStream fos = new FileOutputStream(destination); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - fos.close(); - rbc.close(); - } - -} diff --git a/spring-boot-modules/spring-boot-2/.mvn/wrapper/maven-wrapper.properties b/spring-boot-modules/spring-boot-2/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index 642d572ce9..0000000000 --- a/spring-boot-modules/spring-boot-2/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,2 +0,0 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/spring-boot-modules/spring-boot-2/README.md b/spring-boot-modules/spring-boot-2/README.md deleted file mode 100644 index 7ea97f80c5..0000000000 --- a/spring-boot-modules/spring-boot-2/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Speed up Spring Boot Startup Time](https://www.baeldung.com/spring-boot-startup-speed) diff --git a/spring-boot-modules/spring-boot-2/mvnw b/spring-boot-modules/spring-boot-2/mvnw deleted file mode 100644 index 41c0f0c23d..0000000000 --- a/spring-boot-modules/spring-boot-2/mvnw +++ /dev/null @@ -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 -# -# http://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 "$@" diff --git a/spring-boot-modules/spring-boot-2/mvnw.cmd b/spring-boot-modules/spring-boot-2/mvnw.cmd deleted file mode 100644 index 86115719e5..0000000000 --- a/spring-boot-modules/spring-boot-2/mvnw.cmd +++ /dev/null @@ -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 http://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% diff --git a/spring-boot-modules/spring-boot-2/pom.xml b/spring-boot-modules/spring-boot-2/pom.xml deleted file mode 100644 index 0da07eaf00..0000000000 --- a/spring-boot-modules/spring-boot-2/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - 4.0.0 - spring-boot-2 - jar - Module for Spring Boot version 2.x - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.boot - spring-boot-starter-security - - - org.apache.logging.log4j - log4j-core - ${log4j2.version} - - - org.springframework - spring-context-indexer - ${spring-core.version} - true - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - springStartupApp - com.baeldung.springStart.SpringStartApplication - - - - - repackage - - - - - - - - - 2.17.1 - 5.3.15 - 11 - 11 - - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-2/src/main/resources/application.properties deleted file mode 100644 index 4a5f46a7b1..0000000000 --- a/spring-boot-modules/spring-boot-2/src/main/resources/application.properties +++ /dev/null @@ -1,3 +0,0 @@ -spring.main.lazy-initialization=true -logging.level.org.springframework.boot.autoconfigure=DEBUG -spring.jmx.enabled=false \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-artifacts/pom.xml b/spring-boot-modules/spring-boot-artifacts/pom.xml index 0292dc95cf..7709c6a316 100644 --- a/spring-boot-modules/spring-boot-artifacts/pom.xml +++ b/spring-boot-modules/spring-boot-artifacts/pom.xml @@ -101,7 +101,7 @@ maven-failsafe-plugin 2.18 - integration-tests @@ -110,7 +110,7 @@ verify - **/ExternalPropertyFileLoaderIntegrationTest.java @@ -195,4 +195,4 @@ 4.5.8 - + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization-2/README.md b/spring-boot-modules/spring-boot-basic-customization-2/README.md index bfd24a0475..0f4167d25b 100644 --- a/spring-boot-modules/spring-boot-basic-customization-2/README.md +++ b/spring-boot-modules/spring-boot-basic-customization-2/README.md @@ -9,4 +9,5 @@ This module contains articles about Spring Boot customization 2 - [What Is OncePerRequestFilter?](https://www.baeldung.com/spring-onceperrequestfilter) - [Spring Boot Exit Codes](https://www.baeldung.com/spring-boot-exit-codes) - [Guide to Spring Type Conversions](https://www.baeldung.com/spring-type-conversions) - - [Container Configuration in Spring Boot 2](https://www.baeldung.com/embeddedservletcontainercustomizer-configurableembeddedservletcontainer-spring-boot) \ No newline at end of file + - [Container Configuration in Spring Boot 2](https://www.baeldung.com/embeddedservletcontainercustomizer-configurableembeddedservletcontainer-spring-boot) + - [Speed up Spring Boot Startup Time](https://www.baeldung.com/spring-boot-startup-speed) \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization-2/pom.xml b/spring-boot-modules/spring-boot-basic-customization-2/pom.xml index b537f43c23..439051c7e6 100644 --- a/spring-boot-modules/spring-boot-basic-customization-2/pom.xml +++ b/spring-boot-modules/spring-boot-basic-customization-2/pom.xml @@ -23,7 +23,11 @@ org.springframework.boot spring-boot-starter-data-jpa - + + org.springframework.boot + spring-boot-starter-actuator + + com.h2database h2 @@ -31,11 +35,31 @@ org.springframework.boot spring-boot-starter-test - + com.google.guava guava ${guava.version} + + + + org.springframework.boot + spring-boot-maven-plugin + + springStartupApp + com.baeldung.springStart.SpringStartApplication + + + + + repackage + + + + + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-2/src/main/java/com/baeldung/springStart/SpringStartApplication.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/springStart/SpringStartApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-2/src/main/java/com/baeldung/springStart/SpringStartApplication.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/springStart/SpringStartApplication.java diff --git a/spring-boot-modules/spring-boot-basic-customization-2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-basic-customization-2/src/main/resources/application.properties index ab9de92c82..370ea40d73 100644 --- a/spring-boot-modules/spring-boot-basic-customization-2/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/resources/application.properties @@ -1 +1,6 @@ -sample=string loaded from properties! \ No newline at end of file +sample=string loaded from properties! + +#startup time properties +spring.main.lazy-initialization=true +logging.level.org.springframework.boot.autoconfigure=DEBUG +spring.jmx.enabled=false \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java index 50d5f4ea71..9ef1fcbc8e 100644 --- a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java @@ -27,8 +27,8 @@ public class UserController { LOG.info("Fetching all the users"); return Arrays.asList( new User(UUID.randomUUID().toString(), "User1", "user1@test.com"), - new User(UUID.randomUUID().toString(), "User1", "user1@test.com"), - new User(UUID.randomUUID().toString(), "User1", "user1@test.com")); + new User(UUID.randomUUID().toString(), "User2", "user2@test.com"), + new User(UUID.randomUUID().toString(), "User3", "user3@test.com")); } } diff --git a/spring-boot-modules/spring-boot-data-2/README.md b/spring-boot-modules/spring-boot-data-2/README.md index fd9d034f8a..9ff2b2caf8 100644 --- a/spring-boot-modules/spring-boot-data-2/README.md +++ b/spring-boot-modules/spring-boot-data-2/README.md @@ -5,4 +5,6 @@ - [“HttpMessageNotWritableException: No converter found for return value of type”](https://www.baeldung.com/spring-no-converter-found) - [Creating a Read-Only Repository with Spring Data](https://www.baeldung.com/spring-data-read-only-repository) - [Using JaVers for Data Model Auditing in Spring Data](https://www.baeldung.com/spring-data-javers-audit) -- [BootstrapMode for JPA Repositories](https://github.com/eugenp/tutorials/tree/master/spring-boot-modules/spring-boot-data-2) +- [BootstrapMode for JPA Repositories](https://www.baeldung.com/jpa-bootstrap-mode) +- [Dynamic DTO Validation Config Retrieved from the Database](https://www.baeldung.com/spring-dynamic-dto-validation) + diff --git a/spring-boot-modules/spring-boot-data-2/pom.xml b/spring-boot-modules/spring-boot-data-2/pom.xml index ea5de6d4b5..cd03d1b9b1 100644 --- a/spring-boot-modules/spring-boot-data-2/pom.xml +++ b/spring-boot-modules/spring-boot-data-2/pom.xml @@ -16,6 +16,14 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-validation + org.springframework.boot spring-boot-starter-data-jpa @@ -31,7 +39,7 @@ runtime - + 6.5.3 diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/ContactInfo.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/ContactInfo.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/ContactInfo.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/ContactInfo.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/config/CustomerController.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/config/CustomerController.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/config/CustomerController.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/config/CustomerController.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/dao/ContactInfoExpressionRepository.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/dao/ContactInfoExpressionRepository.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/dao/ContactInfoExpressionRepository.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/dao/ContactInfoExpressionRepository.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/model/ContactInfoExpression.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/model/ContactInfoExpression.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/model/ContactInfoExpression.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/model/ContactInfoExpression.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/model/Customer.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/model/Customer.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/model/Customer.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/model/Customer.java diff --git a/spring-boot-modules/spring-boot-data-2/src/main/resources/data-expressions.sql b/spring-boot-modules/spring-boot-data-2/src/main/resources/data-expressions.sql new file mode 100644 index 0000000000..5a16ceceb9 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-2/src/main/resources/data-expressions.sql @@ -0,0 +1,6 @@ +insert into contact_info_expression values ('email', + '[a-z0-9!#$%&*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?') +insert into contact_info_expression values ('phone', + '^([0-9]( |-)?)?(\(?[0-9]{3}\)?|[0-9]{3})( |-)?([0-9]{3}( |-)?[0-9]{4}|[a-zA-Z0-9]{7})$') +insert into contact_info_expression values ('website', + '^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$') \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-data-2/src/main/resources/schema-expressions.sql b/spring-boot-modules/spring-boot-data-2/src/main/resources/schema-expressions.sql new file mode 100644 index 0000000000..532faefde1 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-2/src/main/resources/schema-expressions.sql @@ -0,0 +1,5 @@ +CREATE TABLE contact_info_expression( + expression_type varchar(50) not null, + pattern varchar(500) not null, + PRIMARY KEY ( expression_type ) +); \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-1/src/main/resources/templates/customer.html b/spring-boot-modules/spring-boot-data-2/src/main/resources/templates/customer.html similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/resources/templates/customer.html rename to spring-boot-modules/spring-boot-data-2/src/main/resources/templates/customer.html diff --git a/spring-boot-modules/spring-boot-1/src/test/resources/application.properties b/spring-boot-modules/spring-boot-data-2/src/test/resources/application.properties similarity index 100% rename from spring-boot-modules/spring-boot-1/src/test/resources/application.properties rename to spring-boot-modules/spring-boot-data-2/src/test/resources/application.properties diff --git a/spring-boot-modules/spring-boot-deployment/README.md b/spring-boot-modules/spring-boot-deployment/README.md index 85f288d33b..125de43a88 100644 --- a/spring-boot-modules/spring-boot-deployment/README.md +++ b/spring-boot-modules/spring-boot-deployment/README.md @@ -7,3 +7,4 @@ This module contains articles about deployment of a Spring Boot Application - [Spring Boot Console Application](https://www.baeldung.com/spring-boot-console-app) - [Comparing Embedded Servlet Containers in Spring Boot](https://www.baeldung.com/spring-boot-servlet-containers) - [Graceful Shutdown of a Spring Boot Application](https://www.baeldung.com/spring-boot-graceful-shutdown) + - [Spring Shutdown Callbacks](https://www.baeldung.com/spring-shutdown-callbacks) diff --git a/spring-boot-modules/spring-boot-deployment/pom.xml b/spring-boot-modules/spring-boot-deployment/pom.xml index 7a9c2096f1..47b1a0f0d5 100644 --- a/spring-boot-modules/spring-boot-deployment/pom.xml +++ b/spring-boot-modules/spring-boot-deployment/pom.xml @@ -41,6 +41,11 @@ org.springframework.boot spring-boot-starter-actuator + + org.springframework.boot + spring-boot-starter-tomcat + provided + com.h2database h2 diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java diff --git a/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java index 8873f1214c..5d3cbe35cb 100644 --- a/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java +++ b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java @@ -13,6 +13,10 @@ import org.springframework.context.annotation.Configuration; // @ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = Rose.class)) // @ComponentScan(basePackages = "com.baeldung.componentscan.springapp") // @ComponentScan(basePackages = "com.baeldung.componentscan.springapp.animals") +// @ComponentScan(basePackages = {"com.baeldung.componentscan.springapp.animals","com.baeldung.componentscan.springapp.flowers"}) +// @ComponentScan(basePackages = "com.baeldung.componentscan.springapp.animals;com.baeldung.componentscan.springapp.flowers") +// @ComponentScan(basePackages = "com.baeldung.componentscan.springapp.animals,com.baeldung.componentscan.springapp.flowers") +// @ComponentScan(basePackages = "com.baeldung.componentscan.springapp.animals com.baeldung.componentscan.springapp.flowers") // @ComponentScan (excludeFilters = @ComponentScan.Filter(type=FilterType.REGEX,pattern="com\\.baeldung\\.componentscan\\.springapp\\.flowers\\..*")) public class SpringComponentScanApp { diff --git a/spring-boot-modules/spring-boot-keycloak/pom.xml b/spring-boot-modules/spring-boot-keycloak/pom.xml index 09ddcaa724..9e39176765 100644 --- a/spring-boot-modules/spring-boot-keycloak/pom.xml +++ b/spring-boot-modules/spring-boot-keycloak/pom.xml @@ -89,7 +89,7 @@ org.codehaus.mojo jaxb2-maven-plugin - 2.5.0 + 2.3.1 xjc diff --git a/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloaksoap/KeycloakSoapIntegrationTest.java b/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloaksoap/KeycloakSoapLiveTest.java similarity index 96% rename from spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloaksoap/KeycloakSoapIntegrationTest.java rename to spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloaksoap/KeycloakSoapLiveTest.java index e0de897044..0327915399 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloaksoap/KeycloakSoapIntegrationTest.java +++ b/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloaksoap/KeycloakSoapLiveTest.java @@ -26,29 +26,35 @@ import java.util.Objects; import static org.assertj.core.api.Assertions.assertThat; /** - * The class contains Live/Integration tests. + * The class contains Live tests. * These tests expect that the Keycloak server is up and running on port 8080. - * The tests may fail without a Keycloak server. */ -@DisplayName("Keycloak SOAP Webservice Unit Tests") +@DisplayName("Keycloak SOAP Webservice Live Tests") @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") @AutoConfigureMockMvc -class KeycloakSoapIntegrationTest { +class KeycloakSoapLiveTest { + + private static final Logger logger = LoggerFactory.getLogger(KeycloakSoapLiveTest.class); - private static final Logger logger = LoggerFactory.getLogger(KeycloakSoapIntegrationTest.class); @LocalServerPort private int port; + @Autowired private TestRestTemplate restTemplate; + @Autowired private ObjectMapper objectMapper; + @Value("${grant.type}") private String grantType; + @Value("${client.id}") private String clientId; + @Value("${client.secret}") private String clientSecret; + @Value("${url}") private String keycloakUrl; diff --git a/spring-boot-modules/spring-boot-libraries/src/test/resources/GraphQL collection.postman_collection.json b/spring-boot-modules/spring-boot-libraries/src/test/resources/GraphQL collection.postman_collection.json new file mode 100644 index 0000000000..8245152bdd --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/resources/GraphQL collection.postman_collection.json @@ -0,0 +1,169 @@ +{ + "info": { + "_postman_id": "910d9690-f629-4491-bbbd-adb30982a386", + "name": "GraphQL collection", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "mutations", + "item": [ + { + "name": "writePost", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "graphql", + "graphql": { + "query": "mutation writePost ($title: String!, $text: String!, $category: String) {\n writePost (title: $title, text: $text, category: $category) {\n id\n title\n text\n category\n }\n}", + "variables": "{\n \"title\": \"\",\n \"text\": \"\",\n \"category\": \"\"\n}" + }, + "options": { + "graphql": {} + } + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + } + ], + "protocolProfileBehavior": {} + }, + { + "name": "queries", + "item": [ + { + "name": "get recent posts", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "graphql", + "graphql": { + "query": "{\r\n recentPosts(count: 10, offset: 0) {\r\n id\r\n title\r\n category\r\n text\r\n author {\r\n id\r\n name\r\n thumbnail\r\n }\r\n }\r\n}", + "variables": "" + } + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + }, + { + "name": "recentPosts - variables", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "graphql", + "graphql": { + "query": "query recentPosts ($count: Int, $offset: Int) {\n recentPosts (count: $count, offset: $offset) {\n id\n title\n text\n category\n }\n}", + "variables": "{\n \"count\": 1,\n \"offset\": 0\n}" + }, + "options": { + "graphql": {} + } + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + }, + { + "name": "get recent posts - raw", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/graphql", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "query {\r\n recentPosts(count: 10, offset: 0) {\r\n id\r\n title\r\n category\r\n author {\r\n id\r\n name\r\n thumbnail\r\n }\r\n }\r\n}" + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + } + ], + "protocolProfileBehavior": {} + } + ], + "event": [ + { + "listen": "prerequest", + "script": { + "id": "b54f267b-c450-4f2d-8105-2f23bab4c922", + "type": "text/javascript", + "exec": [ + "" + ] + } + }, + { + "listen": "test", + "script": { + "id": "00b575be-03d4-4b29-b137-733ead139638", + "type": "text/javascript", + "exec": [ + "" + ] + } + } + ], + "variable": [ + { + "id": "20a274e5-6d51-40d6-81cb-af9eb115b21b", + "key": "url", + "value": "", + "type": "string" + } + ], + "protocolProfileBehavior": {} +} diff --git a/spring-boot-modules/spring-boot-mvc-2/README.md b/spring-boot-modules/spring-boot-mvc-2/README.md index 0d0e05daf0..30e6d71a30 100644 --- a/spring-boot-modules/spring-boot-mvc-2/README.md +++ b/spring-boot-modules/spring-boot-mvc-2/README.md @@ -11,4 +11,5 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections) - [Spring Boot Consuming and Producing JSON](https://www.baeldung.com/spring-boot-json) - [Serve Static Resources with Spring](https://www.baeldung.com/spring-mvc-static-resources) +- [Add Header to Every Request in Postman](https://www.baeldung.com/postman-add-headers-pre-request) - More articles: [[prev -->]](/spring-boot-modules/spring-boot-mvc) diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/Student_API_Collection.postman_collection.json b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/Student_API_Collection.postman_collection.json new file mode 100644 index 0000000000..1cce92b7dc --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/Student_API_Collection.postman_collection.json @@ -0,0 +1,101 @@ +{ + "info": { + "_postman_id": "2dd2d46e-cb0a-4fcd-a1a3-461930df0c38", + "name": "Student API Collection", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "http://localhost:8080/students/", + "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "", + "" + ], + "type": "text/javascript" + } + } + ], + "protocolProfileBehavior": { + "disabledSystemHeaders": {} + }, + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "image/*", + "type": "text", + "disabled": true + }, + { + "key": "Accept", + "value": "application/json", + "type": "text", + "disabled": true + } + ], + "url": { + "raw": "http://localhost:8080/students/", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "students", + "" + ] + } + }, + "response": [] + }, + { + "name": "http://localhost:8080/students/2", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "http://localhost:8080/students/3", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "students", + "3" + ] + } + }, + "response": [] + } + ], + "event": [ + { + "listen": "prerequest", + "script": { + "type": "text/javascript", + "exec": [ + "pm.request.headers.add({ ", + " key: \"Accept\",", + " value: \"application/json\" ", + "});", + "" + ] + } + }, + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "" + ] + } + } + ] +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-4/README.md b/spring-boot-modules/spring-boot-mvc-4/README.md index a05aa3c7b9..a7a341deee 100644 --- a/spring-boot-modules/spring-boot-mvc-4/README.md +++ b/spring-boot-modules/spring-boot-mvc-4/README.md @@ -7,5 +7,6 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [How to Register a Servlet in Java](https://www.baeldung.com/register-servlet) - [Guide to Spring WebUtils and ServletRequestUtils](https://www.baeldung.com/spring-webutils-servletrequestutils) - [Configure a Spring Boot Web Application](https://www.baeldung.com/spring-boot-application-configuration) +- [A Quick Intro to the SpringBootServletInitializer](https://www.baeldung.com/spring-boot-servlet-initializer) - [A Guide to Spring in Eclipse STS](https://www.baeldung.com/eclipse-sts-spring) -- More articles: [[<-- Prev]](/spring-boot-modules/spring-boot-mvc-3) +- [Hide a Request Field in Swagger API](https://www.baeldung.com/spring-swagger-hide-field) diff --git a/spring-boot-modules/spring-boot-mvc-4/pom.xml b/spring-boot-modules/spring-boot-mvc-4/pom.xml index 7d4d6e3d0c..b1c079b715 100644 --- a/spring-boot-modules/spring-boot-mvc-4/pom.xml +++ b/spring-boot-modules/spring-boot-mvc-4/pom.xml @@ -19,13 +19,27 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-thymeleaf + org.springframework.boot spring-boot-starter-validation org.springframework.boot - spring-boot-starter-thymeleaf + spring-boot-devtools + true + + + io.springfox + springfox-boot-starter + ${spring.fox.version} + + + com.fasterxml.jackson.core + jackson-databind org.springframework.boot @@ -42,4 +56,22 @@ + + + + org.springframework.boot + spring-boot-maven-plugin + + ${start-class} + JAR + + + + + + + 3.0.0 + com.baeldung.springboot.swagger.ArticleApplication + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java similarity index 93% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java index 0aa0f0ae0b..5b9ce1271e 100644 --- a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java +++ b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java @@ -5,7 +5,7 @@ import java.time.LocalDateTime; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springboot/swagger/ArticleApplication.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/ArticleApplication.java similarity index 91% rename from spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springboot/swagger/ArticleApplication.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/ArticleApplication.java index 568d31e8bc..8be380baa0 100644 --- a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springboot/swagger/ArticleApplication.java +++ b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/ArticleApplication.java @@ -4,6 +4,7 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; @@ -12,6 +13,7 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication @EnableSwagger2 +@EnableWebMvc public class ArticleApplication { public static void main(String[] args) { diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springboot/swagger/controller/ArticlesController.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/controller/ArticlesController.java similarity index 91% rename from spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springboot/swagger/controller/ArticlesController.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/controller/ArticlesController.java index 96812e367a..c4336a7cfe 100644 --- a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springboot/swagger/controller/ArticlesController.java +++ b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/controller/ArticlesController.java @@ -21,7 +21,7 @@ public class ArticlesController { } @PostMapping("") - public void addArticle(@RequestBody Article article) { + public void addArticle(@ModelAttribute Article article) { articleService.addArticle(article); } diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springboot/swagger/model/Article.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/model/Article.java similarity index 97% rename from spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springboot/swagger/model/Article.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/model/Article.java index 6512b4e1a7..f6318c04b3 100644 --- a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springboot/swagger/model/Article.java +++ b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/model/Article.java @@ -15,6 +15,7 @@ public class Article { //@ApiModelProperty(hidden = true) //@ApiParam(hidden = true) //@ApiModelProperty(readOnly = true) + @ApiParam(hidden = true) private int id; private String title; private int numOfWords; diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springboot/swagger/service/ArticleService.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/service/ArticleService.java similarity index 99% rename from spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springboot/swagger/service/ArticleService.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/service/ArticleService.java index 04f6e6c6e3..3fd0279988 100644 --- a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springboot/swagger/service/ArticleService.java +++ b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/service/ArticleService.java @@ -20,6 +20,6 @@ public class ArticleService { article.setId(articles.size() + 1); articles.add(article); } - + } diff --git a/spring-boot-modules/spring-boot-mvc-4/src/main/resources/static/index.html b/spring-boot-modules/spring-boot-mvc-4/src/main/resources/static/index.html new file mode 100644 index 0000000000..9f55d12685 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-4/src/main/resources/static/index.html @@ -0,0 +1 @@ +Welcome to Baeldung \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/servletinitializer/WarInitializerApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-4/src/test/java/com/baeldung/servletinitializer/WarInitializerApplicationIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/servletinitializer/WarInitializerApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot-mvc-4/src/test/java/com/baeldung/servletinitializer/WarInitializerApplicationIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-mvc/README.md b/spring-boot-modules/spring-boot-mvc/README.md index cdb2bd0fce..fdd7c70af2 100644 --- a/spring-boot-modules/spring-boot-mvc/README.md +++ b/spring-boot-modules/spring-boot-mvc/README.md @@ -7,7 +7,7 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [Custom Validation MessageSource in Spring Boot](https://www.baeldung.com/spring-custom-validation-message-source) - [Display RSS Feed with Spring MVC](https://www.baeldung.com/spring-mvc-rss-feed) - [A Controller, Service and DAO Example with Spring Boot and JSF](https://www.baeldung.com/jsf-spring-boot-controller-service-dao) -- [Setting Up Swagger 2 with a Spring REST API](https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) +- [Setting Up Swagger 2 with a Spring REST API Using Springfox](https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) - [Using Spring ResponseEntity to Manipulate the HTTP Response](https://www.baeldung.com/spring-response-entity) - [The @ServletComponentScan Annotation in Spring Boot](https://www.baeldung.com/spring-servletcomponentscan) - [Guide to Internationalization in Spring Boot](https://www.baeldung.com/spring-boot-internationalization) diff --git a/spring-boot-modules/spring-boot-properties-migrator-demo/pom.xml b/spring-boot-modules/spring-boot-properties-migrator-demo/pom.xml index d44a8ce6f1..95dc06b155 100644 --- a/spring-boot-modules/spring-boot-properties-migrator-demo/pom.xml +++ b/spring-boot-modules/spring-boot-properties-migrator-demo/pom.xml @@ -1,9 +1,8 @@ + 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"> 4.0.0 - spring-boot-properties-migrator-demo 1.0-SNAPSHOT @@ -13,18 +12,13 @@ 1.0.0-SNAPSHOT ../pom.xml - - - - - - - - - - 8 - 8 - + + + + + + + @@ -54,4 +48,9 @@ - + + 8 + 8 + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-springdoc/README.md b/spring-boot-modules/spring-boot-springdoc/README.md index 4ac4147da6..5daca79bd2 100644 --- a/spring-boot-modules/spring-boot-springdoc/README.md +++ b/spring-boot-modules/spring-boot-springdoc/README.md @@ -4,3 +4,4 @@ - [Spring REST Docs vs OpenAPI](https://www.baeldung.com/spring-rest-docs-vs-openapi) - [Hiding Endpoints From Swagger Documentation in Spring Boot](https://www.baeldung.com/spring-swagger-hiding-endpoints) - [Swagger @Api Description Is Deprecated](https://www.baeldung.com/java-swagger-api-description-deprecated) +- [Set List of Objects in Swagger API Response](https://www.baeldung.com/java-swagger-set-list-response) diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/README.md b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/README.md deleted file mode 100644 index a7ff3285ee..0000000000 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Set List of Objects in Swagger API Response](https://www.baeldung.com/java-swagger-set-list-response) diff --git a/spring-boot-modules/spring-boot-validation/pom.xml b/spring-boot-modules/spring-boot-validation/pom.xml index 639a62059d..1412a57e2a 100644 --- a/spring-boot-modules/spring-boot-validation/pom.xml +++ b/spring-boot-modules/spring-boot-validation/pom.xml @@ -22,7 +22,7 @@ org.hibernate.validator hibernate-validator - + org.springframework.boot spring-boot-starter-data-jpa diff --git a/spring-boot-rest-2/README.md b/spring-boot-rest-2/README.md deleted file mode 100644 index 985aa97a86..0000000000 --- a/spring-boot-rest-2/README.md +++ /dev/null @@ -1,5 +0,0 @@ -### Relevant Article: - -- [Get All Endpoints in Spring Boot](https://www.baeldung.com/spring-boot-get-all-endpoints) -- [HTTP PUT vs. POST in REST API](https://www.baeldung.com/rest-http-put-vs-post) -- [415 Unsupported MediaType in Spring Application](https://www.baeldung.com/spring-415-unsupported-mediatype) diff --git a/spring-boot-rest-2/pom.xml b/spring-boot-rest-2/pom.xml deleted file mode 100644 index b75e93577a..0000000000 --- a/spring-boot-rest-2/pom.xml +++ /dev/null @@ -1,57 +0,0 @@ - - - 4.0.0 - com.baeldung.web - spring-boot-rest-2 - spring-boot-rest-2 - war - Spring Boot Rest Module - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-actuator - - - io.springfox - springfox-boot-starter - ${springfox.version} - - - org.springframework.boot - spring-boot-starter-data-jpa - - - com.h2database - h2 - runtime - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - 3.0.0 - - - \ No newline at end of file diff --git a/spring-boot-rest-2/src/main/resources/application.properties b/spring-boot-rest-2/src/main/resources/application.properties deleted file mode 100644 index 5046c9660f..0000000000 --- a/spring-boot-rest-2/src/main/resources/application.properties +++ /dev/null @@ -1,2 +0,0 @@ - -management.endpoints.web.exposure.include=mappings diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 9205416cd5..f58e1aec5c 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -92,4 +92,4 @@ 3.1.3 - + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-security/auth-client/pom.xml b/spring-cloud/spring-cloud-security/auth-client/pom.xml index cdbb056a45..1ec56ce9ef 100644 --- a/spring-cloud/spring-cloud-security/auth-client/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-client/pom.xml @@ -9,7 +9,7 @@ Spring Cloud Security APP Client Module - com.baeldung + com.baeldung.spring.cloud spring-cloud-security 1.0.0-SNAPSHOT diff --git a/spring-cloud/spring-cloud-security/auth-resource/pom.xml b/spring-cloud/spring-cloud-security/auth-resource/pom.xml index c999030c07..9362a71931 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-resource/pom.xml @@ -9,7 +9,7 @@ Spring Cloud Security APP Resource Module - com.baeldung + com.baeldung.spring.cloud spring-cloud-security 1.0.0-SNAPSHOT diff --git a/spring-cloud/spring-cloud-security/auth-server/pom.xml b/spring-cloud/spring-cloud-security/auth-server/pom.xml index c0330aad43..234d9cde78 100644 --- a/spring-cloud/spring-cloud-security/auth-server/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-server/pom.xml @@ -8,7 +8,7 @@ Spring Cloud Security APP Server Module - com.baeldung + com.baeldung.spring.cloud spring-cloud-security 1.0.0-SNAPSHOT diff --git a/spring-data-rest/src/main/resources/logback.xml b/spring-data-rest/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-data-rest/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-di-3/README.md b/spring-di-3/README.md index 4246069616..3ddd720af5 100644 --- a/spring-di-3/README.md +++ b/spring-di-3/README.md @@ -6,4 +6,5 @@ This module contains articles about dependency injection with Spring - [@Lookup Annotation in Spring](https://www.baeldung.com/spring-lookup) - [Spring @Autowired Field Null – Common Causes and Solutions](https://www.baeldung.com/spring-autowired-field-null) +- [Finding All Beans with a Custom Annotation](https://www.baeldung.com/spring-injecting-all-annotated-beans) - More articles: [[<-- prev]](../spring-di-2) diff --git a/spring-reactive/pom.xml b/spring-reactive/pom.xml index 37df1a820d..396fa3ee4a 100644 --- a/spring-reactive/pom.xml +++ b/spring-reactive/pom.xml @@ -59,7 +59,6 @@ integration-lite-first - @@ -76,7 +75,6 @@ integration-lite-second - diff --git a/spring-reactive/src/main/java/com/baeldung/reactive/webclient/Foo.java b/spring-reactive/src/main/java/com/baeldung/reactive/webclient/Foo.java index a58d672686..246ba30667 100644 --- a/spring-reactive/src/main/java/com/baeldung/reactive/webclient/Foo.java +++ b/spring-reactive/src/main/java/com/baeldung/reactive/webclient/Foo.java @@ -1,24 +1,14 @@ package com.baeldung.reactive.webclient; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor public class Foo { private String name; - public Foo() { - super(); - } - - public Foo(String name) { - super(); - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - } diff --git a/spring-reactive/src/main/java/com/baeldung/reactive/webclient/WebClientApplication.java b/spring-reactive/src/main/java/com/baeldung/reactive/webclient/WebClientApplication.java index fd1cb8aff1..3a62e7b8a5 100644 --- a/spring-reactive/src/main/java/com/baeldung/reactive/webclient/WebClientApplication.java +++ b/spring-reactive/src/main/java/com/baeldung/reactive/webclient/WebClientApplication.java @@ -15,11 +15,10 @@ public class WebClientApplication { } @Bean - public SecurityWebFilterChain functionalValidationsSpringSecurityFilterChain(ServerHttpSecurity http) { - http.authorizeExchange() - .anyExchange() - .permitAll(); - http.csrf().disable(); + public SecurityWebFilterChain filterChain(ServerHttpSecurity http) { + http.csrf().disable() + .authorizeExchange() + .anyExchange().permitAll(); return http.build(); } } diff --git a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/Employee.java b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/Employee.java index d41a4f2791..dd88dcb668 100644 --- a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/Employee.java +++ b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/Employee.java @@ -11,7 +11,5 @@ public class Employee { private String id; private String name; - - // standard getters and setters - + } diff --git a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeRepository.java b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeRepository.java index 9aebc577b0..01d32ea57a 100644 --- a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeRepository.java +++ b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeRepository.java @@ -10,46 +10,32 @@ import java.util.Map; @Repository public class EmployeeRepository { - static Map employeeData; - - static Map employeeAccessData; + private static final Map EMPLOYEE_DATA; static { - employeeData = new HashMap<>(); - employeeData.put("1", new Employee("1", "Employee 1")); - employeeData.put("2", new Employee("2", "Employee 2")); - employeeData.put("3", new Employee("3", "Employee 3")); - employeeData.put("4", new Employee("4", "Employee 4")); - employeeData.put("5", new Employee("5", "Employee 5")); - employeeData.put("6", new Employee("6", "Employee 6")); - employeeData.put("7", new Employee("7", "Employee 7")); - employeeData.put("8", new Employee("8", "Employee 8")); - employeeData.put("9", new Employee("9", "Employee 9")); - employeeData.put("10", new Employee("10", "Employee 10")); - - employeeAccessData = new HashMap<>(); - employeeAccessData.put("1", "Employee 1 Access Key"); - employeeAccessData.put("2", "Employee 2 Access Key"); - employeeAccessData.put("3", "Employee 3 Access Key"); - employeeAccessData.put("4", "Employee 4 Access Key"); - employeeAccessData.put("5", "Employee 5 Access Key"); - employeeAccessData.put("6", "Employee 6 Access Key"); - employeeAccessData.put("7", "Employee 7 Access Key"); - employeeAccessData.put("8", "Employee 8 Access Key"); - employeeAccessData.put("9", "Employee 9 Access Key"); - employeeAccessData.put("10", "Employee 10 Access Key"); + EMPLOYEE_DATA = new HashMap<>(); + EMPLOYEE_DATA.put("1", new Employee("1", "Employee 1")); + EMPLOYEE_DATA.put("2", new Employee("2", "Employee 2")); + EMPLOYEE_DATA.put("3", new Employee("3", "Employee 3")); + EMPLOYEE_DATA.put("4", new Employee("4", "Employee 4")); + EMPLOYEE_DATA.put("5", new Employee("5", "Employee 5")); + EMPLOYEE_DATA.put("6", new Employee("6", "Employee 6")); + EMPLOYEE_DATA.put("7", new Employee("7", "Employee 7")); + EMPLOYEE_DATA.put("8", new Employee("8", "Employee 8")); + EMPLOYEE_DATA.put("9", new Employee("9", "Employee 9")); + EMPLOYEE_DATA.put("10", new Employee("10", "Employee 10")); } public Mono findEmployeeById(String id) { - return Mono.just(employeeData.get(id)); + return Mono.just(EMPLOYEE_DATA.get(id)); } public Flux findAllEmployees() { - return Flux.fromIterable(employeeData.values()); + return Flux.fromIterable(EMPLOYEE_DATA.values()); } public Mono updateEmployee(Employee employee) { - Employee existingEmployee = employeeData.get(employee.getId()); + Employee existingEmployee = EMPLOYEE_DATA.get(employee.getId()); if (existingEmployee != null) { existingEmployee.setName(employee.getName()); } diff --git a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeSpringApplication.java b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeSpringApplication.java index f1d21bdc77..0e3cc6bf99 100644 --- a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeSpringApplication.java +++ b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeSpringApplication.java @@ -1,12 +1,19 @@ package com.baeldung.reactive.webflux.annotation; +import com.baeldung.reactive.webflux.EmployeeRepository; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration; +import org.springframework.context.annotation.Bean; @SpringBootApplication(exclude = MongoReactiveAutoConfiguration.class) public class EmployeeSpringApplication { + @Bean + EmployeeRepository employeeRepository() { + return new EmployeeRepository(); + } + public static void main(String[] args) { SpringApplication.run(EmployeeSpringApplication.class, args); diff --git a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebClient.java b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebClient.java index 611a261a1b..5ae193dc7c 100644 --- a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebClient.java +++ b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebClient.java @@ -10,23 +10,23 @@ import reactor.core.publisher.Mono; public class EmployeeWebClient { private static final Logger LOGGER = LoggerFactory.getLogger(EmployeeWebClient.class); - + WebClient client = WebClient.create("http://localhost:8080"); - + public void consume() { Mono employeeMono = client.get() - .uri("/employees/{id}", "1") - .retrieve() - .bodyToMono(Employee.class); + .uri("/employees/{id}", "1") + .retrieve() + .bodyToMono(Employee.class); + + employeeMono.subscribe(employee -> LOGGER.info("Employee: {}", employee)); - employeeMono.subscribe(employee -> LOGGER.debug("Employee: {}", employee)); - Flux employeeFlux = client.get() - .uri("/employees") - .retrieve() - .bodyToFlux(Employee.class); - - employeeFlux.subscribe(employee -> LOGGER.debug("Employee: {}", employee)); + .uri("/employees") + .retrieve() + .bodyToFlux(Employee.class); + + employeeFlux.subscribe(employee -> LOGGER.info("Employee: {}", employee)); } -} \ No newline at end of file +} diff --git a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebSecurityConfig.java b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebSecurityConfig.java index 8dfa455ce3..fc98b70c0f 100644 --- a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebSecurityConfig.java +++ b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebSecurityConfig.java @@ -13,33 +13,31 @@ import org.springframework.security.web.server.SecurityWebFilterChain; @EnableWebFluxSecurity public class EmployeeWebSecurityConfig { - + @Bean public MapReactiveUserDetailsService userDetailsService() { UserDetails user = User - .withUsername("admin") - .password(passwordEncoder().encode("password")) - .roles("ADMIN") - .build(); + .withUsername("admin") + .password(passwordEncoder().encode("password")) + .roles("ADMIN") + .build(); return new MapReactiveUserDetailsService(user); } @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - http.csrf() - .disable() - .authorizeExchange() - .pathMatchers(HttpMethod.POST, "/employees/update") - .hasRole("ADMIN") - .pathMatchers("/**") - .permitAll() - .and() - .httpBasic(); + http + .csrf().disable() + .authorizeExchange() + .pathMatchers(HttpMethod.POST, "/employees/update").hasRole("ADMIN") + .pathMatchers("/**").permitAll() + .and() + .httpBasic(); return http.build(); } - + @Bean public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); + return new BCryptPasswordEncoder(); } } diff --git a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/functional/EmployeeFunctionalConfig.java b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/functional/EmployeeFunctionalConfig.java index f97d40e4e7..8b5c7233d6 100644 --- a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/functional/EmployeeFunctionalConfig.java +++ b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/functional/EmployeeFunctionalConfig.java @@ -25,50 +25,49 @@ public class EmployeeFunctionalConfig { @Bean RouterFunction getAllEmployeesRoute() { - return route(GET("/employees"), - req -> ok().body( - employeeRepository().findAllEmployees(), Employee.class)); + return route(GET("/employees"), + req -> ok().body( + employeeRepository().findAllEmployees(), Employee.class)); } @Bean RouterFunction getEmployeeByIdRoute() { - return route(GET("/employees/{id}"), - req -> ok().body( - employeeRepository().findEmployeeById(req.pathVariable("id")), Employee.class)); + return route(GET("/employees/{id}"), + req -> ok().body( + employeeRepository().findEmployeeById(req.pathVariable("id")), Employee.class)); } @Bean RouterFunction updateEmployeeRoute() { - return route(POST("/employees/update"), - req -> req.body(toMono(Employee.class)) - .doOnNext(employeeRepository()::updateEmployee) - .then(ok().build())); + return route(POST("/employees/update"), + req -> req.body(toMono(Employee.class)) + .doOnNext(employeeRepository()::updateEmployee) + .then(ok().build())); } @Bean RouterFunction composedRoutes() { - return - route(GET("/employees"), + return + route(GET("/employees"), req -> ok().body( employeeRepository().findAllEmployees(), Employee.class)) - - .and(route(GET("/employees/{id}"), - req -> ok().body( - employeeRepository().findEmployeeById(req.pathVariable("id")), Employee.class))) - - .and(route(POST("/employees/update"), - req -> req.body(toMono(Employee.class)) - .doOnNext(employeeRepository()::updateEmployee) - .then(ok().build()))); + + .and(route(GET("/employees/{id}"), + req -> ok().body( + employeeRepository().findEmployeeById(req.pathVariable("id")), Employee.class))) + + .and(route(POST("/employees/update"), + req -> req.body(toMono(Employee.class)) + .doOnNext(employeeRepository()::updateEmployee) + .then(ok().build()))); } @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - http.csrf() - .disable() - .authorizeExchange() - .anyExchange() - .permitAll(); + http + .csrf().disable() + .authorizeExchange() + .anyExchange().permitAll(); return http.build(); } } diff --git a/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebClientIntegrationTest.java b/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebClientIntegrationTest.java index 28b4c19a10..22c545c362 100644 --- a/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebClientIntegrationTest.java +++ b/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebClientIntegrationTest.java @@ -45,41 +45,41 @@ import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(classes = WebClientApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class WebClientIntegrationTest { - @LocalServerPort - private int port; - private static final String BODY_VALUE = "bodyValue"; private static final ParameterizedTypeReference> MAP_RESPONSE_REF = new ParameterizedTypeReference>() { }; + @LocalServerPort + private int port; + @Test public void givenDifferentWebClientCreationMethods_whenUsed_thenObtainExpectedResponse() { // WebClient creation WebClient client1 = WebClient.create(); WebClient client2 = WebClient.create("http://localhost:" + port); WebClient client3 = WebClient.builder() - .baseUrl("http://localhost:" + port) - .defaultCookie("cookieKey", "cookieValue") - .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080")) - .build(); + .baseUrl("http://localhost:" + port) + .defaultCookie("cookieKey", "cookieValue") + .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080")) + .build(); // response assertions StepVerifier.create(retrieveResponse(client1.post() .uri("http://localhost:" + port + "/resource"))) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(retrieveResponse(client2)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(retrieveResponse(client3)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); // assert response without specifying URI StepVerifier.create(retrieveResponse(client1)) - .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() - .contains("Connection refused")) - .verify(); + .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() + .contains("Connection refused")) + .verify(); } @Test @@ -91,60 +91,64 @@ public class WebClientIntegrationTest { // response assertions StepVerifier.create(retrieveResponse(uriSpecPost1)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(retrieveResponse(uriSpecPost2)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(retrieveGetResponse(requestGet)) - .expectNextMatches(nextMap -> nextMap.get("field") - .equals("value")) - .verifyComplete(); + .expectNextMatches(nextMap -> nextMap.get("field") + .equals("value")) + .verifyComplete(); } @Test public void givenDifferentUriSpecifications_whenUsed_thenObtainExpectedResponse() { // uri specification RequestBodySpec bodySpecUsingString = createDefaultPostRequest().uri("/resource"); - RequestBodySpec bodySpecUsingUriBuilder = createDefaultPostRequest().uri(uriBuilder -> uriBuilder.pathSegment("resource") + RequestBodySpec bodySpecUsingUriBuilder = createDefaultPostRequest().uri( + uriBuilder -> uriBuilder.pathSegment("resource") .build()); - RequestBodySpec bodySpecusingURI = createDefaultPostRequest().uri(URI.create("http://localhost:" + port + "/resource")); + RequestBodySpec bodySpecusingURI = createDefaultPostRequest().uri( + URI.create("http://localhost:" + port + "/resource")); RequestBodySpec bodySpecOverridenBaseUri = createDefaultPostRequest().uri(URI.create("/resource")); RequestBodySpec bodySpecOverridenBaseUri2 = WebClient.builder() - .baseUrl("http://localhost:" + port) - .build() - .post() - .uri(URI.create("/resource")); + .baseUrl("http://localhost:" + port) + .build() + .post() + .uri(URI.create("/resource")); // response assertions StepVerifier.create(retrieveResponse(bodySpecUsingString)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(retrieveResponse(bodySpecUsingUriBuilder)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(retrieveResponse(bodySpecusingURI)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); // assert sending request overriding base URI StepVerifier.create(retrieveResponse(bodySpecOverridenBaseUri)) - .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() - .contains("Connection refused")) - .verify(); + .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() + .contains("Connection refused")) + .verify(); StepVerifier.create(retrieveResponse(bodySpecOverridenBaseUri2)) - .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() - .contains("Connection refused")) - .verify(); + .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() + .contains("Connection refused")) + .verify(); } @Test public void givenDifferentBodySpecifications_whenUsed_thenObtainExpectedResponse() { // request body specifications - RequestHeadersSpec headersSpecPost1 = createDefaultPostResourceRequest().body(BodyInserters.fromPublisher(Mono.just(BODY_VALUE), String.class)); - RequestHeadersSpec headersSpecPost2 = createDefaultPostResourceRequest().body(BodyInserters.fromValue(BODY_VALUE)); + RequestHeadersSpec headersSpecPost1 = createDefaultPostResourceRequest().body( + BodyInserters.fromPublisher(Mono.just(BODY_VALUE), String.class)); + RequestHeadersSpec headersSpecPost2 = createDefaultPostResourceRequest().body( + BodyInserters.fromValue(BODY_VALUE)); RequestHeadersSpec headersSpecPost3 = createDefaultPostResourceRequest().bodyValue(BODY_VALUE); RequestHeadersSpec headersSpecFooPost = createDefaultPostRequest().uri("/resource-foo") - .body(Mono.just(new Foo("fooName")), Foo.class); + .body(Mono.just(new Foo("fooName")), Foo.class); BodyInserter inserterPlainObject = BodyInserters.fromValue(new Object()); RequestHeadersSpec headersSpecPlainObject = createDefaultPostResourceRequest().body(inserterPlainObject); @@ -152,54 +156,57 @@ public class WebClientIntegrationTest { LinkedMultiValueMap map = new LinkedMultiValueMap<>(); map.add("key1", "multipartValue1"); map.add("key2", "multipartValue2"); - BodyInserter, ClientHttpRequest> inserterMultipart = BodyInserters.fromMultipartData(map); + BodyInserter, ClientHttpRequest> inserterMultipart = BodyInserters.fromMultipartData( + map); RequestHeadersSpec headersSpecInserterMultipart = createDefaultPostRequest().uri("/resource-multipart") - .body(inserterMultipart); + .body(inserterMultipart); // response assertions StepVerifier.create(retrieveResponse(headersSpecPost1)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(retrieveResponse(headersSpecPost2)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(retrieveResponse(headersSpecPost3)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(retrieveResponse(headersSpecFooPost)) - .expectNext("processedFoo-fooName") - .verifyComplete(); + .expectNext("processedFoo-fooName") + .verifyComplete(); StepVerifier.create(retrieveResponse(headersSpecInserterMultipart)) - .expectNext("processed-multipartValue1-multipartValue2") - .verifyComplete(); + .expectNext("processed-multipartValue1-multipartValue2") + .verifyComplete(); // assert error plain `new Object()` as request body StepVerifier.create(retrieveResponse(headersSpecPlainObject)) - .expectError(CodecException.class) - .verify(); + .expectError(CodecException.class) + .verify(); // assert response for request with no body - Mono> responsePostWithNoBody = createDefaultPostResourceRequest().exchangeToMono(responseHandler -> { - assertThat(responseHandler.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST); - return responseHandler.bodyToMono(MAP_RESPONSE_REF); - }); + Mono> responsePostWithNoBody = createDefaultPostResourceRequest().exchangeToMono( + responseHandler -> { + assertThat(responseHandler.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + return responseHandler.bodyToMono(MAP_RESPONSE_REF); + }); StepVerifier.create(responsePostWithNoBody) - .expectNextMatches(nextMap -> nextMap.get("error") - .equals("Bad Request")) - .verifyComplete(); + .expectNextMatches(nextMap -> nextMap.get("error") + .equals("Bad Request")) + .verifyComplete(); } @Test public void givenPostSpecifications_whenHeadersAdded_thenObtainExpectedResponse() { // request header specification - RequestHeadersSpec headersSpecInserterStringWithHeaders = createDefaultPostResourceRequestResponse().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) - .acceptCharset(StandardCharsets.UTF_8) - .ifNoneMatch("*") - .ifModifiedSince(ZonedDateTime.now()); + RequestHeadersSpec headersSpecInserterStringWithHeaders = createDefaultPostResourceRequestResponse().header( + HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) + .acceptCharset(StandardCharsets.UTF_8) + .ifNoneMatch("*") + .ifModifiedSince(ZonedDateTime.now()); // response assertions StepVerifier.create(retrieveResponse(headersSpecInserterStringWithHeaders)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); } @Test @@ -209,68 +216,66 @@ public class WebClientIntegrationTest { Mono responsePostString2 = createDefaultPostResourceRequestResponse().exchangeToMono(response -> { if (response.statusCode() == HttpStatus.OK) { return response.bodyToMono(String.class); - } else if (response.statusCode() - .is4xxClientError()) { + } else if (response.statusCode().is4xxClientError()) { return Mono.just("Error response"); } else { return response.createException() - .flatMap(Mono::error); + .flatMap(Mono::error); } }); Mono responsePostNoBody = createDefaultPostResourceRequest().exchangeToMono(response -> { if (response.statusCode() == HttpStatus.OK) { return response.bodyToMono(String.class); - } else if (response.statusCode() - .is4xxClientError()) { + } else if (response.statusCode().is4xxClientError()) { return Mono.just("Error response"); } else { return response.createException() - .flatMap(Mono::error); + .flatMap(Mono::error); } }); Mono> responseGet = createDefaultClient().get() - .uri("/resource") - .retrieve() - .bodyToMono(MAP_RESPONSE_REF); + .uri("/resource") + .retrieve() + .bodyToMono(MAP_RESPONSE_REF); // response assertions StepVerifier.create(responsePostString) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(responsePostString2) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(responsePostNoBody) - .expectNext("Error response") - .verifyComplete(); + .expectNext("Error response") + .verifyComplete(); StepVerifier.create(responseGet) - .expectNextMatches(nextMap -> nextMap.get("field") - .equals("value")) - .verifyComplete(); + .expectNextMatches(nextMap -> nextMap.get("field") + .equals("value")) + .verifyComplete(); } @Test public void givenWebClientWithTimeoutConfigurations_whenRequestUsingWronglyConfiguredPublisher_thenObtainTimeout() { HttpClient httpClient = HttpClient.create() - .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000) - .responseTimeout(Duration.ofMillis(1000)) - .doOnConnected(conn -> conn.addHandlerLast(new ReadTimeoutHandler(1000, TimeUnit.MILLISECONDS)) - .addHandlerLast(new WriteTimeoutHandler(1000, TimeUnit.MILLISECONDS))); + .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000) + .responseTimeout(Duration.ofMillis(1000)) + .doOnConnected(conn -> conn.addHandlerLast(new ReadTimeoutHandler(1000, TimeUnit.MILLISECONDS)) + .addHandlerLast(new WriteTimeoutHandler(1000, TimeUnit.MILLISECONDS))); WebClient timeoutClient = WebClient.builder() - .baseUrl("http://localhost:" + port) - .clientConnector(new ReactorClientHttpConnector(httpClient)) - .build(); + .baseUrl("http://localhost:" + port) + .clientConnector(new ReactorClientHttpConnector(httpClient)) + .build(); RequestHeadersSpec neverendingMonoBodyRequest = timeoutClient.post() - .uri("/resource") - .body(Mono.never(), String.class); + .uri("/resource") + .body(Mono.never(), String.class); StepVerifier.create(neverendingMonoBodyRequest.retrieve() .bodyToMono(String.class)) - .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ReadTimeoutException.class.isAssignableFrom(ex.getCause() - .getClass())) - .verify(); + .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) + && ReadTimeoutException.class.isAssignableFrom(ex.getCause().getClass())) + .verify(); } // helper methods to create default instances @@ -293,33 +298,33 @@ public class WebClientIntegrationTest { // helper methods to retrieve a response based on different steps of the process (specs) private Mono retrieveResponse(WebClient client) { return client.post() - .uri("/resource") - .bodyValue(BODY_VALUE) - .retrieve() - .bodyToMono(String.class); + .uri("/resource") + .bodyValue(BODY_VALUE) + .retrieve() + .bodyToMono(String.class); } private Mono retrieveResponse(RequestBodyUriSpec spec) { return spec.uri("/resource") - .bodyValue(BODY_VALUE) - .retrieve() - .bodyToMono(String.class); + .bodyValue(BODY_VALUE) + .retrieve() + .bodyToMono(String.class); } private Mono> retrieveGetResponse(RequestHeadersUriSpec spec) { return spec.uri("/resource") - .retrieve() - .bodyToMono(MAP_RESPONSE_REF); + .retrieve() + .bodyToMono(MAP_RESPONSE_REF); } private Mono retrieveResponse(RequestBodySpec spec) { return spec.bodyValue(BODY_VALUE) - .retrieve() - .bodyToMono(String.class); + .retrieve() + .bodyToMono(String.class); } private Mono retrieveResponse(RequestHeadersSpec spec) { return spec.retrieve() - .bodyToMono(String.class); + .bodyToMono(String.class); } } diff --git a/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebControllerIntegrationTest.java b/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebControllerIntegrationTest.java index 3ab687bb41..22bd2829d3 100644 --- a/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebControllerIntegrationTest.java +++ b/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebControllerIntegrationTest.java @@ -1,22 +1,22 @@ package com.baeldung.reactive.webclient; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; -@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = WebClientApplication.class) +import static org.springframework.test.annotation.DirtiesContext.ClassMode.BEFORE_CLASS; + +@DirtiesContext(classMode = BEFORE_CLASS) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = WebClientApplication.class) public class WebControllerIntegrationTest { @LocalServerPort - int randomServerPort; + private int randomServerPort; @Autowired private WebTestClient testClient; @@ -24,30 +24,26 @@ public class WebControllerIntegrationTest { @Autowired private WebController webController; - @Before - public void setup() { + @BeforeEach + void setup() { webController.setServerPort(randomServerPort); } @Test - public void whenEndpointWithBlockingClientIsCalled_thenThreeTweetsAreReceived() { + void whenEndpointWithBlockingClientIsCalled_thenThreeTweetsAreReceived() { testClient.get() .uri("/tweets-blocking") .exchange() - .expectStatus() - .isOk() - .expectBodyList(Tweet.class) - .hasSize(3); + .expectStatus().isOk() + .expectBodyList(Tweet.class).hasSize(3); } @Test - public void whenEndpointWithNonBlockingClientIsCalled_thenThreeTweetsAreReceived() { + void whenEndpointWithNonBlockingClientIsCalled_thenThreeTweetsAreReceived() { testClient.get() .uri("/tweets-non-blocking") .exchange() - .expectStatus() - .isOk() - .expectBodyList(Tweet.class) - .hasSize(3); + .expectStatus().isOk() + .expectBodyList(Tweet.class).hasSize(3); } } \ No newline at end of file diff --git a/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebTestClientIntegrationTest.java b/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebTestClientIntegrationTest.java index 90f4a0eca2..dc2a2a30b9 100644 --- a/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebTestClientIntegrationTest.java +++ b/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebTestClientIntegrationTest.java @@ -3,6 +3,7 @@ package com.baeldung.reactive.webclient; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.ApplicationContext; import org.springframework.security.test.context.support.WithMockUser; @@ -14,7 +15,7 @@ import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.server.WebHandler; import reactor.core.publisher.Mono; -@SpringBootTest(classes = WebClientApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = WebClientApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class WebTestClientIntegrationTest { @LocalServerPort @@ -26,73 +27,61 @@ public class WebTestClientIntegrationTest { @Autowired private WebClientController controller; - private final RouterFunction ROUTER_FUNCTION = RouterFunctions.route(RequestPredicates.GET("/resource"), request -> ServerResponse.ok() - .build()); - private final WebHandler WEB_HANDLER = exchange -> Mono.empty(); - @Test - public void testWebTestClientWithServerWebHandler() { - WebTestClient.bindToWebHandler(WEB_HANDLER) - .build(); + public void whenBindToWebHandler_thenRequestProcessed() { + WebHandler webHandler = exchange -> Mono.empty(); + + WebTestClient.bindToWebHandler(webHandler) + .build() + .get() + .exchange() + .expectBody().isEmpty(); } @Test - public void testWebTestClientWithRouterFunction() { - WebTestClient.bindToRouterFunction(ROUTER_FUNCTION) - .build() - .get() - .uri("/resource") - .exchange() - .expectStatus() - .isOk() - .expectBody() - .isEmpty(); + public void whenBindToRouter_thenRequestProcessed() { + RouterFunction routerFunction = RouterFunctions.route( + RequestPredicates.GET("/resource"), + request -> ServerResponse.ok().build() + ); + + WebTestClient.bindToRouterFunction(routerFunction) + .build() + .get().uri("/resource") + .exchange() + .expectStatus().isOk() + .expectBody().isEmpty(); } @Test @WithMockUser - public void testWebTestClientWithServerURL() { + public void whenBindToServer_thenRequestProcessed() { WebTestClient.bindToServer() - .baseUrl("http://localhost:" + port) - .build() - .get() - .uri("/resource") - .exchange() - .expectStatus() - .isOk() - .expectBody() - .jsonPath("field") - .isEqualTo("value"); - ; + .baseUrl("http://localhost:" + port).build() + .get().uri("/resource") + .exchange() + .expectStatus().isOk() + .expectBody().jsonPath("field").isEqualTo("value"); } @Test @WithMockUser - public void testWebTestClientWithApplicationContext() { + public void whenBindToApplicationContext_thenRequestProcessed() { WebTestClient.bindToApplicationContext(context) - .build() - .get() - .uri("/resource") - .exchange() - .expectStatus() - .isOk() - .expectBody() - .jsonPath("field") - .isEqualTo("value"); + .build() + .get().uri("/resource") + .exchange() + .expectStatus().isOk() + .expectBody().jsonPath("field").isEqualTo("value"); } @Test - public void testWebTestClientWithController() { + public void whenBindToController_thenRequestProcessed() { WebTestClient.bindToController(controller) - .build() - .get() - .uri("/resource") - .exchange() - .expectStatus() - .isOk() - .expectBody() - .jsonPath("field") - .isEqualTo("value"); + .build() + .get().uri("/resource") + .exchange() + .expectStatus().isOk() + .expectBody().jsonPath("field").isEqualTo("value"); } - } diff --git a/spring-reactive/src/test/java/com/baeldung/reactive/webclientrequests/WebClientRequestsUnitTest.java b/spring-reactive/src/test/java/com/baeldung/reactive/webclientrequests/WebClientRequestsUnitTest.java deleted file mode 100644 index ff59f12391..0000000000 --- a/spring-reactive/src/test/java/com/baeldung/reactive/webclientrequests/WebClientRequestsUnitTest.java +++ /dev/null @@ -1,176 +0,0 @@ -package com.baeldung.reactive.webclientrequests; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.reactive.function.client.ClientRequest; -import org.springframework.web.reactive.function.client.ClientResponse; -import org.springframework.web.reactive.function.client.ExchangeFunction; -import org.springframework.web.reactive.function.client.WebClient; -import org.springframework.web.util.DefaultUriBuilderFactory; -import reactor.core.publisher.Mono; - -import java.time.Duration; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -@RunWith(SpringRunner.class) -@WebFluxTest -public class WebClientRequestsUnitTest { - - private static final String BASE_URL = "https://example.com"; - - private WebClient webClient; - - @Captor - private ArgumentCaptor argumentCaptor; - - private ExchangeFunction exchangeFunction; - - @Before - public void init() { - MockitoAnnotations.initMocks(this); - this.exchangeFunction = mock(ExchangeFunction.class); - ClientResponse mockResponse = mock(ClientResponse.class); - when(this.exchangeFunction.exchange(this.argumentCaptor.capture())).thenReturn(Mono.just(mockResponse)); - this.webClient = WebClient - .builder() - .baseUrl(BASE_URL) - .exchangeFunction(exchangeFunction) - .build(); - } - - @Test - public void whenCallSimpleURI_thenURIMatched() { - this.webClient.get() - .uri("/products") - .exchange() - .block(Duration.ofSeconds(1)); - verifyCalledUrl("/products"); - } - - @Test - public void whenCallSinglePathSegmentUri_thenURIMatched() { - this.webClient.get() - .uri(uriBuilder -> uriBuilder - .path("/products/{id}") - .build(2)) - .exchange() - .block(Duration.ofSeconds(1)); - verifyCalledUrl("/products/2"); - } - - @Test - public void whenCallMultiplePathSegmentsUri_thenURIMatched() { - this.webClient.get() - .uri(uriBuilder -> uriBuilder - .path("/products/{id}/attributes/{attributeId}") - .build(2, 13)) - .exchange() - .block(Duration.ofSeconds(1)); - verifyCalledUrl("/products/2/attributes/13"); - } - - @Test - public void whenCallSingleQueryParams_thenURIMatched() { - this.webClient.get() - .uri(uriBuilder -> uriBuilder - .path("/products/") - .queryParam("name", "AndroidPhone") - .queryParam("color", "black") - .queryParam("deliveryDate", "13/04/2019") - .build()) - .exchange() - .block(Duration.ofSeconds(1)); - verifyCalledUrl("/products/?name=AndroidPhone&color=black&deliveryDate=13/04/2019"); - } - - @Test - public void whenCallSingleQueryParamsPlaceholders_thenURIMatched() { - this.webClient.get() - .uri(uriBuilder -> uriBuilder - .path("/products/") - .queryParam("name", "{title}") - .queryParam("color", "{authorId}") - .queryParam("deliveryDate", "{date}") - .build("AndroidPhone", "black", "13/04/2019")) - .exchange() - .block(Duration.ofSeconds(1)); - verifyCalledUrl("/products/?name=AndroidPhone&color=black&deliveryDate=13%2F04%2F2019"); - } - - @Test - public void whenCallArrayQueryParamsBrackets_thenURIMatched() { - this.webClient.get() - .uri(uriBuilder -> uriBuilder - .path("/products/") - .queryParam("tag[]", "Snapdragon", "NFC") - .build()) - .exchange() - .block(Duration.ofSeconds(1)); - verifyCalledUrl("/products/?tag%5B%5D=Snapdragon&tag%5B%5D=NFC"); - } - - - @Test - public void whenCallArrayQueryParams_thenURIMatched() { - this.webClient.get() - .uri(uriBuilder -> uriBuilder - .path("/products/") - .queryParam("category", "Phones", "Tablets") - .build()) - .exchange() - .block(Duration.ofSeconds(1)); - verifyCalledUrl("/products/?category=Phones&category=Tablets"); - } - - @Test - public void whenCallArrayQueryParamsComma_thenURIMatched() { - this.webClient.get() - .uri(uriBuilder -> uriBuilder - .path("/products/") - .queryParam("category", String.join(",", "Phones", "Tablets")) - .build()) - .exchange() - .block(Duration.ofSeconds(1)); - verifyCalledUrl("/products/?category=Phones,Tablets"); - } - - @Test - public void whenUriComponentEncoding_thenQueryParamsNotEscaped() { - DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(BASE_URL); - factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.URI_COMPONENT); - this.webClient = WebClient - .builder() - .uriBuilderFactory(factory) - .baseUrl(BASE_URL) - .exchangeFunction(exchangeFunction) - .build(); - this.webClient.get() - .uri(uriBuilder -> uriBuilder - .path("/products/") - .queryParam("name", "AndroidPhone") - .queryParam("color", "black") - .queryParam("deliveryDate", "13/04/2019") - .build()) - .exchange() - .block(Duration.ofSeconds(1)); - verifyCalledUrl("/products/?name=AndroidPhone&color=black&deliveryDate=13/04/2019"); - } - - private void verifyCalledUrl(String relativeUrl) { - ClientRequest request = this.argumentCaptor.getValue(); - Assert.assertEquals(String.format("%s%s", BASE_URL, relativeUrl), request.url().toString()); - Mockito.verify(this.exchangeFunction).exchange(request); - verifyNoMoreInteractions(this.exchangeFunction); - } -} diff --git a/spring-reactive/src/test/java/com/baeldung/reactive/webclientrequests/WebClientRequestsWithParametersUnitTest.java b/spring-reactive/src/test/java/com/baeldung/reactive/webclientrequests/WebClientRequestsWithParametersUnitTest.java new file mode 100644 index 0000000000..eefde078e1 --- /dev/null +++ b/spring-reactive/src/test/java/com/baeldung/reactive/webclientrequests/WebClientRequestsWithParametersUnitTest.java @@ -0,0 +1,194 @@ +package com.baeldung.reactive.webclientrequests; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.reactive.function.client.ClientRequest; +import org.springframework.web.reactive.function.client.ClientResponse; +import org.springframework.web.reactive.function.client.ExchangeFunction; +import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.util.DefaultUriBuilderFactory; +import reactor.core.publisher.Mono; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +@RunWith(SpringRunner.class) +@WebFluxTest +public class WebClientRequestsWithParametersUnitTest { + + private static final String BASE_URL = "https://example.com"; + + private WebClient webClient; + + @Captor + private ArgumentCaptor argumentCaptor; + + @Mock + private ExchangeFunction exchangeFunction; + + @Before + public void init() { + ClientResponse mockResponse = mock(ClientResponse.class); + when(mockResponse.bodyToMono(String.class)).thenReturn(Mono.just("test")); + when(exchangeFunction.exchange(argumentCaptor.capture())).thenReturn(Mono.just(mockResponse)); + + webClient = WebClient + .builder() + .baseUrl(BASE_URL) + .exchangeFunction(exchangeFunction) + .build(); + } + + @Test + public void whenCallSimpleURI_thenURIMatched() { + webClient.get() + .uri("/products") + .retrieve() + .bodyToMono(String.class) + .block(); + + verifyCalledUrl("/products"); + } + + @Test + public void whenCallSinglePathSegmentUri_thenURIMatched() { + webClient.get() + .uri(uriBuilder -> uriBuilder + .path("/products/{id}") + .build(2)) + .retrieve() + .bodyToMono(String.class) + .block(); + + verifyCalledUrl("/products/2"); + } + + @Test + public void whenCallMultiplePathSegmentsUri_thenURIMatched() { + webClient.get() + .uri(uriBuilder -> uriBuilder + .path("/products/{id}/attributes/{attributeId}") + .build(2, 13)) + .retrieve() + .bodyToMono(String.class) + .block(); + + verifyCalledUrl("/products/2/attributes/13"); + } + + @Test + public void whenCallSingleQueryParams_thenURIMatched() { + webClient.get() + .uri(uriBuilder -> uriBuilder + .path("/products/") + .queryParam("name", "AndroidPhone") + .queryParam("color", "black") + .queryParam("deliveryDate", "13/04/2019") + .build()) + .retrieve() + .bodyToMono(String.class) + .block(); + + verifyCalledUrl("/products/?name=AndroidPhone&color=black&deliveryDate=13/04/2019"); + } + + @Test + public void whenCallSingleQueryParamsPlaceholders_thenURIMatched() { + webClient.get() + .uri(uriBuilder -> uriBuilder + .path("/products/") + .queryParam("name", "{title}") + .queryParam("color", "{authorId}") + .queryParam("deliveryDate", "{date}") + .build("AndroidPhone", "black", "13/04/2019")) + .retrieve() + .bodyToMono(String.class) + .block(); + + verifyCalledUrl("/products/?name=AndroidPhone&color=black&deliveryDate=13%2F04%2F2019"); + } + + @Test + public void whenCallArrayQueryParamsBrackets_thenURIMatched() { + webClient.get() + .uri(uriBuilder -> uriBuilder + .path("/products/") + .queryParam("tag[]", "Snapdragon", "NFC") + .build()) + .retrieve() + .bodyToMono(String.class) + .block(); + + verifyCalledUrl("/products/?tag%5B%5D=Snapdragon&tag%5B%5D=NFC"); + } + + @Test + public void whenCallArrayQueryParams_thenURIMatched() { + webClient.get() + .uri(uriBuilder -> uriBuilder + .path("/products/") + .queryParam("category", "Phones", "Tablets") + .build()) + .retrieve() + .bodyToMono(String.class) + .block(); + + verifyCalledUrl("/products/?category=Phones&category=Tablets"); + } + + @Test + public void whenCallArrayQueryParamsComma_thenURIMatched() { + webClient.get() + .uri(uriBuilder -> uriBuilder + .path("/products/") + .queryParam("category", String.join(",", "Phones", "Tablets")) + .build()) + .retrieve() + .bodyToMono(String.class) + .block(); + + verifyCalledUrl("/products/?category=Phones,Tablets"); + } + + @Test + public void whenUriComponentEncoding_thenQueryParamsNotEscaped() { + DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(BASE_URL); + factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.URI_COMPONENT); + webClient = WebClient + .builder() + .uriBuilderFactory(factory) + .baseUrl(BASE_URL) + .exchangeFunction(exchangeFunction) + .build(); + + webClient.get() + .uri(uriBuilder -> uriBuilder + .path("/products/") + .queryParam("name", "AndroidPhone") + .queryParam("color", "black") + .queryParam("deliveryDate", "13/04/2019") + .build()) + .retrieve() + .bodyToMono(String.class) + .block(); + + verifyCalledUrl("/products/?name=AndroidPhone&color=black&deliveryDate=13/04/2019"); + } + + private void verifyCalledUrl(String relativeUrl) { + ClientRequest request = argumentCaptor.getValue(); + assertEquals(String.format("%s%s", BASE_URL, relativeUrl), request.url().toString()); + + verify(exchangeFunction).exchange(request); + verifyNoMoreInteractions(exchangeFunction); + } +} diff --git a/spring-reactive/src/test/java/com/baeldung/reactive/webflux/annotation/EmployeeControllerIntegrationTest.java b/spring-reactive/src/test/java/com/baeldung/reactive/webflux/annotation/EmployeeControllerIntegrationTest.java index 24c4303e83..699bc9c154 100644 --- a/spring-reactive/src/test/java/com/baeldung/reactive/webflux/annotation/EmployeeControllerIntegrationTest.java +++ b/spring-reactive/src/test/java/com/baeldung/reactive/webflux/annotation/EmployeeControllerIntegrationTest.java @@ -2,27 +2,27 @@ package com.baeldung.reactive.webflux.annotation; import com.baeldung.reactive.webflux.Employee; import com.baeldung.reactive.webflux.EmployeeRepository; -import com.baeldung.reactive.webflux.annotation.EmployeeSpringApplication; -import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes= EmployeeSpringApplication.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@SpringBootTest(webEnvironment = RANDOM_PORT, classes = EmployeeSpringApplication.class) public class EmployeeControllerIntegrationTest { @Autowired @@ -35,40 +35,62 @@ public class EmployeeControllerIntegrationTest { public void givenEmployeeId_whenGetEmployeeById_thenCorrectEmployee() { Employee employee = new Employee("1", "Employee 1 Name"); - + given(employeeRepository.findEmployeeById("1")).willReturn(Mono.just(employee)); + testClient.get() - .uri("/employees/1") - .exchange() - .expectStatus() - .isOk() - .expectBody(Employee.class) - .isEqualTo(employee); + .uri("/employees/1") + .exchange() + .expectStatus().isOk() + .expectBody(Employee.class).isEqualTo(employee); } @Test public void whenGetAllEmployees_thenCorrectEmployees() { - - List employeeList = new ArrayList<>(); - - Employee employee1 = new Employee("1", "Employee 1 Name"); - Employee employee2 = new Employee("2", "Employee 2 Name"); - Employee employee3 = new Employee("3", "Employee 3 Name"); - - employeeList.add(employee1); - employeeList.add(employee2); - employeeList.add(employee3); - + List employeeList = Arrays.asList( + new Employee("1", "Employee 1 Name"), + new Employee("2", "Employee 2 Name"), + new Employee("3", "Employee 3 Name") + ); Flux employeeFlux = Flux.fromIterable(employeeList); given(employeeRepository.findAllEmployees()).willReturn(employeeFlux); + testClient.get() - .uri("/employees") - .exchange() - .expectStatus() - .isOk() - .expectBodyList(Employee.class) - .hasSize(3) - .isEqualTo(employeeList); + .uri("/employees") + .exchange() + .expectStatus().isOk() + .expectBodyList(Employee.class).isEqualTo(employeeList); + } + + @Test + @WithMockUser(username = "admin", roles = { "ADMIN" }) + public void givenValidUser_whenUpdateEmployee_thenEmployeeUpdated() { + Employee employee = new Employee("10", "Employee 10 Updated"); + + given(employeeRepository.updateEmployee(employee)).willReturn(Mono.just(employee)); + + testClient.post() + .uri("/employees/update") + .body(Mono.just(employee), Employee.class) + .exchange() + .expectStatus().isOk() + .expectBody(Employee.class).isEqualTo(employee); + + verify(employeeRepository).updateEmployee(employee); + } + + @Test + @WithMockUser + public void givenInvalidUser_whenUpdateEmployee_thenForbidden() { + Employee employee = new Employee("10", "Employee 10 Updated"); + + testClient.post() + .uri("/employees/update") + .body(Mono.just(employee), Employee.class) + .exchange() + .expectStatus().isForbidden(); + + verifyNoInteractions(employeeRepository); } } diff --git a/spring-reactive/src/test/java/com/baeldung/reactive/webflux/functional/EmployeeSpringFunctionalIntegrationTest.java b/spring-reactive/src/test/java/com/baeldung/reactive/webflux/functional/EmployeeSpringFunctionalIntegrationTest.java index da866724cc..198ec0d081 100644 --- a/spring-reactive/src/test/java/com/baeldung/reactive/webflux/functional/EmployeeSpringFunctionalIntegrationTest.java +++ b/spring-reactive/src/test/java/com/baeldung/reactive/webflux/functional/EmployeeSpringFunctionalIntegrationTest.java @@ -2,10 +2,8 @@ package com.baeldung.reactive.webflux.functional; import com.baeldung.reactive.webflux.Employee; import com.baeldung.reactive.webflux.EmployeeRepository; -import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; @@ -19,10 +17,10 @@ import java.util.List; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = EmployeeSpringFunctionalApplication.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@SpringBootTest(webEnvironment = RANDOM_PORT, classes = EmployeeSpringFunctionalApplication.class) public class EmployeeSpringFunctionalIntegrationTest { @Autowired @@ -34,58 +32,54 @@ public class EmployeeSpringFunctionalIntegrationTest { @Test public void givenEmployeeId_whenGetEmployeeById_thenCorrectEmployee() { WebTestClient client = WebTestClient - .bindToRouterFunction(config.getEmployeeByIdRoute()) - .build(); + .bindToRouterFunction(config.getEmployeeByIdRoute()) + .build(); Employee employee = new Employee("1", "Employee 1"); given(employeeRepository.findEmployeeById("1")).willReturn(Mono.just(employee)); client.get() - .uri("/employees/1") - .exchange() - .expectStatus() - .isOk() - .expectBody(Employee.class) - .isEqualTo(employee); + .uri("/employees/1") + .exchange() + .expectStatus().isOk() + .expectBody(Employee.class).isEqualTo(employee); } @Test public void whenGetAllEmployees_thenCorrectEmployees() { WebTestClient client = WebTestClient - .bindToRouterFunction(config.getAllEmployeesRoute()) - .build(); + .bindToRouterFunction(config.getAllEmployeesRoute()) + .build(); List employees = Arrays.asList( - new Employee("1", "Employee 1"), - new Employee("2", "Employee 2")); + new Employee("1", "Employee 1"), + new Employee("2", "Employee 2") + ); Flux employeeFlux = Flux.fromIterable(employees); given(employeeRepository.findAllEmployees()).willReturn(employeeFlux); client.get() - .uri("/employees") - .exchange() - .expectStatus() - .isOk() - .expectBodyList(Employee.class) - .isEqualTo(employees); + .uri("/employees") + .exchange() + .expectStatus().isOk() + .expectBodyList(Employee.class).isEqualTo(employees); } @Test public void whenUpdateEmployee_thenEmployeeUpdated() { WebTestClient client = WebTestClient - .bindToRouterFunction(config.updateEmployeeRoute()) - .build(); + .bindToRouterFunction(config.updateEmployeeRoute()) + .build(); Employee employee = new Employee("1", "Employee 1 Updated"); client.post() - .uri("/employees/update") - .body(Mono.just(employee), Employee.class) - .exchange() - .expectStatus() - .isOk(); + .uri("/employees/update") + .body(Mono.just(employee), Employee.class) + .exchange() + .expectStatus().isOk(); verify(employeeRepository).updateEmployee(employee); } diff --git a/spring-roo/pom.xml b/spring-roo/pom.xml index ea42095d92..fa84ec9558 100644 --- a/spring-roo/pom.xml +++ b/spring-roo/pom.xml @@ -18,6 +18,190 @@ + + + + + org.springframework.roo + org.springframework.roo.annotations + ${roo.version} + pom + provided + + + io.springlets + springlets-data-jpa + ${springlets.version} + + + io.springlets + springlets-data-commons + ${springlets.version} + + + io.springlets + springlets-context + ${springlets.version} + + + org.springframework.roo + org.springframework.roo.querydsl.processor + ${querydsl-processor.version} + + + io.tracee.binding + tracee-springmvc + ${tracee.version} + + + io.springlets + springlets-boot-starter-web + ${springlets.version} + + + com.github.mxab.thymeleaf.extras + thymeleaf-extras-data-attribute + ${thymeleaf-data-dialect.version} + + + ar.com.fdvs + DynamicJasper + ${dynamicjasper.version} + + + ar.com.fdvs + DynamicJasper-core-fonts + ${dynamicjasper-fonts.version} + + + org.webjars.bower + bootstrap + ${bootstrap.version} + + + org.webjars.bower + datatables + ${datatables.version} + + + org.webjars.bower + datatables.net-bs + ${datatables-bs.version} + + + org.webjars.bower + datatables.net-buttons + ${datatables-buttons.version} + + + org.webjars.bower + datatables.net-buttons-bs + ${datatables-buttons-bs.version} + + + org.webjars.bower + datatables.net-responsive + ${datatables-responsive.version} + + + org.webjars.bower + datatables.net-responsive-bs + ${datatables-responsive-bs.version} + + + org.webjars.bower + datatables.net-select + ${datatables-select.version} + + + org.webjars.bower + datatables.net-select-bs + ${datatables-select-bs.version} + + + org.webjars.npm + jquery-datatables-checkboxes + ${datatables-checkboxes.version} + + + org.webjars.npm + jquery + + + org.webjars.npm + datatables.net + + + + + org.webjars.bower + github-com-julmot-datatables-mark-js + ${datatables-mark.version} + + + org.webjars.bower + datetimepicker + ${datetimepicker.version} + + + org.webjars.bower + font-awesome + ${fontawesome.version} + + + org.webjars.bower + jquery + ${jquery.version} + + + org.webjars + jquery.inputmask + ${jquery-inputmask.version} + + + org.webjars + jquery + + + + + org.webjars.bower + jquery-validation + ${jquery-validation.version} + + + org.webjars.bower + momentjs + ${momentjs.version} + + + org.webjars.bower + select2 + ${select2.version} + + + org.webjars.bower + select2-bootstrap-theme + ${select2-bootstrap-theme.version} + + + org.webjars + respond + ${respond.version} + + + org.webjars + html5shiv + ${html5shiv.version} + + + org.webjars.bower + ie10-viewport-bug-workaround + ${bootstrap.ie10-viewport-bug-workaround.version} + + + + @@ -404,190 +588,6 @@ - - - - - org.springframework.roo - org.springframework.roo.annotations - ${roo.version} - pom - provided - - - io.springlets - springlets-data-jpa - ${springlets.version} - - - io.springlets - springlets-data-commons - ${springlets.version} - - - io.springlets - springlets-context - ${springlets.version} - - - org.springframework.roo - org.springframework.roo.querydsl.processor - ${querydsl-processor.version} - - - io.tracee.binding - tracee-springmvc - ${tracee.version} - - - io.springlets - springlets-boot-starter-web - ${springlets.version} - - - com.github.mxab.thymeleaf.extras - thymeleaf-extras-data-attribute - ${thymeleaf-data-dialect.version} - - - ar.com.fdvs - DynamicJasper - ${dynamicjasper.version} - - - ar.com.fdvs - DynamicJasper-core-fonts - ${dynamicjasper-fonts.version} - - - org.webjars.bower - bootstrap - ${bootstrap.version} - - - org.webjars.bower - datatables - ${datatables.version} - - - org.webjars.bower - datatables.net-bs - ${datatables-bs.version} - - - org.webjars.bower - datatables.net-buttons - ${datatables-buttons.version} - - - org.webjars.bower - datatables.net-buttons-bs - ${datatables-buttons-bs.version} - - - org.webjars.bower - datatables.net-responsive - ${datatables-responsive.version} - - - org.webjars.bower - datatables.net-responsive-bs - ${datatables-responsive-bs.version} - - - org.webjars.bower - datatables.net-select - ${datatables-select.version} - - - org.webjars.bower - datatables.net-select-bs - ${datatables-select-bs.version} - - - org.webjars.npm - jquery-datatables-checkboxes - ${datatables-checkboxes.version} - - - org.webjars.npm - jquery - - - org.webjars.npm - datatables.net - - - - - org.webjars.bower - github-com-julmot-datatables-mark-js - ${datatables-mark.version} - - - org.webjars.bower - datetimepicker - ${datetimepicker.version} - - - org.webjars.bower - font-awesome - ${fontawesome.version} - - - org.webjars.bower - jquery - ${jquery.version} - - - org.webjars - jquery.inputmask - ${jquery-inputmask.version} - - - org.webjars - jquery - - - - - org.webjars.bower - jquery-validation - ${jquery-validation.version} - - - org.webjars.bower - momentjs - ${momentjs.version} - - - org.webjars.bower - select2 - ${select2.version} - - - org.webjars.bower - select2-bootstrap-theme - ${select2-bootstrap-theme.version} - - - org.webjars - respond - ${respond.version} - - - org.webjars - html5shiv - ${html5shiv.version} - - - org.webjars.bower - ie10-viewport-bug-workaround - ${bootstrap.ie10-viewport-bug-workaround.version} - - - - 2.0.0.RELEASE 8 diff --git a/spring-security-modules/pom.xml b/spring-security-modules/pom.xml index 9fdfde282d..eb643c78c7 100644 --- a/spring-security-modules/pom.xml +++ b/spring-security-modules/pom.xml @@ -22,6 +22,7 @@ spring-security-acl spring-security-auth0 spring-security-core + spring-security-core-2 spring-security-ldap spring-security-legacy-oidc spring-security-oauth2-sso @@ -46,6 +47,7 @@ spring-security-web-x509 spring-session spring-social-login + spring-security-opa \ No newline at end of file diff --git a/spring-security-modules/spring-security-core-2/.gitignore b/spring-security-modules/spring-security-core-2/.gitignore new file mode 100644 index 0000000000..9f970225ad --- /dev/null +++ b/spring-security-modules/spring-security-core-2/.gitignore @@ -0,0 +1 @@ +target/ \ No newline at end of file diff --git a/spring-security-modules/spring-security-core-2/README.md b/spring-security-modules/spring-security-core-2/README.md new file mode 100644 index 0000000000..9ce12af8ef --- /dev/null +++ b/spring-security-modules/spring-security-core-2/README.md @@ -0,0 +1,10 @@ +## Spring Security Core + +This module contains articles about core Spring Security + +### Relevant Articles: +- [Handle Spring Security Exceptions](https://www.baeldung.com/spring-security-exceptions) + +### Build the Project + +`mvn clean install` diff --git a/spring-security-modules/spring-security-core-2/pom.xml b/spring-security-modules/spring-security-core-2/pom.xml new file mode 100644 index 0000000000..cf150bfd42 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/pom.xml @@ -0,0 +1,103 @@ + + + 4.0.0 + spring-security-core-2 + 0.1-SNAPSHOT + spring-security-core-2 + war + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-devtools + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-web + + + com.h2database + h2 + runtime + + + org.springframework.security + spring-security-test + + + + + spring-security-core + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-war-plugin + + + + + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/AppInitializer.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/AppInitializer.java new file mode 100644 index 0000000000..43921f71a2 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/AppInitializer.java @@ -0,0 +1,11 @@ +package com.baeldung.exceptionhandler; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AppInitializer { + public static void main(String[] args) { + SpringApplication.run(AppInitializer.class, args); + } +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/controller/AccessDeniedController.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/controller/AccessDeniedController.java new file mode 100644 index 0000000000..0973fe1ad3 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/controller/AccessDeniedController.java @@ -0,0 +1,15 @@ +package com.baeldung.exceptionhandler.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping("/access-denied") +public class AccessDeniedController { + + @GetMapping + public String accessDenied() { + return "/denied.html"; + } +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/controller/CustomErrorController.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/controller/CustomErrorController.java new file mode 100644 index 0000000000..8b65a623eb --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/controller/CustomErrorController.java @@ -0,0 +1,15 @@ +package com.baeldung.exceptionhandler.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping +public class CustomErrorController { + + @GetMapping("/customError") + public String customErrorController() { + return "/error"; + } +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/controller/HomeController.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/controller/HomeController.java new file mode 100644 index 0000000000..d64bf7b5f3 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/controller/HomeController.java @@ -0,0 +1,15 @@ +package com.baeldung.exceptionhandler.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping("/home") +public class HomeController { + + @GetMapping + public String home() { + return "/index.html"; + } +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/controller/SecuredResourceController.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/controller/SecuredResourceController.java new file mode 100644 index 0000000000..a057570e29 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/controller/SecuredResourceController.java @@ -0,0 +1,15 @@ +package com.baeldung.exceptionhandler.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping("/secured") +public class SecuredResourceController { + + @GetMapping + public String secureResource() { + return "/admin.html"; + } +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/security/CustomAccessDeniedHandler.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/security/CustomAccessDeniedHandler.java new file mode 100644 index 0000000000..a3d6aca9be --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/security/CustomAccessDeniedHandler.java @@ -0,0 +1,17 @@ +package com.baeldung.exceptionhandler.security; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.web.access.AccessDeniedHandler; + +public class CustomAccessDeniedHandler implements AccessDeniedHandler { + + @Override + public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exc) throws IOException { + response.sendRedirect("/access-denied"); + } +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/security/CustomAuthenticationFailureHandler.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/security/CustomAuthenticationFailureHandler.java new file mode 100644 index 0000000000..281f9d5289 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/security/CustomAuthenticationFailureHandler.java @@ -0,0 +1,17 @@ +package com.baeldung.exceptionhandler.security; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; + +public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler { + + @Override + public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException { + httpServletResponse.sendRedirect("/customError"); + } +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/security/CustomAuthenticationSuccessHandler.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/security/CustomAuthenticationSuccessHandler.java new file mode 100644 index 0000000000..62cbdf8873 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/security/CustomAuthenticationSuccessHandler.java @@ -0,0 +1,31 @@ +package com.baeldung.exceptionhandler.security; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; + +public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler { + + @Override + public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { + + HttpSession session = httpServletRequest.getSession(); + User authUser = (User) SecurityContextHolder.getContext() + .getAuthentication() + .getPrincipal(); + session.setAttribute("username", authUser.getUsername()); + session.setAttribute("authorities", authentication.getAuthorities()); + + httpServletResponse.setStatus(HttpServletResponse.SC_OK); + + httpServletResponse.sendRedirect("/home"); + } +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/security/SecurityConfig.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/security/SecurityConfig.java new file mode 100644 index 0000000000..71ded0f131 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/exceptionhandler/security/SecurityConfig.java @@ -0,0 +1,98 @@ +package com.baeldung.exceptionhandler.security; + +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.factory.PasswordEncoderFactories; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; + +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Bean + public UserDetailsService userDetailsService() { + + UserDetails user = User.withUsername("user") + .passwordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder()::encode) + .password("password") + .roles("USER") + .build(); + + UserDetails admin = User.withUsername("admin") + .passwordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder()::encode) + .password("password") + .roles("ADMIN") + .build(); + + InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(); + + userDetailsManager.createUser(user); + userDetailsManager.createUser(admin); + + return userDetailsManager; + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("user") + .password("{noop}password") + .roles("USER") + .and() + .withUser("admin") + .password("{noop}password") + .roles("ADMIN"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf() + .disable() + .httpBasic() + .disable() + .authorizeRequests() + .antMatchers("/login") + .permitAll() + .antMatchers("/customError") + .permitAll() + .antMatchers("/access-denied") + .permitAll() + .antMatchers("/secured") + .hasRole("ADMIN") + .anyRequest() + .authenticated() + .and() + .formLogin() + .failureHandler(authenticationFailureHandler()) + .successHandler(authenticationSuccessHandler()) + .and() + .exceptionHandling() + .accessDeniedHandler(accessDeniedHandler()) + .and() + .logout(); + } + + @Bean + public AuthenticationFailureHandler authenticationFailureHandler() { + return new CustomAuthenticationFailureHandler(); + } + + @Bean + public AuthenticationSuccessHandler authenticationSuccessHandler() { + return new CustomAuthenticationSuccessHandler(); + } + + @Bean + public AccessDeniedHandler accessDeniedHandler() { + return new CustomAccessDeniedHandler(); + } + +} diff --git a/spring-security-modules/spring-security-core-2/src/main/resources/application.properties b/spring-security-modules/spring-security-core-2/src/main/resources/application.properties new file mode 100644 index 0000000000..9d154c9cc0 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.thymeleaf.prefix=classpath:/templates/ \ No newline at end of file diff --git a/spring-security-modules/spring-security-core-2/src/main/resources/templates/admin.html b/spring-security-modules/spring-security-core-2/src/main/resources/templates/admin.html new file mode 100644 index 0000000000..d7f7ec232a --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/resources/templates/admin.html @@ -0,0 +1,5 @@ + + +
Hello Admin!
+ + diff --git a/spring-security-modules/spring-security-core-2/src/main/resources/templates/denied.html b/spring-security-modules/spring-security-core-2/src/main/resources/templates/denied.html new file mode 100644 index 0000000000..b7a8e09309 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/resources/templates/denied.html @@ -0,0 +1,5 @@ + + +
You need permission to perform this action.
+ + diff --git a/spring-security-modules/spring-security-core-2/src/main/resources/templates/error.html b/spring-security-modules/spring-security-core-2/src/main/resources/templates/error.html new file mode 100644 index 0000000000..ce74f05d99 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/resources/templates/error.html @@ -0,0 +1,5 @@ + + +
Ups! Wrong credentials
+ + diff --git a/spring-security-modules/spring-security-core-2/src/main/resources/templates/index.html b/spring-security-modules/spring-security-core-2/src/main/resources/templates/index.html new file mode 100644 index 0000000000..34d070b37a --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/resources/templates/index.html @@ -0,0 +1,6 @@ + + +
Hello User!
+ + + diff --git a/spring-security-modules/spring-security-core-2/src/test/java/com/baeldung/exceptionhandler/SecurityConfigUnitTest.java b/spring-security-modules/spring-security-core-2/src/test/java/com/baeldung/exceptionhandler/SecurityConfigUnitTest.java new file mode 100644 index 0000000000..ad35d575a5 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/test/java/com/baeldung/exceptionhandler/SecurityConfigUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.exceptionhandler; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.exceptionhandler.security.SecurityConfig; + +@RunWith(SpringRunner.class) +@WebMvcTest(SecurityConfig.class) +class SecurityConfigUnitTest { + @Autowired + private MockMvc mvc; + + @Test + void whenUserAccessLogin_shouldSucceed() throws Exception { + mvc.perform(get("/login")) + .andExpect(status().isOk()); + } + + @Test + void whenUserAccessWithWrongCredentials_shouldRedirectToCustomErrorPage() throws Exception { + mvc.perform(formLogin("/login").user("username", "wrong") + .password("password", "credentials")) + .andExpect(redirectedUrl("/customError")); + } + + @Test + void whenUserAccessWithCorrectCredentials_shouldRedirectToHome() throws Exception { + mvc.perform(formLogin("/login").user("username", "user") + .password("password", "password")) + .andExpect(redirectedUrl("/home")); + } + + @Test + @WithMockUser(username = "user", roles = { "USER" }) + void whenUserAccessToSecuredPageWithoutUserRole_shouldRedirectToDeniedPage() throws Exception { + mvc.perform(get("/secured")) + .andExpect(redirectedUrl("/access-denied")); + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-core/README.md b/spring-security-modules/spring-security-core/README.md index 9f8e4dda53..1949b5a929 100644 --- a/spring-security-modules/spring-security-core/README.md +++ b/spring-security-modules/spring-security-core/README.md @@ -10,6 +10,7 @@ This module contains articles about core Spring Security - [Deny Access on Missing @PreAuthorize to Spring Controller Methods](https://www.baeldung.com/spring-deny-access) - [Spring Security: Check If a User Has a Role in Java](https://www.baeldung.com/spring-security-check-user-role) - [Filtering Jackson JSON Output Based on Spring Security Role](https://www.baeldung.com/spring-security-role-filter-json) +- [Handle Spring Security Exceptions](https://www.baeldung.com/spring-security-exceptions) ### Build the Project diff --git a/spring-security-modules/spring-security-opa/README.md b/spring-security-modules/spring-security-opa/README.md new file mode 100644 index 0000000000..d2c1652edb --- /dev/null +++ b/spring-security-modules/spring-security-opa/README.md @@ -0,0 +1,4 @@ + +### Relevant Articles: + +- [Spring Security Authorization with OPA](https://www.baeldung.com/spring-security-authorization-opa) diff --git a/spring-security-modules/spring-security-opa/pom.xml b/spring-security-modules/spring-security-opa/pom.xml new file mode 100644 index 0000000000..72b0574253 --- /dev/null +++ b/spring-security-modules/spring-security-opa/pom.xml @@ -0,0 +1,48 @@ + + 4.0.0 + spring-security-opa + Spring Security with OPA authorization + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.boot + spring-boot-starter-security + + + org.projectlombok + lombok + + + com.google.guava + guava + 31.0.1-jre + + + org.springframework.boot + spring-boot-devtools + + + org.springframework.security + spring-security-test + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/Application.java b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/Application.java new file mode 100644 index 0000000000..789a1f803f --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/Application.java @@ -0,0 +1,13 @@ +package com.baeldung.security.opa; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/OpaConfiguration.java b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/OpaConfiguration.java new file mode 100644 index 0000000000..e24fdbcf35 --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/OpaConfiguration.java @@ -0,0 +1,25 @@ +package com.baeldung.security.opa.config; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.reactive.function.client.WebClient; + +import lombok.RequiredArgsConstructor; + +@Configuration +@RequiredArgsConstructor +@EnableConfigurationProperties(OpaProperties.class) +public class OpaConfiguration { + + private final OpaProperties opaProperties; + + @Bean + public WebClient opaWebClient(WebClient.Builder builder) { + + return builder + .baseUrl(opaProperties.getEndpoint()) + .build(); + } + +} diff --git a/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/OpaProperties.java b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/OpaProperties.java new file mode 100644 index 0000000000..acc23a2fd2 --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/OpaProperties.java @@ -0,0 +1,14 @@ +package com.baeldung.security.opa.config; + +import javax.annotation.Nonnull; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import lombok.Data; + +@ConfigurationProperties(prefix = "opa") +@Data +public class OpaProperties { + @Nonnull + private String endpoint = "http://localhost:8181"; +} diff --git a/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/SecurityConfiguration.java b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/SecurityConfiguration.java new file mode 100644 index 0000000000..7e10cb2e8a --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/SecurityConfiguration.java @@ -0,0 +1,110 @@ +package com.baeldung.security.opa.config; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +import org.reactivestreams.Publisher; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.MediaType; +import org.springframework.http.client.reactive.ClientHttpRequest; +import org.springframework.security.authentication.AnonymousAuthenticationToken; +import org.springframework.security.authorization.AuthorizationDecision; +import org.springframework.security.authorization.ReactiveAuthorizationManager; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.web.server.SecurityWebFilterChain; +import org.springframework.security.web.server.authorization.AuthorizationContext; +import org.springframework.web.reactive.function.BodyInserter; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.ClientResponse; +import org.springframework.web.reactive.function.client.WebClient; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.collect.ImmutableMap; + +import reactor.core.publisher.Mono; + +@Configuration +public class SecurityConfiguration { + + + @Bean + public SecurityWebFilterChain accountAuthorization(ServerHttpSecurity http, @Qualifier("opaWebClient")WebClient opaWebClient) { + + // @formatter:on + return http + .httpBasic() + .and() + .authorizeExchange(exchanges -> { + exchanges + .pathMatchers("/account/*") + .access(opaAuthManager(opaWebClient)); + }) + .build(); + // @formatter:on + + } + + @Bean + public ReactiveAuthorizationManager opaAuthManager(WebClient opaWebClient) { + + return (auth, context) -> { + return opaWebClient.post() + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .body(toAuthorizationPayload(auth,context), Map.class) + .exchangeToMono(this::toDecision); + }; + } + + private Mono toDecision(ClientResponse response) { + + if ( !response.statusCode().is2xxSuccessful()) { + return Mono.just(new AuthorizationDecision(false)); + } + + return response + .bodyToMono(ObjectNode.class) + .map(node -> { + boolean authorized = node.path("result").path("authorized").asBoolean(false); + return new AuthorizationDecision(authorized); + }); + + } + + private Publisher> toAuthorizationPayload(Mono auth, AuthorizationContext context) { + // @formatter:off + return auth + .defaultIfEmpty(new AnonymousAuthenticationToken("**ANONYMOUS**", new Object(), Arrays.asList(new SimpleGrantedAuthority("ANONYMOUS")))) + .map( a -> { + + Map headers = context.getExchange().getRequest() + .getHeaders() + .toSingleValueMap(); + + Map attributes = ImmutableMap.builder() + .put("principal",a.getName()) + .put("authorities", + a.getAuthorities() + .stream() + .map(g -> g.getAuthority()) + .collect(Collectors.toList())) + .put("uri", context.getExchange().getRequest().getURI().getPath()) + .put("headers",headers) + .build(); + + Map input = ImmutableMap.builder() + .put("input",attributes) + .build(); + + return input; + }); + // @formatter:on + } +} diff --git a/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/controller/AccountController.java b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/controller/AccountController.java new file mode 100644 index 0000000000..ba0ff61554 --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/controller/AccountController.java @@ -0,0 +1,23 @@ +package com.baeldung.security.opa.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.security.opa.domain.Account; +import com.baeldung.security.opa.service.AccountService; + +import lombok.RequiredArgsConstructor; +import reactor.core.publisher.Mono; + +@RestController +@RequiredArgsConstructor +public class AccountController { + + private final AccountService accountService; + + @GetMapping("/account/{accountId}") + public Mono getAccount(@PathVariable("accountId") String accountId) { + return accountService.findByAccountId(accountId); + } +} diff --git a/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/domain/Account.java b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/domain/Account.java new file mode 100644 index 0000000000..db494627a8 --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/domain/Account.java @@ -0,0 +1,25 @@ +package com.baeldung.security.opa.domain; + +import java.math.BigDecimal; + +import lombok.Data; + +@Data +public class Account { + + private String id; + private BigDecimal balance; + private String currency; + + + public static Account of(String id, BigDecimal balance, String currency) { + Account acc = new Account(); + acc.setId(id); + acc.setBalance(balance); + acc.setCurrency(currency); + + return acc; + } + + +} diff --git a/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/service/AccountService.java b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/service/AccountService.java new file mode 100644 index 0000000000..18968019f9 --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/service/AccountService.java @@ -0,0 +1,37 @@ +/** + * + */ +package com.baeldung.security.opa.service; + +import java.math.BigDecimal; +import java.util.Map; + +import org.springframework.stereotype.Service; + +import com.baeldung.security.opa.domain.Account; +import com.google.common.collect.ImmutableMap; + +import reactor.core.publisher.Mono; + +/** + * @author Philippe + * + */ +@Service +public class AccountService { + + private Map accounts = ImmutableMap.builder() + .put("0001", Account.of("0001", BigDecimal.valueOf(100.00), "USD")) + .put("0002", Account.of("0002", BigDecimal.valueOf(101.00), "EUR")) + .put("0003", Account.of("0003", BigDecimal.valueOf(102.00), "BRL")) + .put("0004", Account.of("0004", BigDecimal.valueOf(103.00), "AUD")) + .put("0005", Account.of("0005", BigDecimal.valueOf(10400.00), "JPY")) + .build(); + + + public Mono findByAccountId(String accountId) { + return Mono.just(accounts.get(accountId)) + .switchIfEmpty(Mono.error(new IllegalArgumentException("invalid.account"))); + } + +} diff --git a/spring-security-modules/spring-security-opa/src/main/resources/application.yaml b/spring-security-modules/spring-security-opa/src/main/resources/application.yaml new file mode 100644 index 0000000000..6fb9200277 --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/main/resources/application.yaml @@ -0,0 +1,3 @@ +# OPA configuration properties +opa: + endpoint: http://localhost:8181/v1/data/baeldung/auth/account \ No newline at end of file diff --git a/spring-security-modules/spring-security-opa/src/test/java/com/baeldung/security/opa/controller/AccountControllerLiveTest.java b/spring-security-modules/spring-security-opa/src/test/java/com/baeldung/security/opa/controller/AccountControllerLiveTest.java new file mode 100644 index 0000000000..7469fd327c --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/test/java/com/baeldung/security/opa/controller/AccountControllerLiveTest.java @@ -0,0 +1,67 @@ +package com.baeldung.security.opa.controller; + +import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.reactive.server.WebTestClient; + +// !!! NOTICE: Start OPA server before running this test class !!! +@SpringBootTest +@ActiveProfiles("test") +class AccountControllerLiveTest { + + @Autowired + ApplicationContext context; + WebTestClient rest; + + @BeforeEach + public void setup() { + this.rest = WebTestClient.bindToApplicationContext(this.context) + .apply(springSecurity()) + .configureClient() + .build(); + } + + + @Test + @WithMockUser(username = "user1", roles = { "account:read:0001"} ) + void testGivenValidUser_thenSuccess() { + rest.get() + .uri("/account/0001") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .is2xxSuccessful(); + } + + @Test + @WithMockUser(username = "user1", roles = { "account:read:0002"} ) + void testGivenValidUser_thenUnauthorized() { + rest.get() + .uri("/account/0001") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isForbidden(); + } + + @Test + @WithMockUser(username = "user1", roles = {} ) + void testGivenNoAuthorities_thenForbidden() { + rest.get() + .uri("/account/0001") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isForbidden(); + } + + +} diff --git a/spring-security-modules/spring-security-opa/src/test/rego/account.rego b/spring-security-modules/spring-security-opa/src/test/rego/account.rego new file mode 100644 index 0000000000..567d531bb4 --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/test/rego/account.rego @@ -0,0 +1,43 @@ +# +# Simple authorization rule for accounts +# +# Assumes an input document with the following properties: +# +# resource: requested resource +# method: request method +# authorities: Granted authorities +# headers: Request headers +# +package baeldung.auth.account + +# Not authorized by default +default authorized = false + +# Authorize when there are no rules that deny access to the resource and +# there's at least one rule allowing +authorized = true { + count(deny) == 0 + count(allow) > 0 +} + +# Allow access to /public +allow["public"] { + regex.match("^/public/.*",input.uri) +} + +# Account API requires authenticated user +deny["account_api_authenticated"] { + regex.match("^/account/.*",input.uri) + regex.match("ANONYMOUS",input.principal) +} + +# Authorize access to account if principal has +# matching authority +allow["account_api_authorized"] { + regex.match("^/account/.+",input.uri) + parts := split(input.uri,"/") + account := parts[2] + role := concat(":",[ "ROLE_account", "read", account] ) + role == input.authorities[i] +} + diff --git a/spring-security-modules/spring-security-web-boot-3/pom.xml b/spring-security-modules/spring-security-web-boot-3/pom.xml index 5da993acd9..0984c25e07 100644 --- a/spring-security-modules/spring-security-web-boot-3/pom.xml +++ b/spring-security-modules/spring-security-web-boot-3/pom.xml @@ -1,6 +1,7 @@ - + 4.0.0 spring-security-web-boot-3 0.0.1-SNAPSHOT @@ -73,5 +74,4 @@ 3.6.0
- \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-login/pom.xml b/spring-security-modules/spring-security-web-login/pom.xml index 346338cbcd..c2369abc14 100644 --- a/spring-security-modules/spring-security-web-login/pom.xml +++ b/spring-security-modules/spring-security-web-login/pom.xml @@ -118,7 +118,7 @@ runtime
- + org.springframework.boot spring-boot-starter-test ${spring-boot.version} @@ -136,11 +136,11 @@ ${spring-security.version} test - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - + + org.apache.commons + commons-lang3 + ${commons-lang3.version} +
diff --git a/spring-security-modules/spring-security-web-rest/README.md b/spring-security-modules/spring-security-web-rest/README.md index fd1f86f6b8..5a94504762 100644 --- a/spring-security-modules/spring-security-web-rest/README.md +++ b/spring-security-modules/spring-security-web-rest/README.md @@ -9,7 +9,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: -- [Setting Up Swagger 2 with a Spring REST API](https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) +- [Setting Up Swagger 2 with a Spring REST API Using Springfox](https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) - [Custom Error Message Handling for REST API](https://www.baeldung.com/global-error-handler-in-a-spring-rest-api) - [Spring Security Context Propagation with @Async](https://www.baeldung.com/spring-security-async-principal-propagation) - [Servlet 3 Async Support with Spring MVC and Spring Security](https://www.baeldung.com/spring-mvc-async-security) diff --git a/spring-security-modules/spring-security-web-x509/spring-security-web-x509-basic-auth/pom.xml b/spring-security-modules/spring-security-web-x509/spring-security-web-x509-basic-auth/pom.xml index 9598843b63..12153c91f2 100644 --- a/spring-security-modules/spring-security-web-x509/spring-security-web-x509-basic-auth/pom.xml +++ b/spring-security-modules/spring-security-web-x509/spring-security-web-x509-basic-auth/pom.xml @@ -21,7 +21,6 @@ org.springframework.boot spring-boot-maven-plugin
- org.apache.maven.plugins maven-surefire-plugin diff --git a/spring-security-modules/spring-security-web-x509/spring-security-web-x509-client-auth/pom.xml b/spring-security-modules/spring-security-web-x509/spring-security-web-x509-client-auth/pom.xml index f310ab1e5c..f3ea2728f2 100644 --- a/spring-security-modules/spring-security-web-x509/spring-security-web-x509-client-auth/pom.xml +++ b/spring-security-modules/spring-security-web-x509/spring-security-web-x509-client-auth/pom.xml @@ -21,7 +21,6 @@ org.springframework.boot spring-boot-maven-plugin - org.apache.maven.plugins maven-surefire-plugin diff --git a/spring-state-machine/pom.xml b/spring-state-machine/pom.xml index bc2b67cc38..741361b3fa 100644 --- a/spring-state-machine/pom.xml +++ b/spring-state-machine/pom.xml @@ -18,6 +18,11 @@ spring-statemachine-core ${spring-statemachine-core.version}
+ + org.springframework + spring-context + ${spring-context.version} + org.springframework spring-test @@ -32,7 +37,8 @@ - 1.2.3.RELEASE + 3.2.0 + 5.3.19 4.3.7.RELEASE 1.7.0 diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml b/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml index 2afde0b07d..f125018fb0 100644 --- a/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml @@ -9,13 +9,11 @@ jar https://github.com/openapitools/openapi-generator OpenAPI Java - scm:git:git@github.com:openapitools/openapi-generator.git scm:git:git@github.com:openapitools/openapi-generator.git https://github.com/openapitools/openapi-generator - Unlicense @@ -23,7 +21,6 @@ repo - OpenAPI-Generator Contributors diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml index 66e9d1dda2..c9ba912feb 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml @@ -8,13 +8,11 @@ jar https://github.com/swagger-api/swagger-codegen Swagger Java - scm:git:git@github.com:swagger-api/swagger-codegen.git scm:git:git@github.com:swagger-api/swagger-codegen.git https://github.com/swagger-api/swagger-codegen - Unlicense @@ -22,7 +20,6 @@ repo - Swagger diff --git a/spring-web-modules/spring-rest-http-2/README.md b/spring-web-modules/spring-rest-http-2/README.md index bb9175db8c..2c1b1f76f7 100644 --- a/spring-web-modules/spring-rest-http-2/README.md +++ b/spring-web-modules/spring-rest-http-2/README.md @@ -11,4 +11,7 @@ The "REST With Spring 2" Classes: http://bit.ly/restwithspring - [Setting a Request Timeout for a Spring REST API](https://www.baeldung.com/spring-rest-timeout) - [Long Polling in Spring MVC](https://www.baeldung.com/spring-mvc-long-polling) - [Guide to UriComponentsBuilder in Spring](https://www.baeldung.com/spring-uricomponentsbuilder) +- [Get All Endpoints in Spring Boot](https://www.baeldung.com/spring-boot-get-all-endpoints) +- [HTTP PUT vs. POST in REST API](https://www.baeldung.com/rest-http-put-vs-post) +- [415 Unsupported MediaType in Spring Application](https://www.baeldung.com/spring-415-unsupported-mediatype) - More articles: [[<-- prev]](../spring-rest-http) diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/SpringBootRestApplication.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/endpoint/SpringBootRestApplication.java similarity index 100% rename from spring-boot-rest-2/src/main/java/com/baeldung/endpoint/SpringBootRestApplication.java rename to spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/endpoint/SpringBootRestApplication.java diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/controller/HelloController.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/endpoint/controller/HelloController.java similarity index 100% rename from spring-boot-rest-2/src/main/java/com/baeldung/endpoint/controller/HelloController.java rename to spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/endpoint/controller/HelloController.java diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/listener/AnnotationDrivenEndpointsListener.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/endpoint/listener/AnnotationDrivenEndpointsListener.java similarity index 100% rename from spring-boot-rest-2/src/main/java/com/baeldung/endpoint/listener/AnnotationDrivenEndpointsListener.java rename to spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/endpoint/listener/AnnotationDrivenEndpointsListener.java diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/listener/EndpointsListener.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/endpoint/listener/EndpointsListener.java similarity index 100% rename from spring-boot-rest-2/src/main/java/com/baeldung/endpoint/listener/EndpointsListener.java rename to spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/endpoint/listener/EndpointsListener.java diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/swagger/SpringFoxConfig.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/endpoint/swagger/SpringFoxConfig.java similarity index 100% rename from spring-boot-rest-2/src/main/java/com/baeldung/endpoint/swagger/SpringFoxConfig.java rename to spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/endpoint/swagger/SpringFoxConfig.java diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/putvspost/Address.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/putvspost/Address.java similarity index 100% rename from spring-boot-rest-2/src/main/java/com/baeldung/putvspost/Address.java rename to spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/putvspost/Address.java diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/putvspost/AddressController.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/putvspost/AddressController.java similarity index 100% rename from spring-boot-rest-2/src/main/java/com/baeldung/putvspost/AddressController.java rename to spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/putvspost/AddressController.java diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/putvspost/AddressRepository.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/putvspost/AddressRepository.java similarity index 100% rename from spring-boot-rest-2/src/main/java/com/baeldung/putvspost/AddressRepository.java rename to spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/putvspost/AddressRepository.java diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/putvspost/PutVsPostApplication.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/putvspost/PutVsPostApplication.java similarity index 100% rename from spring-boot-rest-2/src/main/java/com/baeldung/putvspost/PutVsPostApplication.java rename to spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/putvspost/PutVsPostApplication.java diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UnsupportedMediaTypeApplication.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/unsupportedmediatype/UnsupportedMediaTypeApplication.java similarity index 100% rename from spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UnsupportedMediaTypeApplication.java rename to spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/unsupportedmediatype/UnsupportedMediaTypeApplication.java diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/unsupportedmediatype/User.java similarity index 100% rename from spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java rename to spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/unsupportedmediatype/User.java diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UserController.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/unsupportedmediatype/UserController.java similarity index 100% rename from spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UserController.java rename to spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/unsupportedmediatype/UserController.java diff --git a/spring-web-modules/spring-rest-http-2/src/main/resources/application.properties b/spring-web-modules/spring-rest-http-2/src/main/resources/application.properties index ff4af943ec..3119ad188a 100644 --- a/spring-web-modules/spring-rest-http-2/src/main/resources/application.properties +++ b/spring-web-modules/spring-rest-http-2/src/main/resources/application.properties @@ -1 +1,2 @@ -spring.mvc.async.request-timeout=750 \ No newline at end of file +spring.mvc.async.request-timeout=750 +management.endpoints.web.exposure.include=mappings \ No newline at end of file diff --git a/spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java b/spring-web-modules/spring-rest-http-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java similarity index 100% rename from spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java rename to spring-web-modules/spring-rest-http-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java diff --git a/spring-web-modules/spring-rest-http-2/src/test/resources/application.properties b/spring-web-modules/spring-rest-http-2/src/test/resources/application.properties index ff4af943ec..10ac1ab5fa 100644 --- a/spring-web-modules/spring-rest-http-2/src/test/resources/application.properties +++ b/spring-web-modules/spring-rest-http-2/src/test/resources/application.properties @@ -1 +1,2 @@ -spring.mvc.async.request-timeout=750 \ No newline at end of file +spring.mvc.async.request-timeout=750 +spring.main.allow-bean-definition-overriding=true diff --git a/spring-web-modules/spring-resttemplate/pom.xml b/spring-web-modules/spring-resttemplate/pom.xml index e5a8ba5ea9..4abaac5628 100644 --- a/spring-web-modules/spring-resttemplate/pom.xml +++ b/spring-web-modules/spring-resttemplate/pom.xml @@ -37,12 +37,12 @@ org.springframework.boot spring-boot-starter-test - + au.com.dius pact-jvm-provider-junit5_2.12 ${pact.version} - - + + au.com.dius pact-jvm-consumer-junit5_2.12 ${pact.version} @@ -119,10 +119,10 @@ spring-test - org.mockito - mockito-junit-jupiter - ${mockito.version} - test + org.mockito + mockito-junit-jupiter + ${mockito.version} + test diff --git a/testing-modules/junit-5-basics/pom.xml b/testing-modules/junit-5-basics/pom.xml index e6636e3239..a758d79069 100644 --- a/testing-modules/junit-5-basics/pom.xml +++ b/testing-modules/junit-5-basics/pom.xml @@ -17,7 +17,7 @@ org.junit.platform - junit-platform-runner + junit-platform-suite ${junit-platform.version} test diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/GreetingsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/GreetingsUnitTest.java index a07162ceed..1ff21548b8 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/GreetingsUnitTest.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/GreetingsUnitTest.java @@ -3,12 +3,9 @@ package com.baeldung; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; import com.baeldung.junit5.Greetings; -@RunWith(JUnitPlatform.class) public class GreetingsUnitTest { @Test diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java index 311c62f425..252bbdb2ce 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java @@ -10,7 +10,6 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -//@RunWith(JUnitPlatform.class) public class JUnit5NewFeaturesUnitTest { private static final Logger log = Logger.getLogger(JUnit5NewFeaturesUnitTest.class.getName()); diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java index c2bbfd4d07..b324910ab7 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java @@ -6,12 +6,9 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; @Tag("annotations") @Tag("junit5") -@RunWith(JUnitPlatform.class) public class AnnotationTestExampleUnitTest { @Test public void shouldRaiseAnException() throws Exception { diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java index c35611aad1..14b1162ecf 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java @@ -6,10 +6,7 @@ import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; -@RunWith(JUnitPlatform.class) public class AssertionsExampleUnitTest { @Test @Disabled diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java index 5181d54a46..68bb66657e 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java @@ -3,12 +3,9 @@ package com.baeldung.migration.junit5; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -@RunWith(JUnitPlatform.class) public class BeforeAllAndAfterAllAnnotationsUnitTest { private static final Logger LOG = LoggerFactory.getLogger(BeforeAllAndAfterAllAnnotationsUnitTest.class); diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java index b2112ef2c3..283665798d 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java @@ -9,12 +9,9 @@ import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -@RunWith(JUnitPlatform.class) public class BeforeEachAndAfterEachAnnotationsUnitTest { private static final Logger LOG = LoggerFactory.getLogger(BeforeEachAndAfterEachAnnotationsUnitTest.class); diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java index c67a57dcbd..5c878ef7d3 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java @@ -1,14 +1,12 @@ package com.baeldung.migration.junit5; -import com.baeldung.migration.junit5.extensions.TraceUnitExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -@RunWith(JUnitPlatform.class) +import com.baeldung.migration.junit5.extensions.TraceUnitExtension; + @ExtendWith(TraceUnitExtension.class) public class RuleExampleUnitTest { diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/suites/AllUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/suites/AllUnitTest.java index 30b92ad428..b14440f1f2 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/suites/AllUnitTest.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/suites/AllUnitTest.java @@ -1,12 +1,13 @@ package com.baeldung.suites; -import org.junit.platform.runner.JUnitPlatform; +import org.junit.platform.suite.api.ExcludePackages; import org.junit.platform.suite.api.SelectPackages; -import org.junit.runner.RunWith; +import org.junit.platform.suite.api.Suite; -@RunWith(JUnitPlatform.class) +@Suite @SelectPackages("com.baeldung") -// @SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class}) +@ExcludePackages("com.baeldung.suites") public class AllUnitTest { } + \ No newline at end of file diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOTestSuite.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOTestSuite.java index 783e5a81a2..cddb76381f 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOTestSuite.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOTestSuite.java @@ -1,11 +1,8 @@ package com.baeldung.tags; -import org.junit.platform.runner.JUnitPlatform; import org.junit.platform.suite.api.IncludeTags; import org.junit.platform.suite.api.SelectPackages; -import org.junit.runner.RunWith; -@RunWith(JUnitPlatform.class) @SelectPackages("com.baeldung.tags") @IncludeTags("UnitTest") public class EmployeeDAOTestSuite { diff --git a/testing-modules/junit-5/pom.xml b/testing-modules/junit-5/pom.xml index f794c3990f..047eddcbcb 100644 --- a/testing-modules/junit-5/pom.xml +++ b/testing-modules/junit-5/pom.xml @@ -32,12 +32,6 @@ junit-platform-engine ${junit-platform.version} - - org.junit.platform - junit-platform-runner - ${junit-platform.version} - test - org.junit.platform junit-platform-console-standalone diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java index e13b4e24be..6aa3dd4a7f 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java @@ -3,14 +3,15 @@ package com.baeldung.junit5.mockito; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; @@ -25,7 +26,6 @@ import com.baeldung.junit5.mockito.service.Errors; import com.baeldung.junit5.mockito.service.UserService; @ExtendWith(MockitoExtension.class) -@RunWith(JUnitPlatform.class) public class UserServiceUnitTest { UserService userService; diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorUnitTest.java index 3db44c9d63..ce9b188afa 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorUnitTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorUnitTest.java @@ -8,10 +8,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; -@RunWith(JUnitPlatform.class) @DisplayName("Testing PersonValidator") public class PersonValidatorUnitTest { diff --git a/testing-modules/junit5-migration/pom.xml b/testing-modules/junit5-migration/pom.xml index 3ea035c4f9..3720c1dc4a 100644 --- a/testing-modules/junit5-migration/pom.xml +++ b/testing-modules/junit5-migration/pom.xml @@ -22,7 +22,7 @@ org.junit.platform - junit-platform-runner + junit-platform-suite ${junit-platform.version} test diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/AnnotationTestExampleUnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/AnnotationTestExampleUnitTest.java index 16de0be9d8..52d8f8f60a 100644 --- a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/AnnotationTestExampleUnitTest.java +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/AnnotationTestExampleUnitTest.java @@ -1,17 +1,14 @@ package com.baeldung.junit5; +import java.time.Duration; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; - -import java.time.Duration; @Tag("annotations") @Tag("junit5") -@RunWith(JUnitPlatform.class) public class AnnotationTestExampleUnitTest { @Test public void shouldRaiseAnException() throws Exception { diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/RuleExampleUnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/RuleExampleUnitTest.java index 297d0f1730..df509f561a 100644 --- a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/RuleExampleUnitTest.java +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/RuleExampleUnitTest.java @@ -2,10 +2,7 @@ package com.baeldung.junit5; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; -@RunWith(JUnitPlatform.class) @ExtendWith(TraceUnitExtension.class) public class RuleExampleUnitTest { diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5vstestng/SelectClassesSuiteUnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5vstestng/SelectClassesSuiteUnitTest.java index 7b4bd746bf..f307a75274 100644 --- a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5vstestng/SelectClassesSuiteUnitTest.java +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5vstestng/SelectClassesSuiteUnitTest.java @@ -1,10 +1,9 @@ package com.baeldung.junit5vstestng; -import org.junit.platform.runner.JUnitPlatform; import org.junit.platform.suite.api.SelectClasses; -import org.junit.runner.RunWith; +import org.junit.platform.suite.api.Suite; -@RunWith(JUnitPlatform.class) +@Suite @SelectClasses({Class1UnitTest.class, Class2UnitTest.class}) public class SelectClassesSuiteUnitTest { diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5vstestng/SelectPackagesSuiteUnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5vstestng/SelectPackagesSuiteUnitTest.java index 7378eafaa7..ef8756a2bb 100644 --- a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5vstestng/SelectPackagesSuiteUnitTest.java +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5vstestng/SelectPackagesSuiteUnitTest.java @@ -1,10 +1,9 @@ package com.baeldung.junit5vstestng; -import org.junit.platform.runner.JUnitPlatform; import org.junit.platform.suite.api.SelectPackages; -import org.junit.runner.RunWith; +import org.junit.platform.suite.api.Suite; -@RunWith(JUnitPlatform.class) +@Suite @SelectPackages({ "com.baeldung.java.suite.childpackage1", "com.baeldung.java.suite.childpackage2" }) public class SelectPackagesSuiteUnitTest { diff --git a/testing-modules/testng-command-line/pom.xml b/testing-modules/testng-command-line/pom.xml index efc49b187d..a71238f4fb 100644 --- a/testing-modules/testng-command-line/pom.xml +++ b/testing-modules/testng-command-line/pom.xml @@ -78,7 +78,6 @@ - ExecuteTestSuite @@ -101,6 +100,7 @@ + UTF-8 1.8 @@ -112,4 +112,5 @@ 3.8.0 2.22.1 - + + \ No newline at end of file