From 96fb3150e7058db82d03208e05b930d1474bfd1d Mon Sep 17 00:00:00 2001 From: Muhammad Abdullah Azam Khan Date: Thu, 14 Oct 2021 01:15:13 +0400 Subject: [PATCH 01/65] 415 Unsupported Media Type 1. Basic user controller added 2. POST API explains the how to support differnet content-type formats --- .../UnsupportedMediaTypeApplication.java | 13 ++++ .../baeldung/unsupportedmediatype/User.java | 61 +++++++++++++++++++ .../unsupportedmediatype/UserController.java | 29 +++++++++ 3 files changed, 103 insertions(+) create mode 100644 spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UnsupportedMediaTypeApplication.java create mode 100644 spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java create mode 100644 spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UserController.java diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UnsupportedMediaTypeApplication.java b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UnsupportedMediaTypeApplication.java new file mode 100644 index 0000000000..ccc136ef86 --- /dev/null +++ b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UnsupportedMediaTypeApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.unsupportedmediatype; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class UnsupportedMediaTypeApplication { + + public static void main(String[] args) { + SpringApplication.run(UnsupportedMediaTypeApplication.class, args); + } + +} diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java new file mode 100644 index 0000000000..74a6f4383b --- /dev/null +++ b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java @@ -0,0 +1,61 @@ +package com.baeldung.unsupportedmediatype; + +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +@XmlRootElement +public class User implements Serializable { + private Integer id; + private String name; + private Integer age; + private String address; + + public User(Integer id, String name, Integer age, String address){ + this.id = id; + this.name = name; + this.age = age; + this.address = address; + } + + 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 Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + @Override + public String toString() { + return "User{" + + "id=" + id + + ", name='" + name + '\'' + + ", age=" + age + + ", address='" + address + '\'' + + '}'; + } +} diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UserController.java b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UserController.java new file mode 100644 index 0000000000..a20043619a --- /dev/null +++ b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UserController.java @@ -0,0 +1,29 @@ +package com.baeldung.unsupportedmediatype; + +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.*; + +import java.util.Collections; +import java.util.List; + +@RestController +@RequestMapping("/user") +public class UserController { + + @GetMapping(value = "/") + List getAllUsers(){ + return Collections.singletonList(new User(1, "Andy", 28, "14th Street")); + } + + @GetMapping(value = "/{user-id}") + User getUser(@PathVariable("user-id") Integer userId){ + return new User(userId, "Andy", 28, "14th Street"); + } + + @PostMapping(value = "/", consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) + void AddUser(@RequestBody User user){ + // Adding the User in the repository + } + + +} \ No newline at end of file From 40cbd480064d16f10ce48eef1701dd989b82e95f Mon Sep 17 00:00:00 2001 From: Muhammad Abdullah Azam Khan Date: Sun, 17 Oct 2021 00:24:08 +0400 Subject: [PATCH 02/65] Test case for unsupported media type error --- .../unsupportedmedia/ApplicationTest.java | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmedia/ApplicationTest.java diff --git a/spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmedia/ApplicationTest.java b/spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmedia/ApplicationTest.java new file mode 100644 index 0000000000..e5c56d0adc --- /dev/null +++ b/spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmedia/ApplicationTest.java @@ -0,0 +1,59 @@ +package com.baeldung.unsupportedmedia; + +import com.baeldung.unsupportedmediatype.UserController; +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.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@WebMvcTest(UserController.class) +public class ApplicationTest { + @Autowired + private MockMvc mockMvc; + + @Test + void JsonTestCase() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.post("/user/") + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content("{\n" + + " \"name\": \"Andy\",\n" + + " \"age\": 1,\n" + + " \"address\": \"Hello world\"\n" + + "}")) + .andExpect(status().isOk()); + } + + @Test + void JsonFailTestCase() throws Exception {// Because no content-type added + mockMvc.perform(MockMvcRequestBuilders.post("/user/") + .content("{\n" + + " \"name\": \"Andy\",\n" + + " \"age\": 1,\n" + + " \"address\": \"Hello world\"\n" + + "}")) + .andExpect(status().isUnsupportedMediaType()); + } + + @Test + void XmlTestCase() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.post("/user/") + .contentType(MediaType.APPLICATION_XML_VALUE) + .content("Andy1
Hello world
")) + .andExpect(status().isOk()); + } + + @Test + void StringTestCase() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.post("/user/") + .contentType(MediaType.TEXT_PLAIN_VALUE) + .content("Andy1
Hello world
")) + .andExpect(status().isUnsupportedMediaType()); + } +} From 1c07cac355bc4f944a600f8ea3569d21efaa7988 Mon Sep 17 00:00:00 2001 From: Muhammad Abdullah Azam Khan Date: Sun, 17 Oct 2021 00:52:40 +0400 Subject: [PATCH 03/65] Resolving build failure cases --- .../com/baeldung/unsupportedmediatype/User.java | 4 ++++ .../ApplicationUnitTest.java} | 15 +++++++-------- 2 files changed, 11 insertions(+), 8 deletions(-) rename spring-boot-rest-2/src/test/java/com/baeldung/{unsupportedmedia/ApplicationTest.java => unsupportedmediatype/ApplicationUnitTest.java} (84%) diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java index 74a6f4383b..5f5f2a972c 100644 --- a/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java +++ b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java @@ -10,6 +10,10 @@ public class User implements Serializable { private Integer age; private String address; + public User(){ + + } + public User(Integer id, String name, Integer age, String address){ this.id = id; this.name = name; diff --git a/spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmedia/ApplicationTest.java b/spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java similarity index 84% rename from spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmedia/ApplicationTest.java rename to spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java index e5c56d0adc..a84388f750 100644 --- a/spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmedia/ApplicationTest.java +++ b/spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java @@ -1,7 +1,6 @@ -package com.baeldung.unsupportedmedia; +package com.baeldung.unsupportedmediatype; -import com.baeldung.unsupportedmediatype.UserController; -import org.junit.jupiter.api.Test; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; @@ -14,12 +13,12 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @WebMvcTest(UserController.class) -public class ApplicationTest { +public class ApplicationUnitTest { @Autowired private MockMvc mockMvc; @Test - void JsonTestCase() throws Exception { + public void JsonTestCase() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/user/") .contentType(MediaType.APPLICATION_JSON_VALUE) .content("{\n" + @@ -31,7 +30,7 @@ public class ApplicationTest { } @Test - void JsonFailTestCase() throws Exception {// Because no content-type added + public void JsonFailTestCase() throws Exception {// Because no content-type added mockMvc.perform(MockMvcRequestBuilders.post("/user/") .content("{\n" + " \"name\": \"Andy\",\n" + @@ -42,7 +41,7 @@ public class ApplicationTest { } @Test - void XmlTestCase() throws Exception { + public void XmlTestCase() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/user/") .contentType(MediaType.APPLICATION_XML_VALUE) .content("Andy1
Hello world
")) @@ -50,7 +49,7 @@ public class ApplicationTest { } @Test - void StringTestCase() throws Exception { + public void StringFailTestCase() throws Exception { // Because content-type is not supported mockMvc.perform(MockMvcRequestBuilders.post("/user/") .contentType(MediaType.TEXT_PLAIN_VALUE) .content("Andy1
Hello world
")) From de03c31939f8a9d22d2387ad004efc36e6f49e3a Mon Sep 17 00:00:00 2001 From: Ralf Ueberfuhr Date: Wed, 20 Oct 2021 14:14:40 +0200 Subject: [PATCH 04/65] BAEL-5036: Add Quarkus Hello App that uses several external modules that contain CDI managed beans. Each module is indexed using a different kind of registration. --- pom.xml | 2 + quarkus-jandex/README.md | 3 + quarkus-jandex/hello-app/.dockerignore | 5 + quarkus-jandex/hello-app/.gitignore | 39 +++ .../.mvn/wrapper/MavenWrapperDownloader.java | 114 +++++++ .../.mvn/wrapper/maven-wrapper.properties | 2 + quarkus-jandex/hello-app/README.md | 51 +++ quarkus-jandex/hello-app/mvnw | 310 ++++++++++++++++++ quarkus-jandex/hello-app/mvnw.cmd | 182 ++++++++++ quarkus-jandex/hello-app/pom.xml | 131 ++++++++ .../hello-app/src/main/docker/Dockerfile.jvm | 55 ++++ .../src/main/docker/Dockerfile.legacy-jar | 51 +++ .../src/main/docker/Dockerfile.native | 27 ++ .../main/docker/Dockerfile.native-distroless | 23 ++ .../baeldung/quarkus/hello/HelloResource.java | 26 ++ .../resources/META-INF/resources/index.html | 14 + .../src/main/resources/application.properties | 2 + .../pom.xml | 26 ++ .../ApplicationPropertiesHelloSender.java | 15 + quarkus-jandex/hello-sender-beans-xml/pom.xml | 26 ++ .../sender/beansxml/BeansXmlHelloSender.java | 15 + .../src/main/resources/META-INF/beans.xml | 0 .../hello-sender-maven-plugin/pom.xml | 46 +++ .../mavenplugin/MavenPluginHelloSender.java | 15 + .../hello-sender-undetected/pom.xml | 26 ++ .../undetected/UndetectedHelloSender.java | 15 + quarkus-jandex/hello-service/pom.xml | 21 ++ .../hello/service/HelloRetrieving.java | 17 + .../quarkus/hello/service/HelloService.java | 18 + .../src/main/resources/META-INF/beans.xml | 0 quarkus-jandex/pom.xml | 42 +++ 31 files changed, 1319 insertions(+) create mode 100644 quarkus-jandex/README.md create mode 100644 quarkus-jandex/hello-app/.dockerignore create mode 100644 quarkus-jandex/hello-app/.gitignore create mode 100644 quarkus-jandex/hello-app/.mvn/wrapper/MavenWrapperDownloader.java create mode 100644 quarkus-jandex/hello-app/.mvn/wrapper/maven-wrapper.properties create mode 100644 quarkus-jandex/hello-app/README.md create mode 100644 quarkus-jandex/hello-app/mvnw create mode 100644 quarkus-jandex/hello-app/mvnw.cmd create mode 100644 quarkus-jandex/hello-app/pom.xml create mode 100644 quarkus-jandex/hello-app/src/main/docker/Dockerfile.jvm create mode 100644 quarkus-jandex/hello-app/src/main/docker/Dockerfile.legacy-jar create mode 100644 quarkus-jandex/hello-app/src/main/docker/Dockerfile.native create mode 100644 quarkus-jandex/hello-app/src/main/docker/Dockerfile.native-distroless create mode 100644 quarkus-jandex/hello-app/src/main/java/com/baeldung/quarkus/hello/HelloResource.java create mode 100644 quarkus-jandex/hello-app/src/main/resources/META-INF/resources/index.html create mode 100644 quarkus-jandex/hello-app/src/main/resources/application.properties create mode 100644 quarkus-jandex/hello-sender-application-properties/pom.xml create mode 100644 quarkus-jandex/hello-sender-application-properties/src/main/java/com/baeldung/quarkus/hello/sender/applicationproperties/ApplicationPropertiesHelloSender.java create mode 100644 quarkus-jandex/hello-sender-beans-xml/pom.xml create mode 100644 quarkus-jandex/hello-sender-beans-xml/src/main/java/com/baeldung/quarkus/hello/sender/beansxml/BeansXmlHelloSender.java create mode 100644 quarkus-jandex/hello-sender-beans-xml/src/main/resources/META-INF/beans.xml create mode 100644 quarkus-jandex/hello-sender-maven-plugin/pom.xml create mode 100644 quarkus-jandex/hello-sender-maven-plugin/src/main/java/com/baeldung/quarkus/hello/sender/mavenplugin/MavenPluginHelloSender.java create mode 100644 quarkus-jandex/hello-sender-undetected/pom.xml create mode 100644 quarkus-jandex/hello-sender-undetected/src/main/java/com/baeldung/quarkus/hello/sender/undetected/UndetectedHelloSender.java create mode 100644 quarkus-jandex/hello-service/pom.xml create mode 100644 quarkus-jandex/hello-service/src/main/java/com/baeldung/quarkus/hello/service/HelloRetrieving.java create mode 100644 quarkus-jandex/hello-service/src/main/java/com/baeldung/quarkus/hello/service/HelloService.java create mode 100644 quarkus-jandex/hello-service/src/main/resources/META-INF/beans.xml create mode 100644 quarkus-jandex/pom.xml diff --git a/pom.xml b/pom.xml index 1e26d09906..f51491137e 100644 --- a/pom.xml +++ b/pom.xml @@ -534,6 +534,7 @@ quarkus quarkus-extension + quarkus-jandex rabbitmq @@ -1004,6 +1005,7 @@ quarkus quarkus-extension + quarkus-jandex rabbitmq diff --git a/quarkus-jandex/README.md b/quarkus-jandex/README.md new file mode 100644 index 0000000000..a03cdc708f --- /dev/null +++ b/quarkus-jandex/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Create a Jandex index in Quarkus for classes in a external module](https://www.baeldung.com/quarkus-jandex) diff --git a/quarkus-jandex/hello-app/.dockerignore b/quarkus-jandex/hello-app/.dockerignore new file mode 100644 index 0000000000..94810d006e --- /dev/null +++ b/quarkus-jandex/hello-app/.dockerignore @@ -0,0 +1,5 @@ +* +!target/*-runner +!target/*-runner.jar +!target/lib/* +!target/quarkus-app/* \ No newline at end of file diff --git a/quarkus-jandex/hello-app/.gitignore b/quarkus-jandex/hello-app/.gitignore new file mode 100644 index 0000000000..bdf57ce3b4 --- /dev/null +++ b/quarkus-jandex/hello-app/.gitignore @@ -0,0 +1,39 @@ +#Maven +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +release.properties + +# Eclipse +.project +.classpath +.settings/ +bin/ + +# IntelliJ +.idea +*.ipr +*.iml +*.iws + +# NetBeans +nb-configuration.xml + +# Visual Studio Code +.vscode +.factorypath + +# OSX +.DS_Store + +# Vim +*.swp +*.swo + +# patch +*.orig +*.rej + +# Local environment +.env diff --git a/quarkus-jandex/hello-app/.mvn/wrapper/MavenWrapperDownloader.java b/quarkus-jandex/hello-app/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000000..c39041cdf6 --- /dev/null +++ b/quarkus-jandex/hello-app/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,114 @@ +/* + * 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 + * + * 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. + */ + +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/quarkus-jandex/hello-app/.mvn/wrapper/maven-wrapper.properties b/quarkus-jandex/hello-app/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..ffdc10e59f --- /dev/null +++ b/quarkus-jandex/hello-app/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.1/apache-maven-3.8.1-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/quarkus-jandex/hello-app/README.md b/quarkus-jandex/hello-app/README.md new file mode 100644 index 0000000000..769709eb00 --- /dev/null +++ b/quarkus-jandex/hello-app/README.md @@ -0,0 +1,51 @@ +# Hello App with Quarkus + +## Running the application in dev mode + +You can run your application in dev mode that enables live coding using: + +```shell script +./mvnw compile quarkus:dev +``` + +You can then find the app using `http://localhost:8080`. + +> **_NOTE:_** Quarkus now ships with a Dev UI, which is available in dev mode only at http://localhost:8080/q/dev/. + +## Packaging and running the application + +The application can be packaged using: + +```shell script +./mvnw package +``` + +It produces the `quarkus-run.jar` file in the `target/quarkus-app/` directory. Be aware that it’s not an _über-jar_ as the dependencies are copied into the `target/quarkus-app/lib/` directory. + +The application is now runnable using `java -jar target/quarkus-app/quarkus-run.jar`. + +If you want to build an _über-jar_, execute the following command: + +```shell script +./mvnw package -Dquarkus.package.type=uber-jar +``` + +The application, packaged as an _über-jar_, is now runnable using `java -jar target/*-runner.jar`. + +## Creating a native executable + +You can create a native executable using: + +```shell script +./mvnw package -Pnative +``` + +Or, if you don't have GraalVM installed, you can run the native executable build in a container using: + +```shell script +./mvnw package -Pnative -Dquarkus.native.container-build=true +``` + +You can then execute your native executable with: `./target/quarkus-sample-1.0-SNAPSHOT-runner` + +If you want to learn more about building native executables, please consult https://quarkus.io/guides/maven-tooling.html. diff --git a/quarkus-jandex/hello-app/mvnw b/quarkus-jandex/hello-app/mvnw new file mode 100644 index 0000000000..a16b5431b4 --- /dev/null +++ b/quarkus-jandex/hello-app/mvnw @@ -0,0 +1,310 @@ +#!/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/quarkus-jandex/hello-app/mvnw.cmd b/quarkus-jandex/hello-app/mvnw.cmd new file mode 100644 index 0000000000..c8d43372c9 --- /dev/null +++ b/quarkus-jandex/hello-app/mvnw.cmd @@ -0,0 +1,182 @@ +@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/quarkus-jandex/hello-app/pom.xml b/quarkus-jandex/hello-app/pom.xml new file mode 100644 index 0000000000..8da874a1c7 --- /dev/null +++ b/quarkus-jandex/hello-app/pom.xml @@ -0,0 +1,131 @@ + + + 4.0.0 + + + com.baeldung.quarkus + quarkus-jandex + 1.0.0-SNAPSHOT + + + hello-app + + + + io.quarkus + quarkus-resteasy + + + io.quarkus + quarkus-arc + + + io.quarkus + quarkus-junit5 + test + + + io.rest-assured + rest-assured + test + + + ${project.groupId} + hello-service + ${project.version} + + + ${project.groupId} + hello-sender-beans-xml + ${project.version} + + + ${project.groupId} + hello-sender-maven-plugin + ${project.version} + + + ${project.groupId} + hello-sender-application-properties + ${project.version} + + + ${project.groupId} + hello-sender-undetected + ${project.version} + + + + + + ${quarkus.platform.group-id} + quarkus-maven-plugin + ${quarkus.platform.version} + true + + + + build + generate-code + generate-code-tests + + + + + + maven-compiler-plugin + ${compiler-plugin.version} + + ${maven.compiler.parameters} + + + + maven-surefire-plugin + ${surefire-plugin.version} + + + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + + native + + + native + + + + + + maven-failsafe-plugin + ${surefire-plugin.version} + + + + integration-test + verify + + + + ${project.build.directory}/${project.build.finalName}-runner + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + + + native + + + + diff --git a/quarkus-jandex/hello-app/src/main/docker/Dockerfile.jvm b/quarkus-jandex/hello-app/src/main/docker/Dockerfile.jvm new file mode 100644 index 0000000000..3eb1b4de84 --- /dev/null +++ b/quarkus-jandex/hello-app/src/main/docker/Dockerfile.jvm @@ -0,0 +1,55 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode +# +# Before building the container image run: +# +# ./mvnw package +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.jvm -t quarkus/quarkus-sample-jvm . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus-sample-jvm +# +# If you want to include the debug port into your docker image +# you will have to expose the debug port (default 5005) like this : EXPOSE 8080 5005 +# +# Then run the container using : +# +# docker run -i --rm -p 8080:8080 -p 5005:5005 -e JAVA_ENABLE_DEBUG="true" quarkus/quarkus-sample-jvm +# +### +FROM registry.access.redhat.com/ubi8/ubi-minimal:8.4 + +ARG JAVA_PACKAGE=java-11-openjdk-headless +ARG RUN_JAVA_VERSION=1.3.8 +ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' +# Install java and the run-java script +# Also set up permissions for user `1001` +RUN microdnf install curl ca-certificates ${JAVA_PACKAGE} \ + && microdnf update \ + && microdnf clean all \ + && mkdir /deployments \ + && chown 1001 /deployments \ + && chmod "g+rwX" /deployments \ + && chown 1001:root /deployments \ + && curl https://repo1.maven.org/maven2/io/fabric8/run-java-sh/${RUN_JAVA_VERSION}/run-java-sh-${RUN_JAVA_VERSION}-sh.sh -o /deployments/run-java.sh \ + && chown 1001 /deployments/run-java.sh \ + && chmod 540 /deployments/run-java.sh \ + && echo "securerandom.source=file:/dev/urandom" >> /etc/alternatives/jre/conf/security/java.security + +# Configure the JAVA_OPTIONS, you can add -XshowSettings:vm to also display the heap size. +ENV JAVA_OPTIONS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" +# We make four distinct layers so if there are application changes the library layers can be re-used +COPY --chown=1001 target/quarkus-app/lib/ /deployments/lib/ +COPY --chown=1001 target/quarkus-app/*.jar /deployments/ +COPY --chown=1001 target/quarkus-app/app/ /deployments/app/ +COPY --chown=1001 target/quarkus-app/quarkus/ /deployments/quarkus/ + +EXPOSE 8080 +USER 1001 + +ENTRYPOINT [ "/deployments/run-java.sh" ] + diff --git a/quarkus-jandex/hello-app/src/main/docker/Dockerfile.legacy-jar b/quarkus-jandex/hello-app/src/main/docker/Dockerfile.legacy-jar new file mode 100644 index 0000000000..f32188a45d --- /dev/null +++ b/quarkus-jandex/hello-app/src/main/docker/Dockerfile.legacy-jar @@ -0,0 +1,51 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode +# +# Before building the container image run: +# +# ./mvnw package -Dquarkus.package.type=legacy-jar +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.legacy-jar -t quarkus/quarkus-sample-legacy-jar . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus-sample-legacy-jar +# +# If you want to include the debug port into your docker image +# you will have to expose the debug port (default 5005) like this : EXPOSE 8080 5005 +# +# Then run the container using : +# +# docker run -i --rm -p 8080:8080 -p 5005:5005 -e JAVA_ENABLE_DEBUG="true" quarkus/quarkus-sample-legacy-jar +# +### +FROM registry.access.redhat.com/ubi8/ubi-minimal:8.4 + +ARG JAVA_PACKAGE=java-11-openjdk-headless +ARG RUN_JAVA_VERSION=1.3.8 +ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' +# Install java and the run-java script +# Also set up permissions for user `1001` +RUN microdnf install curl ca-certificates ${JAVA_PACKAGE} \ + && microdnf update \ + && microdnf clean all \ + && mkdir /deployments \ + && chown 1001 /deployments \ + && chmod "g+rwX" /deployments \ + && chown 1001:root /deployments \ + && curl https://repo1.maven.org/maven2/io/fabric8/run-java-sh/${RUN_JAVA_VERSION}/run-java-sh-${RUN_JAVA_VERSION}-sh.sh -o /deployments/run-java.sh \ + && chown 1001 /deployments/run-java.sh \ + && chmod 540 /deployments/run-java.sh \ + && echo "securerandom.source=file:/dev/urandom" >> /etc/alternatives/jre/conf/security/java.security + +# Configure the JAVA_OPTIONS, you can add -XshowSettings:vm to also display the heap size. +ENV JAVA_OPTIONS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" +COPY target/lib/* /deployments/lib/ +COPY target/*-runner.jar /deployments/app.jar + +EXPOSE 8080 +USER 1001 + +ENTRYPOINT [ "/deployments/run-java.sh" ] diff --git a/quarkus-jandex/hello-app/src/main/docker/Dockerfile.native b/quarkus-jandex/hello-app/src/main/docker/Dockerfile.native new file mode 100644 index 0000000000..4fa16507fe --- /dev/null +++ b/quarkus-jandex/hello-app/src/main/docker/Dockerfile.native @@ -0,0 +1,27 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode +# +# Before building the container image run: +# +# ./mvnw package -Pnative +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.native -t quarkus/quarkus-sample . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus-sample +# +### +FROM registry.access.redhat.com/ubi8/ubi-minimal:8.4 +WORKDIR /work/ +RUN chown 1001 /work \ + && chmod "g+rwX" /work \ + && chown 1001:root /work +COPY --chown=1001:root target/*-runner /work/application + +EXPOSE 8080 +USER 1001 + +CMD ["./application", "-Dquarkus.http.host=0.0.0.0"] diff --git a/quarkus-jandex/hello-app/src/main/docker/Dockerfile.native-distroless b/quarkus-jandex/hello-app/src/main/docker/Dockerfile.native-distroless new file mode 100644 index 0000000000..86370b0a0b --- /dev/null +++ b/quarkus-jandex/hello-app/src/main/docker/Dockerfile.native-distroless @@ -0,0 +1,23 @@ +#### +# This Dockerfile is used in order to build a distroless container that runs the Quarkus application in native (no JVM) mode +# +# Before building the container image run: +# +# ./mvnw package -Pnative +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.native-distroless -t quarkus/quarkus-sample . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus-sample +# +### +FROM quay.io/quarkus/quarkus-distroless-image:1.0 +COPY target/*-runner /application + +EXPOSE 8080 +USER nonroot + +CMD ["./application", "-Dquarkus.http.host=0.0.0.0"] diff --git a/quarkus-jandex/hello-app/src/main/java/com/baeldung/quarkus/hello/HelloResource.java b/quarkus-jandex/hello-app/src/main/java/com/baeldung/quarkus/hello/HelloResource.java new file mode 100644 index 0000000000..1867527327 --- /dev/null +++ b/quarkus-jandex/hello-app/src/main/java/com/baeldung/quarkus/hello/HelloResource.java @@ -0,0 +1,26 @@ +package com.baeldung.quarkus.hello; + +import com.baeldung.quarkus.hello.service.HelloService; + +import javax.inject.Inject; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +@Path("/hello") +public class HelloResource { + + @Inject + HelloService service; + + @GET + @Produces(MediaType.TEXT_PLAIN) + public String hello() { + StringBuilder sb = new StringBuilder(); + sb.append("Those are saying hello:\n=======================\n\n"); + service.sendHello(s -> sb.append(" - ").append(s).append("\n")); + return sb.toString(); + } + +} diff --git a/quarkus-jandex/hello-app/src/main/resources/META-INF/resources/index.html b/quarkus-jandex/hello-app/src/main/resources/META-INF/resources/index.html new file mode 100644 index 0000000000..ba625a1420 --- /dev/null +++ b/quarkus-jandex/hello-app/src/main/resources/META-INF/resources/index.html @@ -0,0 +1,14 @@ + + + + + qHello App + + + +

Hello App

+ +This app demonstrates how Quarkus resolves CDI managed beans. You can find the output of all resolved beans by invoking the Hello Resource. + + + diff --git a/quarkus-jandex/hello-app/src/main/resources/application.properties b/quarkus-jandex/hello-app/src/main/resources/application.properties new file mode 100644 index 0000000000..95ff9889c7 --- /dev/null +++ b/quarkus-jandex/hello-app/src/main/resources/application.properties @@ -0,0 +1,2 @@ +quarkus.index-dependency.hello-sender.group-id=com.baeldung.quarkus +quarkus.index-dependency.hello-sender.artifact-id=hello-sender-application-properties diff --git a/quarkus-jandex/hello-sender-application-properties/pom.xml b/quarkus-jandex/hello-sender-application-properties/pom.xml new file mode 100644 index 0000000000..01784b44f4 --- /dev/null +++ b/quarkus-jandex/hello-sender-application-properties/pom.xml @@ -0,0 +1,26 @@ + + + + com.baeldung.quarkus + quarkus-jandex + 1.0.0-SNAPSHOT + + 4.0.0 + + hello-sender-application-properties + + + + io.quarkus + quarkus-arc + + + ${project.groupId} + hello-service + ${project.version} + + + + diff --git a/quarkus-jandex/hello-sender-application-properties/src/main/java/com/baeldung/quarkus/hello/sender/applicationproperties/ApplicationPropertiesHelloSender.java b/quarkus-jandex/hello-sender-application-properties/src/main/java/com/baeldung/quarkus/hello/sender/applicationproperties/ApplicationPropertiesHelloSender.java new file mode 100644 index 0000000000..ffd495e92e --- /dev/null +++ b/quarkus-jandex/hello-sender-application-properties/src/main/java/com/baeldung/quarkus/hello/sender/applicationproperties/ApplicationPropertiesHelloSender.java @@ -0,0 +1,15 @@ +package com.baeldung.quarkus.hello.sender.applicationproperties; + +import com.baeldung.quarkus.hello.service.HelloRetrieving; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.event.Observes; + +@ApplicationScoped +public class ApplicationPropertiesHelloSender { + + public void sendHello(@Observes HelloRetrieving event) { + event.getHelloReceiver().accept("Hi, I was detected by inserting this module's groupId and artifactId into the app's application.properties file."); + } + +} diff --git a/quarkus-jandex/hello-sender-beans-xml/pom.xml b/quarkus-jandex/hello-sender-beans-xml/pom.xml new file mode 100644 index 0000000000..30cabcc91d --- /dev/null +++ b/quarkus-jandex/hello-sender-beans-xml/pom.xml @@ -0,0 +1,26 @@ + + + + com.baeldung.quarkus + quarkus-jandex + 1.0.0-SNAPSHOT + + 4.0.0 + + hello-sender-beans-xml + + + + io.quarkus + quarkus-arc + + + ${project.groupId} + hello-service + ${project.version} + + + + diff --git a/quarkus-jandex/hello-sender-beans-xml/src/main/java/com/baeldung/quarkus/hello/sender/beansxml/BeansXmlHelloSender.java b/quarkus-jandex/hello-sender-beans-xml/src/main/java/com/baeldung/quarkus/hello/sender/beansxml/BeansXmlHelloSender.java new file mode 100644 index 0000000000..bed6a7793d --- /dev/null +++ b/quarkus-jandex/hello-sender-beans-xml/src/main/java/com/baeldung/quarkus/hello/sender/beansxml/BeansXmlHelloSender.java @@ -0,0 +1,15 @@ +package com.baeldung.quarkus.hello.sender.beansxml; + +import com.baeldung.quarkus.hello.service.HelloRetrieving; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.event.Observes; + +@ApplicationScoped +public class BeansXmlHelloSender { + + public void sendHello(@Observes HelloRetrieving event) { + event.getHelloReceiver().accept("Hi, I was detected using an empty META-INF/beans.xml file."); + } + +} diff --git a/quarkus-jandex/hello-sender-beans-xml/src/main/resources/META-INF/beans.xml b/quarkus-jandex/hello-sender-beans-xml/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..e69de29bb2 diff --git a/quarkus-jandex/hello-sender-maven-plugin/pom.xml b/quarkus-jandex/hello-sender-maven-plugin/pom.xml new file mode 100644 index 0000000000..ad226f38dd --- /dev/null +++ b/quarkus-jandex/hello-sender-maven-plugin/pom.xml @@ -0,0 +1,46 @@ + + + + com.baeldung.quarkus + quarkus-jandex + 1.0.0-SNAPSHOT + + 4.0.0 + + hello-sender-maven-plugin + + + + io.quarkus + quarkus-arc + + + ${project.groupId} + hello-service + ${project.version} + + + + + + + + org.jboss.jandex + jandex-maven-plugin + 1.2.1 + + + make-index + + + jandex + + + + + + + + diff --git a/quarkus-jandex/hello-sender-maven-plugin/src/main/java/com/baeldung/quarkus/hello/sender/mavenplugin/MavenPluginHelloSender.java b/quarkus-jandex/hello-sender-maven-plugin/src/main/java/com/baeldung/quarkus/hello/sender/mavenplugin/MavenPluginHelloSender.java new file mode 100644 index 0000000000..ca08eef5ac --- /dev/null +++ b/quarkus-jandex/hello-sender-maven-plugin/src/main/java/com/baeldung/quarkus/hello/sender/mavenplugin/MavenPluginHelloSender.java @@ -0,0 +1,15 @@ +package com.baeldung.quarkus.hello.sender.mavenplugin; + +import com.baeldung.quarkus.hello.service.HelloRetrieving; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.event.Observes; + +@ApplicationScoped +public class MavenPluginHelloSender { + + public void sendHello(@Observes HelloRetrieving event) { + event.getHelloReceiver().accept("Hi, I was detected using the Jandex Maven Plugin."); + } + +} diff --git a/quarkus-jandex/hello-sender-undetected/pom.xml b/quarkus-jandex/hello-sender-undetected/pom.xml new file mode 100644 index 0000000000..0d8cb29a98 --- /dev/null +++ b/quarkus-jandex/hello-sender-undetected/pom.xml @@ -0,0 +1,26 @@ + + + + com.baeldung.quarkus + quarkus-jandex + 1.0.0-SNAPSHOT + + 4.0.0 + + hello-sender-undetected + + + + io.quarkus + quarkus-arc + + + ${project.groupId} + hello-service + ${project.version} + + + + diff --git a/quarkus-jandex/hello-sender-undetected/src/main/java/com/baeldung/quarkus/hello/sender/undetected/UndetectedHelloSender.java b/quarkus-jandex/hello-sender-undetected/src/main/java/com/baeldung/quarkus/hello/sender/undetected/UndetectedHelloSender.java new file mode 100644 index 0000000000..a39e610b2a --- /dev/null +++ b/quarkus-jandex/hello-sender-undetected/src/main/java/com/baeldung/quarkus/hello/sender/undetected/UndetectedHelloSender.java @@ -0,0 +1,15 @@ +package com.baeldung.quarkus.hello.sender.undetected; + +import com.baeldung.quarkus.hello.service.HelloRetrieving; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.event.Observes; + +@ApplicationScoped +public class UndetectedHelloSender { + + public void sendHello(@Observes HelloRetrieving event) { + event.getHelloReceiver().accept("Hi, I do not create a Jandex index, so I should not get detected."); + } + +} diff --git a/quarkus-jandex/hello-service/pom.xml b/quarkus-jandex/hello-service/pom.xml new file mode 100644 index 0000000000..274423c526 --- /dev/null +++ b/quarkus-jandex/hello-service/pom.xml @@ -0,0 +1,21 @@ + + + + com.baeldung.quarkus + quarkus-jandex + 1.0.0-SNAPSHOT + + 4.0.0 + + hello-service + + + + io.quarkus + quarkus-arc + + + + diff --git a/quarkus-jandex/hello-service/src/main/java/com/baeldung/quarkus/hello/service/HelloRetrieving.java b/quarkus-jandex/hello-service/src/main/java/com/baeldung/quarkus/hello/service/HelloRetrieving.java new file mode 100644 index 0000000000..513e2ff245 --- /dev/null +++ b/quarkus-jandex/hello-service/src/main/java/com/baeldung/quarkus/hello/service/HelloRetrieving.java @@ -0,0 +1,17 @@ +package com.baeldung.quarkus.hello.service; + +import java.util.function.Consumer; + +public class HelloRetrieving { + + private final Consumer helloReceiver; + + public HelloRetrieving(Consumer helloReceiver) { + this.helloReceiver = helloReceiver; + } + + public Consumer getHelloReceiver() { + return helloReceiver; + } + +} diff --git a/quarkus-jandex/hello-service/src/main/java/com/baeldung/quarkus/hello/service/HelloService.java b/quarkus-jandex/hello-service/src/main/java/com/baeldung/quarkus/hello/service/HelloService.java new file mode 100644 index 0000000000..4b93d2f12f --- /dev/null +++ b/quarkus-jandex/hello-service/src/main/java/com/baeldung/quarkus/hello/service/HelloService.java @@ -0,0 +1,18 @@ +package com.baeldung.quarkus.hello.service; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.event.Event; +import javax.inject.Inject; +import java.util.function.Consumer; + +@ApplicationScoped +public class HelloService { + + @Inject + Event helloRetrievingEvent; + + public void sendHello(Consumer target) { + helloRetrievingEvent.fire(new HelloRetrieving(target)); + } + +} diff --git a/quarkus-jandex/hello-service/src/main/resources/META-INF/beans.xml b/quarkus-jandex/hello-service/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..e69de29bb2 diff --git a/quarkus-jandex/pom.xml b/quarkus-jandex/pom.xml new file mode 100644 index 0000000000..e8e66b44b1 --- /dev/null +++ b/quarkus-jandex/pom.xml @@ -0,0 +1,42 @@ + + + 4.0.0 + com.baeldung.quarkus + quarkus-jandex + 1.0.0-SNAPSHOT + pom + + + hello-service + hello-sender-beans-xml + hello-sender-maven-plugin + hello-sender-application-properties + hello-sender-undetected + hello-app + + + + 3.8.1 + true + 11 + 11 + UTF-8 + UTF-8 + quarkus-bom + io.quarkus.platform + 2.3.0.Final + 3.0.0-M5 + + + + + ${quarkus.platform.group-id} + ${quarkus.platform.artifact-id} + ${quarkus.platform.version} + pom + import + + + + From df4c4a3f8d5a055598a3d1651ca022d8e5c0af4a Mon Sep 17 00:00:00 2001 From: Muhammad Abdullah Azam Khan Date: Fri, 5 Nov 2021 18:32:19 +0400 Subject: [PATCH 05/65] Refactoring for better Indentation and Formatting --- .../UnsupportedMediaTypeApplication.java | 6 ++-- .../baeldung/unsupportedmediatype/User.java | 17 +++++------ .../ApplicationUnitTest.java | 28 +++++++++---------- 3 files changed, 26 insertions(+), 25 deletions(-) diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UnsupportedMediaTypeApplication.java b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UnsupportedMediaTypeApplication.java index ccc136ef86..2bf6bb33cd 100644 --- a/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UnsupportedMediaTypeApplication.java +++ b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UnsupportedMediaTypeApplication.java @@ -6,8 +6,8 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class UnsupportedMediaTypeApplication { - public static void main(String[] args) { - SpringApplication.run(UnsupportedMediaTypeApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(UnsupportedMediaTypeApplication.class, args); + } } diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java index 5f5f2a972c..f9c3d9c191 100644 --- a/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java +++ b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java @@ -11,10 +11,9 @@ public class User implements Serializable { private String address; public User(){ - } - public User(Integer id, String name, Integer age, String address){ + public User(Integer id, String name, Integer age, String address) { this.id = id; this.name = name; this.age = age; @@ -55,11 +54,13 @@ public class User implements Serializable { @Override public String toString() { - return "User{" + - "id=" + id + - ", name='" + name + '\'' + - ", age=" + age + - ", address='" + address + '\'' + - '}'; + return "User{" + + "id=" + id + + ", name='" + name + '\'' + + ", age=" + age + + ", address='" + address + '\'' + + '}'; } + + } diff --git a/spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java b/spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java index a84388f750..95de780106 100644 --- a/spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java +++ b/spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java @@ -21,38 +21,38 @@ public class ApplicationUnitTest { public void JsonTestCase() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/user/") .contentType(MediaType.APPLICATION_JSON_VALUE) - .content("{\n" + - " \"name\": \"Andy\",\n" + - " \"age\": 1,\n" + - " \"address\": \"Hello world\"\n" + - "}")) + .content( "{\n" + + " \"name\": \"Andy\",\n" + + " \"age\": 1,\n" + + " \"address\": \"Hello world\"\n" + + "}")) .andExpect(status().isOk()); } @Test public void JsonFailTestCase() throws Exception {// Because no content-type added mockMvc.perform(MockMvcRequestBuilders.post("/user/") - .content("{\n" + - " \"name\": \"Andy\",\n" + - " \"age\": 1,\n" + - " \"address\": \"Hello world\"\n" + - "}")) + .content( "{\n" + + " \"name\": \"Andy\",\n" + + " \"age\": 1,\n" + + " \"address\": \"Hello world\"\n" + + "}")) .andExpect(status().isUnsupportedMediaType()); } @Test public void XmlTestCase() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/user/") - .contentType(MediaType.APPLICATION_XML_VALUE) - .content("Andy1
Hello world
")) + .contentType(MediaType.APPLICATION_XML_VALUE) + .content("Andy1
Hello world
")) .andExpect(status().isOk()); } @Test public void StringFailTestCase() throws Exception { // Because content-type is not supported mockMvc.perform(MockMvcRequestBuilders.post("/user/") - .contentType(MediaType.TEXT_PLAIN_VALUE) - .content("Andy1
Hello world
")) + .contentType(MediaType.TEXT_PLAIN_VALUE) + .content("Andy1
Hello world
")) .andExpect(status().isUnsupportedMediaType()); } } From 629d093fd48e9657a8165ce0e2ad556a6675f172 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Fri, 19 Nov 2021 23:17:22 +0530 Subject: [PATCH 06/65] JAVA-3592: Upgrade h2 dependency in the main pom.xml --- libraries-data-db/pom.xml | 1 - pom.xml | 2 +- spring-boot-modules/spring-boot-angular/pom.xml | 1 - spring-boot-modules/spring-boot-data/pom.xml | 1 - .../spring-session/spring-session-jdbc/pom.xml | 1 - testing-modules/spring-testing-2/pom.xml | 1 - 6 files changed, 1 insertion(+), 6 deletions(-) diff --git a/libraries-data-db/pom.xml b/libraries-data-db/pom.xml index 20119da8a2..c0f2848705 100644 --- a/libraries-data-db/pom.xml +++ b/libraries-data-db/pom.xml @@ -63,7 +63,6 @@ com.h2database h2 - ${h2.version} diff --git a/pom.xml b/pom.xml index 372bc5a9f3..6b1b29fb8e 100644 --- a/pom.xml +++ b/pom.xml @@ -1428,7 +1428,7 @@ 3.13.0 1.18.20 - 1.4.197 + 1.4.200 diff --git a/spring-boot-modules/spring-boot-angular/pom.xml b/spring-boot-modules/spring-boot-angular/pom.xml index 89a8814d2f..443e7b2f88 100644 --- a/spring-boot-modules/spring-boot-angular/pom.xml +++ b/spring-boot-modules/spring-boot-angular/pom.xml @@ -32,7 +32,6 @@ com.h2database h2 - ${h2.version} runtime diff --git a/spring-boot-modules/spring-boot-data/pom.xml b/spring-boot-modules/spring-boot-data/pom.xml index 447b730c02..46ca8639ed 100644 --- a/spring-boot-modules/spring-boot-data/pom.xml +++ b/spring-boot-modules/spring-boot-data/pom.xml @@ -36,7 +36,6 @@ com.h2database h2 - ${h2.version} org.springframework.boot diff --git a/spring-security-modules/spring-session/spring-session-jdbc/pom.xml b/spring-security-modules/spring-session/spring-session-jdbc/pom.xml index 64bbce44f2..3cc2b8d18e 100644 --- a/spring-security-modules/spring-session/spring-session-jdbc/pom.xml +++ b/spring-security-modules/spring-session/spring-session-jdbc/pom.xml @@ -28,7 +28,6 @@ com.h2database h2 - ${h2.version} runtime diff --git a/testing-modules/spring-testing-2/pom.xml b/testing-modules/spring-testing-2/pom.xml index f3e4f098b4..82a9ed9599 100644 --- a/testing-modules/spring-testing-2/pom.xml +++ b/testing-modules/spring-testing-2/pom.xml @@ -26,7 +26,6 @@ com.h2database h2 - ${h2.version} org.postgresql From fa1f32f1864a34739ee934f240b4fe872d938d54 Mon Sep 17 00:00:00 2001 From: chaos2418 <> Date: Sat, 20 Nov 2021 09:45:50 +0530 Subject: [PATCH 07/65] JAVA-8435: reducing logging for tutorials-integration job --- .../r2dbc/src/test/resources/logback-test.xml | 12 +++++ .../src/test/resources/logback-test.xml | 12 +++++ .../DatasourceProxyBeanPostProcessor.java | 5 +- .../src/main/resources/application.properties | 2 +- .../src/test/resources/logback-test.xml | 12 +++++ .../src/test/resources/logback-test.xml | 12 +++++ .../EnversFooBarAuditIntegrationTest.java | 37 +++++++++----- .../persistence/hibernate/FooFixtures.java | 39 +++++++++------ .../FooSortingPersistenceIntegrationTest.java | 49 ++++++++++++------- ...rentServicePersistenceIntegrationTest.java | 13 +++-- .../spring/config/PersistenceTestConfig.java | 2 +- .../query/UserRepositoryIntegrationTest.java | 25 ++++------ .../ArticleRepositoryIntegrationTest.java | 2 +- .../src/test/resources/fetching.cfg.xml | 2 +- .../src/test/resources/fetchingLazy.cfg.xml | 2 +- .../SpringDataAggregateIntegrationTest.java | 3 +- .../PassengerRepositoryIntegrationTest.java | 3 +- .../EntityGraphIntegrationTest.java | 2 +- .../exists/CarRepositoryIntegrationTest.java | 2 + .../joins/JpaJoinsIntegrationTest.java | 3 +- .../src/test/resources/logback-test.xml | 12 +++++ .../saveperformance/BookApplication.java | 10 ++-- .../src/test/resources/logback-test.xml | 12 +++++ .../InventoryRepositoryIntegrationTest.java | 2 +- .../daos/JpaRepositoriesIntegrationTest.java | 2 +- .../UserRepositoryIntegrationTest.java | 2 +- .../like/MovieRepositoryIntegrationTest.java | 2 +- .../FruitPopulatorIntegrationTest.java | 2 +- .../PassengerRepositoryIntegrationTest.java | 2 +- .../SongRepositoryIntegrationTest.java | 2 +- .../src/test/resources/logback-test.xml | 12 +++++ .../dynamicupdate/DynamicUpdateConfig.java | 2 +- .../immutable/util/HibernateUtil.java | 9 +++- .../manytomany/util/HibernateUtil.java | 16 +++--- .../manytomany/spring/PersistenceConfig.java | 2 +- .../baeldung/spring/PersistenceConfig.java | 2 +- .../src/main/resources/immutable.cfg.xml | 2 +- .../src/main/resources/manytomany.cfg.xml | 2 +- .../src/test/resources/manytomany.cfg.xml | 2 +- .../guide/EmployeeDAOIntegrationTest.java | 6 ++- .../src/test/resources/logback-test.xml | 12 +++++ .../main/resources/persistence-h2.properties | 2 +- .../src/test/resources/logback-test.xml | 12 +++++ .../test/resources/manytomany/test.properties | 2 +- .../main/resources/persistence-h2.properties | 2 +- .../persistence-student-h2.properties | 2 +- .../resources/persistence-student.properties | 2 +- .../src/test/java/META-INF/persistence.xml | 2 +- ...oPaginationPersistenceIntegrationTest.java | 6 ++- .../FooServiceSortingIntegrationTest.java | 22 +++++---- ...eSortingWitNullsManualIntegrationTest.java | 8 ++- .../resources/persistence-student.properties | 2 +- pom.xml | 6 +++ 53 files changed, 300 insertions(+), 122 deletions(-) create mode 100644 persistence-modules/r2dbc/src/test/resources/logback-test.xml create mode 100644 persistence-modules/spring-boot-persistence-2/src/test/resources/logback-test.xml create mode 100644 persistence-modules/spring-boot-persistence-mongodb/src/test/resources/logback-test.xml create mode 100644 persistence-modules/spring-data-cassandra-reactive/src/test/resources/logback-test.xml create mode 100644 persistence-modules/spring-data-jpa-query/src/test/resources/logback-test.xml create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/test/resources/logback-test.xml create mode 100644 persistence-modules/spring-data-jpa-repo/src/test/resources/logback-test.xml create mode 100644 persistence-modules/spring-jdbc/src/test/resources/logback-test.xml create mode 100644 persistence-modules/spring-jpa-2/src/test/resources/logback-test.xml diff --git a/persistence-modules/r2dbc/src/test/resources/logback-test.xml b/persistence-modules/r2dbc/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/r2dbc/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-2/src/test/resources/logback-test.xml b/persistence-modules/spring-boot-persistence-2/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/config/DatasourceProxyBeanPostProcessor.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/config/DatasourceProxyBeanPostProcessor.java index c087427b65..1952a26f2f 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/config/DatasourceProxyBeanPostProcessor.java +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/config/DatasourceProxyBeanPostProcessor.java @@ -1,10 +1,7 @@ package com.baeldung.h2db.lazy_load_no_trans.config; import net.ttddyy.dsproxy.listener.DataSourceQueryCountListener; -import net.ttddyy.dsproxy.listener.logging.CommonsQueryLoggingListener; -import net.ttddyy.dsproxy.listener.logging.DefaultQueryLogEntryCreator; import net.ttddyy.dsproxy.listener.logging.SLF4JLogLevel; -import net.ttddyy.dsproxy.listener.logging.SLF4JQueryLoggingListener; import net.ttddyy.dsproxy.support.ProxyDataSource; import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder; import org.aopalliance.intercept.MethodInterceptor; @@ -49,7 +46,7 @@ public class DatasourceProxyBeanPostProcessor implements BeanPostProcessor { this.dataSource = ProxyDataSourceBuilder.create(dataSource) .name("MyDS") .multiline() - .logQueryBySlf4j(SLF4JLogLevel.INFO) + .logQueryBySlf4j(SLF4JLogLevel.DEBUG) .listener(new DataSourceQueryCountListener()) .build(); } diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application.properties b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application.properties index 134cda6628..2499d7cd06 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application.properties +++ b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application.properties @@ -4,7 +4,7 @@ spring.datasource.username=sa spring.datasource.password= spring.jpa.defer-datasource-initialization=true spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.show-sql=true +spring.jpa.show-sql=false spring.jpa.properties.hibernate.format_sql=true spring.jpa.properties.hibernate.validator.apply_to_ddl=false #spring.jpa.properties.hibernate.check_nullability=true diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/test/resources/logback-test.xml b/persistence-modules/spring-boot-persistence-mongodb/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-cassandra-reactive/src/test/resources/logback-test.xml b/persistence-modules/spring-data-cassandra-reactive/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/spring-data-cassandra-reactive/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java index 444324dafc..7397a61cac 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java @@ -123,24 +123,39 @@ public class EnversFooBarAuditIntegrationTest { assertNotNull(barRevisionList); assertEquals(4, barRevisionList.size()); - assertEquals("BAR", barRevisionList.get(0).getName()); - assertEquals("BAR", barRevisionList.get(1).getName()); - assertEquals("BAR1", barRevisionList.get(2).getName()); - assertEquals("BAR1", barRevisionList.get(3).getName()); + assertEquals("BAR", barRevisionList.get(0) + .getName()); + assertEquals("BAR", barRevisionList.get(1) + .getName()); + assertEquals("BAR1", barRevisionList.get(2) + .getName()); + assertEquals("BAR1", barRevisionList.get(3) + .getName()); - assertEquals(1, barRevisionList.get(0).getFooSet().size()); - assertEquals(2, barRevisionList.get(1).getFooSet().size()); - assertEquals(2, barRevisionList.get(2).getFooSet().size()); - assertEquals(3, barRevisionList.get(3).getFooSet().size()); + assertEquals(1, barRevisionList.get(0) + .getFooSet() + .size()); + assertEquals(2, barRevisionList.get(1) + .getFooSet() + .size()); + assertEquals(2, barRevisionList.get(2) + .getFooSet() + .size()); + assertEquals(3, barRevisionList.get(3) + .getFooSet() + .size()); // test Foo revisions fooRevisionList = fooService.getRevisions(); assertNotNull(fooRevisionList); assertEquals(3, fooRevisionList.size()); - assertEquals("FOO1", fooRevisionList.get(0).getName()); - assertEquals("FOO2", fooRevisionList.get(1).getName()); - assertEquals("FOO3", fooRevisionList.get(2).getName()); + assertEquals("FOO1", fooRevisionList.get(0) + .getName()); + assertEquals("FOO2", fooRevisionList.get(1) + .getName()); + assertEquals("FOO3", fooRevisionList.get(2) + .getName()); } } diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java index da840dc027..e0bd8a4f98 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java @@ -10,8 +10,13 @@ import org.hibernate.SessionFactory; import org.hibernate.Transaction; import com.google.common.collect.Lists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class FooFixtures { + + private static final Logger LOGGER = LoggerFactory.getLogger(FooFixtures.class); + private SessionFactory sessionFactory; public FooFixtures(final SessionFactory sessionFactory) { @@ -36,26 +41,30 @@ public class FooFixtures { foo.setBar(bar); session.save(foo); final Foo foo2 = new Foo(null); - if (i % 2 == 0) + if (i % 2 == 0) { foo2.setName("LuckyFoo" + (i + 120)); + } foo2.setBar(bar); session.save(foo2); - bar.getFooSet().add(foo); - bar.getFooSet().add(foo2); + bar.getFooSet() + .add(foo); + bar.getFooSet() + .add(foo2); session.merge(bar); } tx.commit(); session.flush(); } catch (final HibernateException he) { - if (tx != null) + if (tx != null) { tx.rollback(); - System.out.println("Not able to open session"); - he.printStackTrace(); + } + LOGGER.error("Not able to open session", he); } catch (final Exception e) { - e.printStackTrace(); + LOGGER.error(e.getLocalizedMessage(), e); } finally { - if (session != null) + if (session != null) { session.close(); + } } } @@ -71,7 +80,8 @@ public class FooFixtures { final Foo foo = new Foo(); foo.setName("Foo_" + (i + 120)); final Bar bar = new Bar("bar_" + i); - bar.getFooSet().add(foo); + bar.getFooSet() + .add(foo); foo.setBar(bar); fooList.add(foo); @@ -86,15 +96,16 @@ public class FooFixtures { tx.commit(); session.flush(); } catch (final HibernateException he) { - if (tx != null) + if (tx != null) { tx.rollback(); - System.out.println("Not able to open session"); - he.printStackTrace(); + } + LOGGER.error("Not able to open session", he); } catch (final Exception e) { - e.printStackTrace(); + LOGGER.error(e.getLocalizedMessage(), e); } finally { - if (session != null) + if (session != null) { session.close(); + } } } diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java index 8173088af0..fe73ddba3f 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java @@ -15,6 +15,8 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -29,6 +31,8 @@ import com.baeldung.spring.config.PersistenceTestConfig; @SuppressWarnings("unchecked") public class FooSortingPersistenceIntegrationTest { + private static final Logger LOGGER = LoggerFactory.getLogger(FooSortingPersistenceIntegrationTest.class); + @Autowired private SessionFactory sessionFactory; @@ -46,7 +50,8 @@ public class FooSortingPersistenceIntegrationTest { @After public void after() { - session.getTransaction().commit(); + session.getTransaction() + .commit(); session.close(); } @@ -56,7 +61,7 @@ public class FooSortingPersistenceIntegrationTest { final Query query = session.createQuery(hql); final List fooList = query.list(); for (final Foo foo : fooList) { - System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); + LOGGER.debug("Name: {} , Id: {}", foo.getName(), foo.getId()); } } @@ -66,9 +71,10 @@ public class FooSortingPersistenceIntegrationTest { final Query query = session.createQuery(hql); final List fooList = query.list(); - assertNull(fooList.get(fooList.toArray().length - 1).getName()); + assertNull(fooList.get(fooList.toArray().length - 1) + .getName()); for (final Foo foo : fooList) { - System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); + LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId()); } } @@ -77,9 +83,10 @@ public class FooSortingPersistenceIntegrationTest { final String hql = "FROM Foo f ORDER BY f.name NULLS FIRST"; final Query query = session.createQuery(hql); final List fooList = query.list(); - assertNull(fooList.get(0).getName()); + assertNull(fooList.get(0) + .getName()); for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName()); + LOGGER.debug("Name: {}", foo.getName()); } } @@ -90,7 +97,7 @@ public class FooSortingPersistenceIntegrationTest { final Query query = session.createQuery(hql); final List fooList = query.list(); for (final Foo foo : fooList) { - System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); + LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId()); } } @@ -100,7 +107,7 @@ public class FooSortingPersistenceIntegrationTest { final Query query = session.createQuery(hql); final List fooList = query.list(); for (final Foo foo : fooList) { - System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); + LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId()); } } @@ -110,7 +117,7 @@ public class FooSortingPersistenceIntegrationTest { final Query query = session.createQuery(hql); final List fooList = query.list(); for (final Foo foo : fooList) { - System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); + LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId()); } } @@ -120,7 +127,7 @@ public class FooSortingPersistenceIntegrationTest { criteria.addOrder(Order.asc("id")); final List fooList = criteria.list(); for (final Foo foo : fooList) { - System.out.println("Id: " + foo.getId() + ", FirstName: " + foo.getName()); + LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName()); } } @@ -131,29 +138,33 @@ public class FooSortingPersistenceIntegrationTest { criteria.addOrder(Order.asc("id")); final List fooList = criteria.list(); for (final Foo foo : fooList) { - System.out.println("Id: " + foo.getId() + ", FirstName: " + foo.getName()); + LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName()); } } @Test public final void whenCriteriaSortingStringNullsLastAsc_thenNullsLast() { final Criteria criteria = session.createCriteria(Foo.class, "FOO"); - criteria.addOrder(Order.asc("name").nulls(NullPrecedence.LAST)); + criteria.addOrder(Order.asc("name") + .nulls(NullPrecedence.LAST)); final List fooList = criteria.list(); - assertNull(fooList.get(fooList.toArray().length - 1).getName()); + assertNull(fooList.get(fooList.toArray().length - 1) + .getName()); for (final Foo foo : fooList) { - System.out.println("Id: " + foo.getId() + ", FirstName: " + foo.getName()); + LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName()); } } @Test public final void whenCriteriaSortingStringNullsFirstDesc_thenNullsFirst() { final Criteria criteria = session.createCriteria(Foo.class, "FOO"); - criteria.addOrder(Order.desc("name").nulls(NullPrecedence.FIRST)); + criteria.addOrder(Order.desc("name") + .nulls(NullPrecedence.FIRST)); final List fooList = criteria.list(); - assertNull(fooList.get(0).getName()); + assertNull(fooList.get(0) + .getName()); for (final Foo foo : fooList) { - System.out.println("Id: " + foo.getId() + ", FirstName: " + foo.getName()); + LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName()); } } @@ -164,9 +175,9 @@ public class FooSortingPersistenceIntegrationTest { final List barList = query.list(); for (final Bar bar : barList) { final Set fooSet = bar.getFooSet(); - System.out.println("Bar Id:" + bar.getId()); + LOGGER.debug("Bar Id:{}", bar.getId()); for (final Foo foo : fooSet) { - System.out.println("FooName:" + foo.getName()); + LOGGER.debug("FooName:{}", foo.getName()); } } } diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java index 5a73e39ca2..8c766954ff 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java @@ -1,7 +1,10 @@ package com.baeldung.persistence.service; +import com.baeldung.persistence.hibernate.FooSortingPersistenceIntegrationTest; import org.junit.Test; import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.test.context.ContextConfiguration; @@ -16,6 +19,8 @@ import com.baeldung.spring.config.PersistenceTestConfig; @ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) public class ParentServicePersistenceIntegrationTest { + private static final Logger LOGGER = LoggerFactory.getLogger(ParentServicePersistenceIntegrationTest.class); + @Autowired private IParentService service; @@ -37,11 +42,11 @@ public class ParentServicePersistenceIntegrationTest { final Parent parentEntity = new Parent(childEntity); service.create(parentEntity); - System.out.println("Child = " + childService.findOne(childEntity.getId())); - System.out.println("Child - parent = " + childService.findOne(childEntity.getId()).getParent()); + LOGGER.debug("Child = {}", childService.findOne(childEntity.getId())); + LOGGER.debug("Child - parent = {}", childService.findOne(childEntity.getId()).getParent()); - System.out.println("Parent = " + service.findOne(parentEntity.getId())); - System.out.println("Parent - child = " + service.findOne(parentEntity.getId()).getChild()); + LOGGER.debug("Parent = {}", service.findOne(parentEntity.getId())); + LOGGER.debug("Parent - child = {}", service.findOne(parentEntity.getId()).getChild()); } @Test(expected = DataIntegrityViolationException.class) diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java index 34301741fe..c8f14c5563 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java @@ -166,7 +166,7 @@ public class PersistenceTestConfig { hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - hibernateProperties.setProperty("hibernate.show_sql", "true"); + hibernateProperties.setProperty("hibernate.show_sql", "false"); // hibernateProperties.setProperty("hibernate.format_sql", "true"); // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/UserRepositoryIntegrationTest.java index a9ab13feed..df07c74c5a 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/UserRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/UserRepositoryIntegrationTest.java @@ -19,7 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(SpringRunner.class) -@DataJpaTest(properties = "spring.sql.init.data-locations=classpath:insert_users.sql") +@DataJpaTest(properties = "spring.sql.init.data-locations=classpath:insert_users.sql", showSql = false) public class UserRepositoryIntegrationTest { @Autowired @@ -40,46 +40,42 @@ public class UserRepositoryIntegrationTest { @Test public void whenFindAllSortedByNameThenAllSorted() { List allUsersSortedByName = userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); - assertThat(allUsersSortedByName) - .extracting("name") + assertThat(allUsersSortedByName).extracting("name") .containsSequence("Bob", "Cindy", "John"); } @Test public void whenFindAllSortedByNameLengthThenException() { - assertThatThrownBy(() -> userRepository.findAll(Sort.by("LENGTH(name)"))) - .isInstanceOf(PropertyReferenceException.class); + assertThatThrownBy(() -> userRepository.findAll(Sort.by("LENGTH(name)"))).isInstanceOf(PropertyReferenceException.class); } @Test public void whenFindAllUsersSortedByNameThenAllSorted() { List allUsersSortedByName = userRepository.findAllUsers(Sort.by(Sort.Direction.ASC, "name")); - assertThat(allUsersSortedByName) - .extracting("name") + assertThat(allUsersSortedByName).extracting("name") .containsSequence("Bob", "Cindy", "John"); } @Test public void whenFindAllUsersSortedByNameLengthThenAllSorted() { List allUsersSortedByName = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)")); - assertThat(allUsersSortedByName) - .extracting("name") + assertThat(allUsersSortedByName).extracting("name") .containsSequence("Bob", "John", "Cindy"); } @Test public void whenFindAllUsersWithPaginationThenPaginated() { Page page = userRepository.findAllUsersWithPagination(PageRequest.of(0, 1)); - assertThat(page.stream().map(User::getId)) - .hasSize(1) + assertThat(page.stream() + .map(User::getId)).hasSize(1) .containsOnly(1); } @Test public void whenFindAllUsersWithPaginationNativeThenPaginated() { Page page = userRepository.findAllUsersWithPaginationNative(PageRequest.of(1, 1)); - assertThat(page.stream().map(User::getId)) - .hasSize(1) + assertThat(page.stream() + .map(User::getId)).hasSize(1) .containsOnly(2); } @@ -126,8 +122,7 @@ public class UserRepositoryIntegrationTest { @Test public void whenFindUserByNameListThenAllFound() { List users = userRepository.findUserByNameList(Arrays.asList("Bob", "Cindy")); - assertThat(users) - .extracting("name") + assertThat(users).extracting("name") .containsOnly("Bob", "Cindy"); } diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepositoryIntegrationTest.java index e00a340615..b97fbc5275 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepositoryIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) -@DataJpaTest(properties="spring.sql.init.data-locations=classpath:import_entities.sql") +@DataJpaTest(properties="spring.sql.init.data-locations=classpath:import_entities.sql", showSql = false) public class ArticleRepositoryIntegrationTest { @Autowired diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetching.cfg.xml b/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetching.cfg.xml index 55a3aeb51c..4d3ff2ae63 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetching.cfg.xml +++ b/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetching.cfg.xml @@ -11,7 +11,7 @@ org.hibernate.dialect.H2Dialect update - true + false diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetchingLazy.cfg.xml b/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetchingLazy.cfg.xml index 8fcf578660..8a2bf593cb 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetchingLazy.cfg.xml +++ b/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetchingLazy.cfg.xml @@ -11,7 +11,7 @@ org.hibernate.dialect.H2Dialect update - true + false diff --git a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java index 779ade7a3f..a73ad949db 100644 --- a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java @@ -16,8 +16,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; @RunWith(SpringRunner.class) -@DataJpaTest - +@DataJpaTest(showSql = false) @Sql(scripts = "/test-aggregation-data.sql") public class SpringDataAggregateIntegrationTest { diff --git a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java index f082350019..d80380854d 100644 --- a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java @@ -26,8 +26,7 @@ import static org.hamcrest.core.IsNot.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; - -@DataJpaTest +@DataJpaTest(showSql = false) @RunWith(SpringRunner.class) public class PassengerRepositoryIntegrationTest { diff --git a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java index 24880a5dff..b6bf51ac65 100644 --- a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java @@ -14,7 +14,7 @@ import com.baeldung.entitygraph.model.Item; import com.baeldung.entitygraph.repository.CharacteristicsRepository; import com.baeldung.entitygraph.repository.ItemRepository; -@DataJpaTest +@DataJpaTest(showSql = false) @RunWith(SpringRunner.class) @Sql(scripts = "/entitygraph-data.sql") public class EntityGraphIntegrationTest { diff --git a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java index d99f6671a3..c740fd7abd 100644 --- a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java @@ -9,6 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Example; import org.springframework.data.domain.ExampleMatcher; +import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import java.util.Arrays; @@ -19,6 +20,7 @@ import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatc @RunWith(SpringRunner.class) @SpringBootTest(classes = {Application.class}) +@TestPropertySource(properties = {"spring.jpa.show-sql=false"}) public class CarRepositoryIntegrationTest { @Autowired diff --git a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java index 9b0d23f3e4..e24b2ae4b7 100644 --- a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java @@ -13,10 +13,11 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) -@DataJpaTest +@DataJpaTest(showSql = false) @ActiveProfiles("joins") public class JpaJoinsIntegrationTest { diff --git a/persistence-modules/spring-data-jpa-query/src/test/resources/logback-test.xml b/persistence-modules/spring-data-jpa-query/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/saveperformance/BookApplication.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/saveperformance/BookApplication.java index 56ad918be3..46cb8d3453 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/saveperformance/BookApplication.java +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/saveperformance/BookApplication.java @@ -1,5 +1,7 @@ package com.baeldung.spring.data.persistence.saveperformance; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -12,6 +14,8 @@ import java.util.List; @SpringBootApplication public class BookApplication { + private static final Logger LOGGER = LoggerFactory.getLogger(BookApplication.class); + @Autowired private BookRepository bookRepository; @@ -25,13 +29,13 @@ public class BookApplication { int bookCount = 10000; long start = System.currentTimeMillis(); - for(int i = 0; i < bookCount; i++) { + for (int i = 0; i < bookCount; i++) { bookRepository.save(new Book("Book " + i, "Author " + i)); } long end = System.currentTimeMillis(); bookRepository.deleteAll(); - System.out.println("It took " + (end - start) + "ms to execute save() for " + bookCount + " books"); + LOGGER.debug("It took {}ms to execute save() for {} books.", (end - start), bookCount); List bookList = new ArrayList<>(); for (int i = 0; i < bookCount; i++) { @@ -42,7 +46,7 @@ public class BookApplication { bookRepository.saveAll(bookList); end = System.currentTimeMillis(); - System.out.println("It took " + (end - start) + "ms to execute saveAll() with " + bookCount + " books\n"); + LOGGER.debug("It took {}ms to execute saveAll() with {}} books.", (end - start), bookCount); } } diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/resources/logback-test.xml b/persistence-modules/spring-data-jpa-repo-2/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java index e4bd3dabff..9201df8990 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java @@ -19,7 +19,7 @@ import com.baeldung.Application; import com.baeldung.boot.domain.MerchandiseEntity; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) +@SpringBootTest(classes = Application.class, properties = {"spring.jpa.show-sql=false"}) public class InventoryRepositoryIntegrationTest { private static final String ORIGINAL_TITLE = "Pair of Pants"; diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java index fe02f79a56..34de77a2b3 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java @@ -21,7 +21,7 @@ import com.baeldung.boot.domain.Location; import com.baeldung.boot.domain.Store; @RunWith(SpringRunner.class) -@DataJpaTest(properties="spring.sql.init.data-locations=classpath:import_entities.sql") +@DataJpaTest(properties="spring.sql.init.data-locations=classpath:import_entities.sql", showSql = false) public class JpaRepositoriesIntegrationTest { @Autowired private LocationRepository locationRepository; diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java index 2a6e166b88..41c171e449 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java @@ -17,7 +17,7 @@ import java.util.List; import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) -@SpringBootTest(classes = QueryApplication.class) +@SpringBootTest(classes = QueryApplication.class, properties = {"spring.jpa.show-sql=false"}) public class UserRepositoryIntegrationTest { private static final String USER_NAME_ADAM = "Adam"; diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java index cc96b638ab..a4a1982df8 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java @@ -16,7 +16,7 @@ import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TES @RunWith(SpringRunner.class) @Sql(scripts = { "/test-movie-data.sql" }) -@SpringBootTest(classes = LikeApplication.class) +@SpringBootTest(classes = LikeApplication.class, properties = {"spring.jpa.show-sql=false"}) @Sql(scripts = "/test-movie-cleanup.sql", executionPhase = AFTER_TEST_METHOD) public class MovieRepositoryIntegrationTest { @Autowired diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java index 4d3661e717..d0b2ab8dd7 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.entity.Fruit; @RunWith(SpringRunner.class) -@SpringBootTest +@SpringBootTest(properties = {"spring.jpa.show-sql=false"}) public class FruitPopulatorIntegrationTest { @Autowired diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java index 37fcef7dab..fd06710084 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java @@ -18,7 +18,7 @@ import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.entity.Passenger; -@DataJpaTest +@DataJpaTest(showSql = false) @RunWith(SpringRunner.class) public class PassengerRepositoryIntegrationTest { diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java index 19362acd44..619b410f0d 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java @@ -16,7 +16,7 @@ import com.baeldung.entity.Song; import com.baeldung.repository.SongRepository; @RunWith(SpringRunner.class) -@SpringBootTest +@SpringBootTest(properties = {"spring.jpa.show-sql=false"}) @Sql(scripts = { "/test-song-data.sql" }) public class SongRepositoryIntegrationTest { diff --git a/persistence-modules/spring-data-jpa-repo/src/test/resources/logback-test.xml b/persistence-modules/spring-data-jpa-repo/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/dynamicupdate/DynamicUpdateConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/dynamicupdate/DynamicUpdateConfig.java index 4871a3d1e2..23e28a9e3b 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/dynamicupdate/DynamicUpdateConfig.java +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/dynamicupdate/DynamicUpdateConfig.java @@ -74,7 +74,7 @@ public class DynamicUpdateConfig { Properties properties = new Properties(); properties.setProperty("hibernate.hbm2ddl.auto", Preconditions.checkNotNull(env.getProperty("hibernate.hbm2ddl.auto"))); properties.setProperty("hibernate.dialect", Preconditions.checkNotNull(env.getProperty("hibernate.dialect"))); - properties.setProperty("hibernate.show_sql", "true"); + properties.setProperty("hibernate.show_sql", "false"); return properties; } } \ No newline at end of file diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java index 722f0251d1..25d7de4b07 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java @@ -6,8 +6,12 @@ import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class HibernateUtil { + + private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class); private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { @@ -17,10 +21,11 @@ public class HibernateUtil { configuration.addAnnotatedClass(Event.class); configuration.addAnnotatedClass(EventGeneratedId.class); configuration.configure("immutable.cfg.xml"); - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) + .build(); return configuration.buildSessionFactory(serviceRegistry); } catch (Throwable ex) { - System.out.println("Initial SessionFactory creation failed." + ex); + LOGGER.debug("Initial SessionFactory creation failed.", ex); throw new ExceptionInInitializerError(ex); } } diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java index 5f489dd027..29e8d7515a 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java @@ -6,8 +6,12 @@ import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import com.baeldung.hibernate.manytomany.model.Employee; import com.baeldung.hibernate.manytomany.model.Project; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class HibernateUtil { + + private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class); private static SessionFactory sessionFactory; private static SessionFactory buildSessionFactory() { @@ -17,25 +21,25 @@ public class HibernateUtil { configuration.addAnnotatedClass(Employee.class); configuration.addAnnotatedClass(Project.class); configuration.configure("manytomany.cfg.xml"); - System.out.println("Hibernate Annotation Configuration loaded"); + LOGGER.debug("Hibernate Annotation Configuration loaded"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) - .build(); - System.out.println("Hibernate Annotation serviceRegistry created"); + .build(); + LOGGER.debug("Hibernate Annotation serviceRegistry created"); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } catch (Throwable ex) { - System.err.println("Initial SessionFactory creation failed." + ex); - ex.printStackTrace(); + LOGGER.error("Initial SessionFactory creation failed.", ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { - if (sessionFactory == null) + if (sessionFactory == null) { sessionFactory = buildSessionFactory(); + } return sessionFactory; } } diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java index 44cbfadb25..b8e7e1b2fd 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java @@ -63,7 +63,7 @@ public class PersistenceConfig { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - hibernateProperties.setProperty("hibernate.show_sql", "true"); + hibernateProperties.setProperty("hibernate.show_sql", "false"); return hibernateProperties; } diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java index 74ac0a269e..159d6e2e8e 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java @@ -71,7 +71,7 @@ public class PersistenceConfig { hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - hibernateProperties.setProperty("hibernate.show_sql", "true"); + hibernateProperties.setProperty("hibernate.show_sql", "false"); // Envers properties hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); diff --git a/persistence-modules/spring-hibernate-5/src/main/resources/immutable.cfg.xml b/persistence-modules/spring-hibernate-5/src/main/resources/immutable.cfg.xml index a572ebeac2..4e55b4632f 100644 --- a/persistence-modules/spring-hibernate-5/src/main/resources/immutable.cfg.xml +++ b/persistence-modules/spring-hibernate-5/src/main/resources/immutable.cfg.xml @@ -23,7 +23,7 @@ thread - true + false update diff --git a/persistence-modules/spring-hibernate-5/src/main/resources/manytomany.cfg.xml b/persistence-modules/spring-hibernate-5/src/main/resources/manytomany.cfg.xml index 3c753a89af..315e2e3118 100644 --- a/persistence-modules/spring-hibernate-5/src/main/resources/manytomany.cfg.xml +++ b/persistence-modules/spring-hibernate-5/src/main/resources/manytomany.cfg.xml @@ -10,6 +10,6 @@ tutorialuser org.hibernate.dialect.MySQLDialect thread - true + false diff --git a/persistence-modules/spring-hibernate-5/src/test/resources/manytomany.cfg.xml b/persistence-modules/spring-hibernate-5/src/test/resources/manytomany.cfg.xml index a7a23ec70d..2ca23d57d3 100644 --- a/persistence-modules/spring-hibernate-5/src/test/resources/manytomany.cfg.xml +++ b/persistence-modules/spring-hibernate-5/src/test/resources/manytomany.cfg.xml @@ -10,7 +10,7 @@ sa org.hibernate.dialect.H2Dialect thread - true + false create-drop diff --git a/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAOIntegrationTest.java b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAOIntegrationTest.java index c29d5c4534..b382895143 100644 --- a/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAOIntegrationTest.java +++ b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAOIntegrationTest.java @@ -9,6 +9,8 @@ import com.baeldung.spring.jdbc.template.guide.config.SpringJdbcConfig; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.test.context.ContextConfiguration; @@ -19,6 +21,8 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @ContextConfiguration(classes = { SpringJdbcConfig.class }, loader = AnnotationConfigContextLoader.class) public class EmployeeDAOIntegrationTest { + private static final Logger LOGGER = LoggerFactory.getLogger(EmployeeDAOIntegrationTest.class); + @Autowired private EmployeeDAO employeeDao; @@ -70,7 +74,7 @@ public class EmployeeDAOIntegrationTest { try { employeeDao.addEmplyee(7); } catch (final DuplicateKeyException e) { - System.out.println(e.getMessage()); + LOGGER.error(e.getMessage(), e); Assert.assertTrue(e.getMessage().contains("Custome Exception translator - Integrity contraint voilation.")); } } diff --git a/persistence-modules/spring-jdbc/src/test/resources/logback-test.xml b/persistence-modules/spring-jdbc/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/spring-jdbc/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-jpa-2/src/main/resources/persistence-h2.properties b/persistence-modules/spring-jpa-2/src/main/resources/persistence-h2.properties index 716a96fde3..b429ce3a16 100644 --- a/persistence-modules/spring-jpa-2/src/main/resources/persistence-h2.properties +++ b/persistence-modules/spring-jpa-2/src/main/resources/persistence-h2.properties @@ -6,7 +6,7 @@ jdbc.pass= # hibernate.X hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true +hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop hibernate.cache.use_second_level_cache=true hibernate.cache.use_query_cache=true diff --git a/persistence-modules/spring-jpa-2/src/test/resources/logback-test.xml b/persistence-modules/spring-jpa-2/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/spring-jpa-2/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-jpa-2/src/test/resources/manytomany/test.properties b/persistence-modules/spring-jpa-2/src/test/resources/manytomany/test.properties index 9e4236a6c2..db92a1b8c1 100644 --- a/persistence-modules/spring-jpa-2/src/test/resources/manytomany/test.properties +++ b/persistence-modules/spring-jpa-2/src/test/resources/manytomany/test.properties @@ -2,5 +2,5 @@ jdbc.driverClassName=org.h2.Driver jdbc.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1 hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true +hibernate.show_sql=false hibernate.hbm2ddl.auto=validate diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties b/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties index a3060cc796..72b51f02b7 100644 --- a/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties +++ b/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties @@ -6,5 +6,5 @@ jdbc.pass= # hibernate.X hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true +hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence-student-h2.properties b/persistence-modules/spring-jpa/src/main/resources/persistence-student-h2.properties index 405e6ff109..a5d2bec189 100644 --- a/persistence-modules/spring-jpa/src/main/resources/persistence-student-h2.properties +++ b/persistence-modules/spring-jpa/src/main/resources/persistence-student-h2.properties @@ -6,7 +6,7 @@ jdbc.pass= # hibernate.X hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true +hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop hibernate.cache.use_second_level_cache=false hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence-student.properties b/persistence-modules/spring-jpa/src/main/resources/persistence-student.properties index d4c82420de..9a06518238 100644 --- a/persistence-modules/spring-jpa/src/main/resources/persistence-student.properties +++ b/persistence-modules/spring-jpa/src/main/resources/persistence-student.properties @@ -4,7 +4,7 @@ jdbc.user=tutorialuser jdbc.pass=tutorialpass hibernate.dialect=org.hibernate.dialect.MySQL5Dialect -hibernate.show_sql=true +hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop hibernate.cache.use_second_level_cache=false diff --git a/persistence-modules/spring-jpa/src/test/java/META-INF/persistence.xml b/persistence-modules/spring-jpa/src/test/java/META-INF/persistence.xml index 495f076fef..76a3b61399 100644 --- a/persistence-modules/spring-jpa/src/test/java/META-INF/persistence.xml +++ b/persistence-modules/spring-jpa/src/test/java/META-INF/persistence.xml @@ -11,7 +11,7 @@ - + diff --git a/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java index fbda459d65..66f20a6724 100644 --- a/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java @@ -20,6 +20,8 @@ import com.baeldung.persistence.model.Foo; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; @@ -31,6 +33,8 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @DirtiesContext public class FooPaginationPersistenceIntegrationTest { + private static final Logger LOGGER = LoggerFactory.getLogger(FooPaginationPersistenceIntegrationTest.class); + @PersistenceContext private EntityManager entityManager; @@ -137,7 +141,7 @@ public class FooPaginationPersistenceIntegrationTest { typedQuery = entityManager.createQuery(select); typedQuery.setFirstResult(pageNumber - 1); typedQuery.setMaxResults(pageSize); - System.out.println("Current page: " + typedQuery.getResultList()); + LOGGER.debug("Current page: {}", typedQuery.getResultList()); pageNumber += pageSize; } diff --git a/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooServiceSortingIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooServiceSortingIntegrationTest.java index c3db45ab41..8d1f94edf8 100644 --- a/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooServiceSortingIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooServiceSortingIntegrationTest.java @@ -15,6 +15,8 @@ import com.baeldung.persistence.model.Bar; import com.baeldung.persistence.model.Foo; import org.junit.Test; import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -26,6 +28,8 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @SuppressWarnings("unchecked") public class FooServiceSortingIntegrationTest { + private static final Logger LOGGER = LoggerFactory.getLogger(FooServiceSortingIntegrationTest.class); + @PersistenceContext private EntityManager entityManager; @@ -37,7 +41,7 @@ public class FooServiceSortingIntegrationTest { final Query sortQuery = entityManager.createQuery(jql); final List fooList = sortQuery.getResultList(); for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId()); + LOGGER.debug("Name:{}-------Id:{}", foo.getName(), foo.getId()); } } @@ -47,7 +51,7 @@ public class FooServiceSortingIntegrationTest { final Query sortQuery = entityManager.createQuery(jql); final List fooList = sortQuery.getResultList(); for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId()); + LOGGER.debug("Name:{}-------Id:{}", foo.getName(), foo.getId()); } } @@ -57,7 +61,7 @@ public class FooServiceSortingIntegrationTest { final Query sortQuery = entityManager.createQuery(jql); final List fooList = sortQuery.getResultList(); for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId()); + LOGGER.debug("Name:{}-------Id:{}", foo.getName(), foo.getId()); } } @@ -67,9 +71,9 @@ public class FooServiceSortingIntegrationTest { final Query barJoinQuery = entityManager.createQuery(jql); final List fooList = barJoinQuery.getResultList(); for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName()); + LOGGER.debug("Name:{}", foo.getName()); if (foo.getBar() != null) { - System.out.print("-------BarId:" + foo.getBar().getId()); + LOGGER.debug("-------BarId:{}", foo.getBar().getId()); } } } @@ -80,9 +84,9 @@ public class FooServiceSortingIntegrationTest { final Query barQuery = entityManager.createQuery(jql); final List barList = barQuery.getResultList(); for (final Bar bar : barList) { - System.out.println("Bar Id:" + bar.getId()); + LOGGER.debug("Bar Id:{}", bar.getId()); for (final Foo foo : bar.getFooList()) { - System.out.println("FooName:" + foo.getName()); + LOGGER.debug("FooName:{}", foo.getName()); } } } @@ -97,7 +101,7 @@ public class FooServiceSortingIntegrationTest { final TypedQuery typedQuery = entityManager.createQuery(select); final List fooList = typedQuery.getResultList(); for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "--------Id:" + foo.getId()); + LOGGER.debug("Name:{}-------Id:{}", foo.getName(), foo.getId()); } } @@ -111,7 +115,7 @@ public class FooServiceSortingIntegrationTest { final TypedQuery typedQuery = entityManager.createQuery(select); final List fooList = typedQuery.getResultList(); for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId()); + LOGGER.debug("Name:{}-------Id:{}", foo.getName(), foo.getId()); } } diff --git a/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java index 103321fc64..b19259d9df 100644 --- a/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java @@ -13,6 +13,8 @@ import com.baeldung.config.PersistenceJPAConfig; import com.baeldung.persistence.model.Foo; import org.junit.Test; import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; @@ -24,6 +26,8 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @DirtiesContext public class FooServiceSortingWitNullsManualIntegrationTest { + private static final Logger LOGGER = LoggerFactory.getLogger(FooServiceSortingWitNullsManualIntegrationTest.class); + @PersistenceContext private EntityManager entityManager; @@ -43,7 +47,7 @@ public class FooServiceSortingWitNullsManualIntegrationTest { final List fooList = sortQuery.getResultList(); assertNull(fooList.get(fooList.toArray().length - 1).getName()); for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName()); + LOGGER.debug("Name:{}", foo.getName()); } } @@ -57,7 +61,7 @@ public class FooServiceSortingWitNullsManualIntegrationTest { final List fooList = sortQuery.getResultList(); assertNull(fooList.get(0).getName()); for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName()); + LOGGER.debug("Name:{}", foo.getName()); } } diff --git a/persistence-modules/spring-jpa/src/test/resources/persistence-student.properties b/persistence-modules/spring-jpa/src/test/resources/persistence-student.properties index 3b6b580630..9ca389d6ab 100644 --- a/persistence-modules/spring-jpa/src/test/resources/persistence-student.properties +++ b/persistence-modules/spring-jpa/src/test/resources/persistence-student.properties @@ -2,7 +2,7 @@ jdbc.driverClassName=org.h2.Driver jdbc.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1 hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true +hibernate.show_sql=false hibernate.hbm2ddl.auto=create hibernate.cache.use_second_level_cache=false diff --git a/pom.xml b/pom.xml index 6d10dcb668..e18e571372 100644 --- a/pom.xml +++ b/pom.xml @@ -790,6 +790,9 @@ **/*IntegrationTest.java **/*IntTest.java + + ${tutorialsproject.basedir}/logback-config.xml + @@ -1047,6 +1050,9 @@ **/*IntegrationTest.java **/*IntTest.java + + ${tutorialsproject.basedir}/logback-config.xml + From 817647d43d7b99766793eba17978568bcb25503a Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sat, 20 Nov 2021 13:17:25 +0530 Subject: [PATCH 08/65] explicit h2 version for hibernate-mapping --- persistence-modules/hibernate-mapping/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml index 805402951e..e837f57d8f 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -75,6 +75,7 @@ + 1.4.197 5.4.12.Final 2.10.4 3.8.0 From 569e1fc8c78d4d01b3f2e70c77e65c766dfb00a1 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 21 Nov 2021 13:32:09 +0530 Subject: [PATCH 09/65] explicit h2 version for spring-data-eclipselink and core-java-lang-oop-modifiers --- core-java-modules/core-java-lang-oop-modifiers/pom.xml | 1 + persistence-modules/spring-data-eclipselink/pom.xml | 1 + 2 files changed, 2 insertions(+) diff --git a/core-java-modules/core-java-lang-oop-modifiers/pom.xml b/core-java-modules/core-java-lang-oop-modifiers/pom.xml index 70c70608eb..3cdcc3a481 100644 --- a/core-java-modules/core-java-lang-oop-modifiers/pom.xml +++ b/core-java-modules/core-java-lang-oop-modifiers/pom.xml @@ -30,6 +30,7 @@ 3.10.0 + 1.4.197 \ No newline at end of file diff --git a/persistence-modules/spring-data-eclipselink/pom.xml b/persistence-modules/spring-data-eclipselink/pom.xml index a344d64864..561d144fe3 100644 --- a/persistence-modules/spring-data-eclipselink/pom.xml +++ b/persistence-modules/spring-data-eclipselink/pom.xml @@ -66,6 +66,7 @@ 1.5.9.RELEASE 2.7.0 + 1.4.197 \ No newline at end of file From 8c30cbb5e3b99115d9e155e5e5a689044e215cbe Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 21 Nov 2021 17:58:26 +0530 Subject: [PATCH 10/65] removed explicit h2.version as parent now is at the required 1.4.200 --- libraries-testing/pom.xml | 1 - persistence-modules/core-java-persistence-2/pom.xml | 1 - persistence-modules/core-java-persistence/pom.xml | 1 - persistence-modules/hibernate-annotations/pom.xml | 1 - persistence-modules/jooq/pom.xml | 1 - persistence-modules/r2dbc/pom.xml | 1 - persistence-modules/spring-data-mongodb-reactive/pom.xml | 2 -- persistence-modules/spring-persistence-simple/pom.xml | 1 - spring-5-data-reactive/pom.xml | 2 -- spring-boot-modules/spring-boot-libraries/pom.xml | 2 -- spring-boot-modules/spring-boot-react/pom.xml | 2 -- 11 files changed, 15 deletions(-) diff --git a/libraries-testing/pom.xml b/libraries-testing/pom.xml index d7b4a88369..7df5750134 100644 --- a/libraries-testing/pom.xml +++ b/libraries-testing/pom.xml @@ -208,7 +208,6 @@ 4.1.1 3.14.0 2.0.0.0 - 1.4.200 2.7.0 3.14.0 1.8 diff --git a/persistence-modules/core-java-persistence-2/pom.xml b/persistence-modules/core-java-persistence-2/pom.xml index 15676bf03e..780c1fcfca 100644 --- a/persistence-modules/core-java-persistence-2/pom.xml +++ b/persistence-modules/core-java-persistence-2/pom.xml @@ -44,7 +44,6 @@ - 1.4.200 8.4.1.jre11 10.2.0.4.0 8.0.22 diff --git a/persistence-modules/core-java-persistence/pom.xml b/persistence-modules/core-java-persistence/pom.xml index 96f8cef310..17d7db28d9 100644 --- a/persistence-modules/core-java-persistence/pom.xml +++ b/persistence-modules/core-java-persistence/pom.xml @@ -61,7 +61,6 @@ - 1.4.200 3.10.0 2.4.0 3.2.0 diff --git a/persistence-modules/hibernate-annotations/pom.xml b/persistence-modules/hibernate-annotations/pom.xml index e5c19915a4..634cd64cca 100644 --- a/persistence-modules/hibernate-annotations/pom.xml +++ b/persistence-modules/hibernate-annotations/pom.xml @@ -45,7 +45,6 @@ 5.4.7.Final - 1.4.200 true 2.1.7.RELEASE 5.4.7.Final diff --git a/persistence-modules/jooq/pom.xml b/persistence-modules/jooq/pom.xml index c66be9db77..b9229377ab 100644 --- a/persistence-modules/jooq/pom.xml +++ b/persistence-modules/jooq/pom.xml @@ -45,7 +45,6 @@ 3.13.4 - 1.4.200 \ No newline at end of file diff --git a/persistence-modules/r2dbc/pom.xml b/persistence-modules/r2dbc/pom.xml index ae4ca4d91d..1ce5eb3e96 100644 --- a/persistence-modules/r2dbc/pom.xml +++ b/persistence-modules/r2dbc/pom.xml @@ -63,7 +63,6 @@ 0.8.1.RELEASE - 1.4.200 \ No newline at end of file diff --git a/persistence-modules/spring-data-mongodb-reactive/pom.xml b/persistence-modules/spring-data-mongodb-reactive/pom.xml index c1398ca80d..2220418ac3 100644 --- a/persistence-modules/spring-data-mongodb-reactive/pom.xml +++ b/persistence-modules/spring-data-mongodb-reactive/pom.xml @@ -71,7 +71,6 @@ com.h2database h2 - ${h2.version} org.apache.httpcomponents @@ -126,7 +125,6 @@ 5.2.2.RELEASE 4.5.2 - 1.4.200 3.3.1.RELEASE diff --git a/persistence-modules/spring-persistence-simple/pom.xml b/persistence-modules/spring-persistence-simple/pom.xml index 437a439b99..ec7c8bd3a0 100644 --- a/persistence-modules/spring-persistence-simple/pom.xml +++ b/persistence-modules/spring-persistence-simple/pom.xml @@ -92,7 +92,6 @@ 2.2 1.3 2.2.7.RELEASE - 1.4.200 0.23.0 diff --git a/spring-5-data-reactive/pom.xml b/spring-5-data-reactive/pom.xml index 3a9651de39..c145992737 100644 --- a/spring-5-data-reactive/pom.xml +++ b/spring-5-data-reactive/pom.xml @@ -72,7 +72,6 @@ com.h2database h2 - ${h2.version} org.apache.httpcomponents @@ -135,7 +134,6 @@ 1.0.0.RELEASE 0.8.1.RELEASE 4.5.2 - 1.4.200 1.5.23 3.3.1.RELEASE diff --git a/spring-boot-modules/spring-boot-libraries/pom.xml b/spring-boot-modules/spring-boot-libraries/pom.xml index ad00629e14..8d1fb57997 100644 --- a/spring-boot-modules/spring-boot-libraries/pom.xml +++ b/spring-boot-modules/spring-boot-libraries/pom.xml @@ -83,7 +83,6 @@ com.h2database h2 - ${h2.version} @@ -240,7 +239,6 @@ 2.2.4 2.3.2 0.23.0 - 1.4.200 2.1.0 1.5-beta1 2.1 diff --git a/spring-boot-modules/spring-boot-react/pom.xml b/spring-boot-modules/spring-boot-react/pom.xml index 3e8a9a7bd1..d515aed6ce 100644 --- a/spring-boot-modules/spring-boot-react/pom.xml +++ b/spring-boot-modules/spring-boot-react/pom.xml @@ -25,7 +25,6 @@ com.h2database h2 - ${h2.version} runtime @@ -128,7 +127,6 @@ v14.18.0 v1.12.1 2.4.4 - 1.4.200 1.0.2 From 9f5371404d3452040571b74a9e13f7bc7fa158e8 Mon Sep 17 00:00:00 2001 From: chaos2418 <> Date: Tue, 23 Nov 2021 09:38:47 +0530 Subject: [PATCH 11/65] JAVA-8638: addressing PR review comments. --- .../EnversFooBarAuditIntegrationTest.java | 37 ++++++------------- .../persistence/hibernate/FooFixtures.java | 9 ++--- .../FooSortingPersistenceIntegrationTest.java | 21 ++++------- .../query/UserRepositoryIntegrationTest.java | 23 +++++++----- .../immutable/util/HibernateUtil.java | 3 +- 5 files changed, 36 insertions(+), 57 deletions(-) diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java index 7397a61cac..444324dafc 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java @@ -123,39 +123,24 @@ public class EnversFooBarAuditIntegrationTest { assertNotNull(barRevisionList); assertEquals(4, barRevisionList.size()); - assertEquals("BAR", barRevisionList.get(0) - .getName()); - assertEquals("BAR", barRevisionList.get(1) - .getName()); - assertEquals("BAR1", barRevisionList.get(2) - .getName()); - assertEquals("BAR1", barRevisionList.get(3) - .getName()); + assertEquals("BAR", barRevisionList.get(0).getName()); + assertEquals("BAR", barRevisionList.get(1).getName()); + assertEquals("BAR1", barRevisionList.get(2).getName()); + assertEquals("BAR1", barRevisionList.get(3).getName()); - assertEquals(1, barRevisionList.get(0) - .getFooSet() - .size()); - assertEquals(2, barRevisionList.get(1) - .getFooSet() - .size()); - assertEquals(2, barRevisionList.get(2) - .getFooSet() - .size()); - assertEquals(3, barRevisionList.get(3) - .getFooSet() - .size()); + assertEquals(1, barRevisionList.get(0).getFooSet().size()); + assertEquals(2, barRevisionList.get(1).getFooSet().size()); + assertEquals(2, barRevisionList.get(2).getFooSet().size()); + assertEquals(3, barRevisionList.get(3).getFooSet().size()); // test Foo revisions fooRevisionList = fooService.getRevisions(); assertNotNull(fooRevisionList); assertEquals(3, fooRevisionList.size()); - assertEquals("FOO1", fooRevisionList.get(0) - .getName()); - assertEquals("FOO2", fooRevisionList.get(1) - .getName()); - assertEquals("FOO3", fooRevisionList.get(2) - .getName()); + assertEquals("FOO1", fooRevisionList.get(0).getName()); + assertEquals("FOO2", fooRevisionList.get(1).getName()); + assertEquals("FOO3", fooRevisionList.get(2).getName()); } } diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java index e0bd8a4f98..a7763bb0f8 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java @@ -46,10 +46,8 @@ public class FooFixtures { } foo2.setBar(bar); session.save(foo2); - bar.getFooSet() - .add(foo); - bar.getFooSet() - .add(foo2); + bar.getFooSet().add(foo); + bar.getFooSet().add(foo2); session.merge(bar); } tx.commit(); @@ -80,8 +78,7 @@ public class FooFixtures { final Foo foo = new Foo(); foo.setName("Foo_" + (i + 120)); final Bar bar = new Bar("bar_" + i); - bar.getFooSet() - .add(foo); + bar.getFooSet().add(foo); foo.setBar(bar); fooList.add(foo); diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java index fe73ddba3f..6078eb3af0 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java @@ -50,8 +50,7 @@ public class FooSortingPersistenceIntegrationTest { @After public void after() { - session.getTransaction() - .commit(); + session.getTransaction().commit(); session.close(); } @@ -71,8 +70,7 @@ public class FooSortingPersistenceIntegrationTest { final Query query = session.createQuery(hql); final List fooList = query.list(); - assertNull(fooList.get(fooList.toArray().length - 1) - .getName()); + assertNull(fooList.get(fooList.toArray().length - 1).getName()); for (final Foo foo : fooList) { LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId()); } @@ -83,8 +81,7 @@ public class FooSortingPersistenceIntegrationTest { final String hql = "FROM Foo f ORDER BY f.name NULLS FIRST"; final Query query = session.createQuery(hql); final List fooList = query.list(); - assertNull(fooList.get(0) - .getName()); + assertNull(fooList.get(0).getName()); for (final Foo foo : fooList) { LOGGER.debug("Name: {}", foo.getName()); @@ -145,11 +142,9 @@ public class FooSortingPersistenceIntegrationTest { @Test public final void whenCriteriaSortingStringNullsLastAsc_thenNullsLast() { final Criteria criteria = session.createCriteria(Foo.class, "FOO"); - criteria.addOrder(Order.asc("name") - .nulls(NullPrecedence.LAST)); + criteria.addOrder(Order.asc("name").nulls(NullPrecedence.LAST)); final List fooList = criteria.list(); - assertNull(fooList.get(fooList.toArray().length - 1) - .getName()); + assertNull(fooList.get(fooList.toArray().length - 1).getName()); for (final Foo foo : fooList) { LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName()); } @@ -158,11 +153,9 @@ public class FooSortingPersistenceIntegrationTest { @Test public final void whenCriteriaSortingStringNullsFirstDesc_thenNullsFirst() { final Criteria criteria = session.createCriteria(Foo.class, "FOO"); - criteria.addOrder(Order.desc("name") - .nulls(NullPrecedence.FIRST)); + criteria.addOrder(Order.desc("name").nulls(NullPrecedence.FIRST)); final List fooList = criteria.list(); - assertNull(fooList.get(0) - .getName()); + assertNull(fooList.get(0).getName()); for (final Foo foo : fooList) { LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName()); } diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/UserRepositoryIntegrationTest.java index df07c74c5a..19760f2bfe 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/UserRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/UserRepositoryIntegrationTest.java @@ -40,42 +40,46 @@ public class UserRepositoryIntegrationTest { @Test public void whenFindAllSortedByNameThenAllSorted() { List allUsersSortedByName = userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); - assertThat(allUsersSortedByName).extracting("name") + assertThat(allUsersSortedByName) + .extracting("name") .containsSequence("Bob", "Cindy", "John"); } @Test public void whenFindAllSortedByNameLengthThenException() { - assertThatThrownBy(() -> userRepository.findAll(Sort.by("LENGTH(name)"))).isInstanceOf(PropertyReferenceException.class); + assertThatThrownBy(() -> userRepository.findAll(Sort.by("LENGTH(name)"))) + .isInstanceOf(PropertyReferenceException.class); } @Test public void whenFindAllUsersSortedByNameThenAllSorted() { List allUsersSortedByName = userRepository.findAllUsers(Sort.by(Sort.Direction.ASC, "name")); - assertThat(allUsersSortedByName).extracting("name") + assertThat(allUsersSortedByName) + .extracting("name") .containsSequence("Bob", "Cindy", "John"); } @Test public void whenFindAllUsersSortedByNameLengthThenAllSorted() { List allUsersSortedByName = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)")); - assertThat(allUsersSortedByName).extracting("name") + assertThat(allUsersSortedByName) + .extracting("name") .containsSequence("Bob", "John", "Cindy"); } @Test public void whenFindAllUsersWithPaginationThenPaginated() { Page page = userRepository.findAllUsersWithPagination(PageRequest.of(0, 1)); - assertThat(page.stream() - .map(User::getId)).hasSize(1) + assertThat(page.stream().map(User::getId)) + .hasSize(1) .containsOnly(1); } @Test public void whenFindAllUsersWithPaginationNativeThenPaginated() { Page page = userRepository.findAllUsersWithPaginationNative(PageRequest.of(1, 1)); - assertThat(page.stream() - .map(User::getId)).hasSize(1) + assertThat(page.stream().map(User::getId)) + .hasSize(1) .containsOnly(2); } @@ -122,7 +126,8 @@ public class UserRepositoryIntegrationTest { @Test public void whenFindUserByNameListThenAllFound() { List users = userRepository.findUserByNameList(Arrays.asList("Bob", "Cindy")); - assertThat(users).extracting("name") + assertThat(users) + .extracting("name") .containsOnly("Bob", "Cindy"); } diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java index 25d7de4b07..aee4206e53 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java @@ -21,8 +21,7 @@ public class HibernateUtil { configuration.addAnnotatedClass(Event.class); configuration.addAnnotatedClass(EventGeneratedId.class); configuration.configure("immutable.cfg.xml"); - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) - .build(); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); return configuration.buildSessionFactory(serviceRegistry); } catch (Throwable ex) { LOGGER.debug("Initial SessionFactory creation failed.", ex); From 5c2f72ffb34a9e0c4317615db2ac699d6d33a1ec Mon Sep 17 00:00:00 2001 From: chaos2418 <> Date: Tue, 23 Nov 2021 19:12:32 +0530 Subject: [PATCH 12/65] JAVA-8638: addressing PR review comments. --- .../src/main/resources/application.properties | 2 +- .../java/com/baeldung/exists/CarRepositoryIntegrationTest.java | 1 - .../src/main/resources/application.properties | 2 +- .../baeldung/boot/daos/InventoryRepositoryIntegrationTest.java | 2 +- .../derivedquery/repository/UserRepositoryIntegrationTest.java | 2 +- .../java/com/baeldung/like/MovieRepositoryIntegrationTest.java | 2 +- .../com/baeldung/repository/FruitPopulatorIntegrationTest.java | 2 +- .../com/baeldung/repository/SongRepositoryIntegrationTest.java | 2 +- 8 files changed, 7 insertions(+), 8 deletions(-) diff --git a/persistence-modules/spring-data-jpa-query/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-query/src/main/resources/application.properties index 9bb870895d..eb0e519ef0 100644 --- a/persistence-modules/spring-data-jpa-query/src/main/resources/application.properties +++ b/persistence-modules/spring-data-jpa-query/src/main/resources/application.properties @@ -1,2 +1,2 @@ -spring.jpa.show-sql=true +spring.jpa.show-sql=false spring.jpa.defer-datasource-initialization=true \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java index c740fd7abd..53f22ed0d1 100644 --- a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java @@ -20,7 +20,6 @@ import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatc @RunWith(SpringRunner.class) @SpringBootTest(classes = {Application.class}) -@TestPropertySource(properties = {"spring.jpa.show-sql=false"}) public class CarRepositoryIntegrationTest { @Autowired diff --git a/persistence-modules/spring-data-jpa-repo/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-repo/src/main/resources/application.properties index ae1afe6e98..1a370121c5 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/resources/application.properties +++ b/persistence-modules/spring-data-jpa-repo/src/main/resources/application.properties @@ -1,4 +1,4 @@ -spring.jpa.show-sql=true +spring.jpa.show-sql=false spring.jpa.defer-datasource-initialization=true #MySql #spring.datasource.url=jdbc:mysql://localhost:3306/baeldung diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java index 9201df8990..e4bd3dabff 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java @@ -19,7 +19,7 @@ import com.baeldung.Application; import com.baeldung.boot.domain.MerchandiseEntity; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, properties = {"spring.jpa.show-sql=false"}) +@SpringBootTest(classes = Application.class) public class InventoryRepositoryIntegrationTest { private static final String ORIGINAL_TITLE = "Pair of Pants"; diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java index 41c171e449..2a6e166b88 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java @@ -17,7 +17,7 @@ import java.util.List; import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) -@SpringBootTest(classes = QueryApplication.class, properties = {"spring.jpa.show-sql=false"}) +@SpringBootTest(classes = QueryApplication.class) public class UserRepositoryIntegrationTest { private static final String USER_NAME_ADAM = "Adam"; diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java index a4a1982df8..cc96b638ab 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java @@ -16,7 +16,7 @@ import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TES @RunWith(SpringRunner.class) @Sql(scripts = { "/test-movie-data.sql" }) -@SpringBootTest(classes = LikeApplication.class, properties = {"spring.jpa.show-sql=false"}) +@SpringBootTest(classes = LikeApplication.class) @Sql(scripts = "/test-movie-cleanup.sql", executionPhase = AFTER_TEST_METHOD) public class MovieRepositoryIntegrationTest { @Autowired diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java index d0b2ab8dd7..4d3661e717 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.entity.Fruit; @RunWith(SpringRunner.class) -@SpringBootTest(properties = {"spring.jpa.show-sql=false"}) +@SpringBootTest public class FruitPopulatorIntegrationTest { @Autowired diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java index 619b410f0d..19362acd44 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java @@ -16,7 +16,7 @@ import com.baeldung.entity.Song; import com.baeldung.repository.SongRepository; @RunWith(SpringRunner.class) -@SpringBootTest(properties = {"spring.jpa.show-sql=false"}) +@SpringBootTest @Sql(scripts = { "/test-song-data.sql" }) public class SongRepositoryIntegrationTest { From 18d9b86fe2b9e3ce496b5042ca77431e2fd32cb6 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 24 Nov 2021 09:06:52 +0530 Subject: [PATCH 13/65] Fix integration build --- .../src/test/resources/hibernate-pessimistic-locking.properties | 2 +- testing-modules/junit-5-basics/pom.xml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/persistence-modules/hibernate-jpa/src/test/resources/hibernate-pessimistic-locking.properties b/persistence-modules/hibernate-jpa/src/test/resources/hibernate-pessimistic-locking.properties index 4f1ff5e93a..342f7b0bf5 100644 --- a/persistence-modules/hibernate-jpa/src/test/resources/hibernate-pessimistic-locking.properties +++ b/persistence-modules/hibernate-jpa/src/test/resources/hibernate-pessimistic-locking.properties @@ -1,5 +1,5 @@ hibernate.connection.driver_class=org.h2.Driver -hibernate.connection.url=jdbc:h2:mem:mydb3;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100;MVCC=FALSE +hibernate.connection.url=jdbc:h2:mem:mydb3;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100 hibernate.connection.username=sa hibernate.connection.autocommit=true hibernate.dialect=org.hibernate.dialect.H2Dialect diff --git a/testing-modules/junit-5-basics/pom.xml b/testing-modules/junit-5-basics/pom.xml index 62dc4321a8..4dcba2db96 100644 --- a/testing-modules/junit-5-basics/pom.xml +++ b/testing-modules/junit-5-basics/pom.xml @@ -124,6 +124,7 @@ 5.0.6.RELEASE + 1.4.197 \ No newline at end of file From 6de241f917f34abdcee65d1effe5c21e87119740 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 24 Nov 2021 19:40:29 +0800 Subject: [PATCH 14/65] Update README.md --- linux-bash/text/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/linux-bash/text/README.md b/linux-bash/text/README.md index 1c27abc8c6..5423ddf916 100644 --- a/linux-bash/text/README.md +++ b/linux-bash/text/README.md @@ -1,4 +1,3 @@ ### Relevant Articles: -- [Linux Commands – Remove All Text After X](https://www.baeldung.com/linux/remove-text-after-x-in-file) - [Linux Commands for Appending Multiple Lines to a File](https://www.baeldung.com/linux/appending-multiple-lines-to-file2) From ce2820897871bbded5109c96ef7d8023037c5c03 Mon Sep 17 00:00:00 2001 From: Ralf Ueberfuhr Date: Wed, 24 Nov 2021 12:56:12 +0100 Subject: [PATCH 15/65] BAEL-5036: Deactivate JDK8 build for Quarkus 2.x project --- pom.xml | 2 +- quarkus-jandex/README.md | 3 --- quarkus-jandex/pom.xml | 28 +++++++++++++++------------- 3 files changed, 16 insertions(+), 17 deletions(-) delete mode 100644 quarkus-jandex/README.md diff --git a/pom.xml b/pom.xml index f51491137e..cdad7ed8ea 100644 --- a/pom.xml +++ b/pom.xml @@ -534,7 +534,6 @@ quarkus quarkus-extension - quarkus-jandex rabbitmq @@ -1310,6 +1309,7 @@ core-java-modules/multimodulemavenproject persistence-modules/sirix quarkus-vs-springboot + quarkus-jandex spring-boot-modules/spring-boot-cassandre diff --git a/quarkus-jandex/README.md b/quarkus-jandex/README.md deleted file mode 100644 index a03cdc708f..0000000000 --- a/quarkus-jandex/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Create a Jandex index in Quarkus for classes in a external module](https://www.baeldung.com/quarkus-jandex) diff --git a/quarkus-jandex/pom.xml b/quarkus-jandex/pom.xml index e8e66b44b1..eb7f308599 100644 --- a/quarkus-jandex/pom.xml +++ b/quarkus-jandex/pom.xml @@ -15,20 +15,8 @@ hello-sender-undetected hello-app - - - 3.8.1 - true - 11 - 11 - UTF-8 - UTF-8 - quarkus-bom - io.quarkus.platform - 2.3.0.Final - 3.0.0-M5 - + ${quarkus.platform.group-id} @@ -39,4 +27,18 @@ + + + 3.8.1 + true + 11 + 11 + UTF-8 + UTF-8 + quarkus-bom + io.quarkus.platform + 2.4.2.Final + 3.0.0-M5 + + From 5725ff4b0c3c361e373c32df27d50427d481d197 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 24 Nov 2021 19:56:47 +0800 Subject: [PATCH 16/65] Delete README.md --- guest/core-kotlin/README.md | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 guest/core-kotlin/README.md diff --git a/guest/core-kotlin/README.md b/guest/core-kotlin/README.md deleted file mode 100644 index fad62ebea6..0000000000 --- a/guest/core-kotlin/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Kotlin vs Java](https://www.baeldung.com/kotlin/vs-java) From 9ae3f55ece8e89a8ca9b7ab02f8235f47406edb8 Mon Sep 17 00:00:00 2001 From: Ralf Ueberfuhr Date: Wed, 24 Nov 2021 12:57:12 +0100 Subject: [PATCH 17/65] BAEL-5036: Deactivate JDK8 build for Quarkus 2.x project --- pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/pom.xml b/pom.xml index cdad7ed8ea..f001dfd357 100644 --- a/pom.xml +++ b/pom.xml @@ -1004,7 +1004,6 @@ quarkus quarkus-extension - quarkus-jandex rabbitmq From 33656e5c85001a6128ceeb673c9069e5af955d95 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 24 Nov 2021 20:03:28 +0800 Subject: [PATCH 18/65] Update README.md --- .../src/test/java/com/baeldung/applicationcontext/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-core/src/test/java/com/baeldung/applicationcontext/README.md b/spring-core/src/test/java/com/baeldung/applicationcontext/README.md index 211007e0cf..a626417d47 100644 --- a/spring-core/src/test/java/com/baeldung/applicationcontext/README.md +++ b/spring-core/src/test/java/com/baeldung/applicationcontext/README.md @@ -1,3 +1,3 @@ ### Relevant Articles: -- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets) + - [Intro to the Spring ClassPathXmlApplicationContext](http://www.baeldung.com/spring-classpathxmlapplicationcontext) From fcd5717d6f43b6d5bc411c062f729fac3ce8fec5 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 24 Nov 2021 20:06:53 +0800 Subject: [PATCH 19/65] Update README.md --- core-java-modules/core-java-string-operations-2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-string-operations-2/README.md b/core-java-modules/core-java-string-operations-2/README.md index d66515d372..f95b002906 100644 --- a/core-java-modules/core-java-string-operations-2/README.md +++ b/core-java-modules/core-java-string-operations-2/README.md @@ -12,5 +12,5 @@ This module contains articles about string operations. - [L-Trim and R-Trim Alternatives in Java](https://www.baeldung.com/java-trim-alternatives) - [Encode a String to UTF-8 in Java](https://www.baeldung.com/java-string-encode-utf-8) - [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding) -- [Convert Hex to ASCII in Java](https://www.baeldung.com/java-convert-hex-to-ascii) #remove additional readme file +- [Convert Hex to ASCII in Java](https://www.baeldung.com/java-convert-hex-to-ascii) - More articles: [[<-- prev]](../core-java-string-operations) From 15a103b4f8e46253d8c27b24bee088ec10074764 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Wed, 24 Nov 2021 13:20:20 +0100 Subject: [PATCH 20/65] JAVA-8667: Remove hamcrest dependency declarations from the child modules --- core-java-modules/core-java-collections-maps-4/pom.xml | 6 ------ .../core-java-string-conversions-2/pom.xml | 6 ------ core-java-modules/core-java-string-conversions/pom.xml | 6 ------ .../core-java-string-operations-2/pom.xml | 6 ------ ethereum/pom.xml | 6 ------ java-collections-conversions-2/pom.xml | 6 ------ libraries-testing/pom.xml | 1 - libraries/pom.xml | 7 ------- parent-java/pom.xml | 1 - spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml | 10 ---------- spring-cloud/spring-cloud-zuul/spring-zuul-ui/pom.xml | 5 ----- spring-core-2/pom.xml | 5 ----- .../spring-security-web-boot-1/pom.xml | 5 ----- .../spring-security-web-boot-2/pom.xml | 5 ----- .../spring-security-web-rest-custom/pom.xml | 5 ----- spring-web-modules/spring-rest-query-language/pom.xml | 5 ----- spring-web-modules/spring-rest-simple/pom.xml | 5 ----- spring-web-modules/spring-rest-testing/pom.xml | 5 ----- spring-web-modules/spring-resttemplate/pom.xml | 5 ----- testing-modules/selenium-junit-testng/pom.xml | 5 ----- testing-modules/testing-assertions/pom.xml | 6 ------ 21 files changed, 111 deletions(-) diff --git a/core-java-modules/core-java-collections-maps-4/pom.xml b/core-java-modules/core-java-collections-maps-4/pom.xml index 2109804ff0..c5296e9a43 100644 --- a/core-java-modules/core-java-collections-maps-4/pom.xml +++ b/core-java-modules/core-java-collections-maps-4/pom.xml @@ -28,12 +28,6 @@ ${junit.version} test - - org.hamcrest - hamcrest-all - ${hamcrest-all.version} - test - diff --git a/core-java-modules/core-java-string-conversions-2/pom.xml b/core-java-modules/core-java-string-conversions-2/pom.xml index f97443d9ca..45eb0dc2e2 100644 --- a/core-java-modules/core-java-string-conversions-2/pom.xml +++ b/core-java-modules/core-java-string-conversions-2/pom.xml @@ -20,12 +20,6 @@ guava ${guava.version} - - org.hamcrest - hamcrest - ${hamcrest.version} - test - com.ibm.icu icu4j diff --git a/core-java-modules/core-java-string-conversions/pom.xml b/core-java-modules/core-java-string-conversions/pom.xml index 148f04101f..8ed3e1d628 100644 --- a/core-java-modules/core-java-string-conversions/pom.xml +++ b/core-java-modules/core-java-string-conversions/pom.xml @@ -35,12 +35,6 @@ guava ${guava.version} - - org.hamcrest - hamcrest - ${hamcrest.version} - test - diff --git a/core-java-modules/core-java-string-operations-2/pom.xml b/core-java-modules/core-java-string-operations-2/pom.xml index 0d31486759..848a358aa2 100644 --- a/core-java-modules/core-java-string-operations-2/pom.xml +++ b/core-java-modules/core-java-string-operations-2/pom.xml @@ -45,12 +45,6 @@ javax.el ${javax.el.version} - - org.hamcrest - hamcrest - ${hamcrest.version} - test - org.openjdk.jmh jmh-core diff --git a/ethereum/pom.xml b/ethereum/pom.xml index 95dd1c0955..d2b05222c3 100644 --- a/ethereum/pom.xml +++ b/ethereum/pom.xml @@ -144,12 +144,6 @@ test - - org.hamcrest - hamcrest - ${hamcrest.version} - test - com.jayway.jsonpath json-path diff --git a/java-collections-conversions-2/pom.xml b/java-collections-conversions-2/pom.xml index 694b416169..9f8ef7addc 100644 --- a/java-collections-conversions-2/pom.xml +++ b/java-collections-conversions-2/pom.xml @@ -26,12 +26,6 @@ modelmapper ${modelmapper.version} - - org.hamcrest - hamcrest - ${hamcrest.version} - test - io.vavr vavr diff --git a/libraries-testing/pom.xml b/libraries-testing/pom.xml index d62d094f08..0815c94dbf 100644 --- a/libraries-testing/pom.xml +++ b/libraries-testing/pom.xml @@ -118,7 +118,6 @@ ${spring-mock-mvc.version} test - org.hamcrest java-hamcrest diff --git a/libraries/pom.xml b/libraries/pom.xml index b0a0aa22ea..7bef56deb0 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -167,12 +167,6 @@ google-oauth-client-jetty ${google-api.version} - - org.hamcrest - hamcrest-all - ${hamcrest-all.version} - test - @@ -279,7 +273,6 @@ 1.15 1.23.0 0.9.4.0006L - 1.3 3.2.0-m7 5.1.1 5.0.2 diff --git a/parent-java/pom.xml b/parent-java/pom.xml index 4e5081393c..808eed1c44 100644 --- a/parent-java/pom.xml +++ b/parent-java/pom.xml @@ -43,7 +43,6 @@ 31.0.1-jre 2.3.7 - 2.2 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml b/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml index 8e7b87c220..8248884632 100644 --- a/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml +++ b/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml @@ -68,16 +68,6 @@ spring-boot-starter-test ${spring-boot.version} - - org.hamcrest - hamcrest-core - ${hamcrest-core.version} - test - - - 1.3 - - \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-ui/pom.xml b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/pom.xml index 7c3f668473..c071b8863a 100644 --- a/spring-cloud/spring-cloud-zuul/spring-zuul-ui/pom.xml +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/pom.xml @@ -27,11 +27,6 @@ spring-test test - - org.hamcrest - hamcrest - test - org.mockito mockito-core diff --git a/spring-core-2/pom.xml b/spring-core-2/pom.xml index dda23c4ea4..19e7fb5f28 100644 --- a/spring-core-2/pom.xml +++ b/spring-core-2/pom.xml @@ -129,11 +129,6 @@ spring-test test - - org.hamcrest - hamcrest - test - org.mockito mockito-core diff --git a/spring-security-modules/spring-security-web-boot-1/pom.xml b/spring-security-modules/spring-security-web-boot-1/pom.xml index a376a49b4c..3f6001686d 100644 --- a/spring-security-modules/spring-security-web-boot-1/pom.xml +++ b/spring-security-modules/spring-security-web-boot-1/pom.xml @@ -59,11 +59,6 @@ postgresql runtime - - org.hamcrest - hamcrest - test - org.springframework spring-test diff --git a/spring-security-modules/spring-security-web-boot-2/pom.xml b/spring-security-modules/spring-security-web-boot-2/pom.xml index ade644741d..91b6ff8724 100644 --- a/spring-security-modules/spring-security-web-boot-2/pom.xml +++ b/spring-security-modules/spring-security-web-boot-2/pom.xml @@ -59,11 +59,6 @@ postgresql runtime - - org.hamcrest - hamcrest - test - org.springframework spring-test diff --git a/spring-security-modules/spring-security-web-rest-custom/pom.xml b/spring-security-modules/spring-security-web-rest-custom/pom.xml index 85e50412ad..1403154767 100644 --- a/spring-security-modules/spring-security-web-rest-custom/pom.xml +++ b/spring-security-modules/spring-security-web-rest-custom/pom.xml @@ -116,11 +116,6 @@ ${commons-lang3.version} - - org.hamcrest - hamcrest - test - org.mockito mockito-core diff --git a/spring-web-modules/spring-rest-query-language/pom.xml b/spring-web-modules/spring-rest-query-language/pom.xml index c5a8c172f3..65f28f5be0 100644 --- a/spring-web-modules/spring-rest-query-language/pom.xml +++ b/spring-web-modules/spring-rest-query-language/pom.xml @@ -181,11 +181,6 @@ spring-test test - - org.hamcrest - hamcrest - test - org.mockito mockito-core diff --git a/spring-web-modules/spring-rest-simple/pom.xml b/spring-web-modules/spring-rest-simple/pom.xml index 69d88d6456..2f8d6eac27 100644 --- a/spring-web-modules/spring-rest-simple/pom.xml +++ b/spring-web-modules/spring-rest-simple/pom.xml @@ -120,11 +120,6 @@ ${com.squareup.okhttp3.version} - - org.hamcrest - hamcrest - test - org.mockito mockito-core diff --git a/spring-web-modules/spring-rest-testing/pom.xml b/spring-web-modules/spring-rest-testing/pom.xml index dc5fdcd323..93942e97b6 100644 --- a/spring-web-modules/spring-rest-testing/pom.xml +++ b/spring-web-modules/spring-rest-testing/pom.xml @@ -165,11 +165,6 @@ spring-test test - - org.hamcrest - hamcrest - test - org.mockito mockito-core diff --git a/spring-web-modules/spring-resttemplate/pom.xml b/spring-web-modules/spring-resttemplate/pom.xml index 3066a82242..5cac186fad 100644 --- a/spring-web-modules/spring-resttemplate/pom.xml +++ b/spring-web-modules/spring-resttemplate/pom.xml @@ -108,11 +108,6 @@ ${com.squareup.okhttp3.version} - - org.hamcrest - hamcrest - test - org.mockito mockito-core diff --git a/testing-modules/selenium-junit-testng/pom.xml b/testing-modules/selenium-junit-testng/pom.xml index 0bf6f0726d..dfa19c48d4 100644 --- a/testing-modules/selenium-junit-testng/pom.xml +++ b/testing-modules/selenium-junit-testng/pom.xml @@ -31,11 +31,6 @@ testng ${testng.version} - - org.hamcrest - hamcrest-all - ${hamcrest-all.version} - ru.yandex.qatools.ashot ashot diff --git a/testing-modules/testing-assertions/pom.xml b/testing-modules/testing-assertions/pom.xml index 12af95b575..689ca35733 100644 --- a/testing-modules/testing-assertions/pom.xml +++ b/testing-modules/testing-assertions/pom.xml @@ -18,12 +18,6 @@ logback-classic ${logback.version} - - org.hamcrest - hamcrest-all - ${hamcrest-all.version} - test - org.apache.commons commons-collections4 From 195ab27fe3635b23af14644bfaec1dbc75393cda Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Wed, 24 Nov 2021 13:07:45 +0000 Subject: [PATCH 21/65] [BAEL-44334] Enhance the process test to shutdown ExecutorService --- .../shell/JavaProcessUnitIntegrationTest.java | 43 ++++++++++++++++--- 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/core-java-modules/core-java-os/src/test/java/com/baeldung/shell/JavaProcessUnitIntegrationTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/shell/JavaProcessUnitIntegrationTest.java index 53e9364207..9d24dd1578 100644 --- a/core-java-modules/core-java-os/src/test/java/com/baeldung/shell/JavaProcessUnitIntegrationTest.java +++ b/core-java-modules/core-java-os/src/test/java/com/baeldung/shell/JavaProcessUnitIntegrationTest.java @@ -1,12 +1,23 @@ -package com.baeldung.java.shell; +package com.baeldung.shell; +import org.junit.After; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import java.util.function.Consumer; +import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + public class JavaProcessUnitIntegrationTest { private static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows"); @@ -29,6 +40,18 @@ public class JavaProcessUnitIntegrationTest { private String homeDirectory = System.getProperty("user.home"); + private ExecutorService executorService; + + @Before + public void setUp() { + executorService = Executors.newSingleThreadExecutor(); + } + + @After + public void tearDown() { + executorService.shutdown(); + } + @Test public void givenProcess_whenCreatingViaRuntime_shouldSucceed() throws Exception { Process process; @@ -38,9 +61,13 @@ public class JavaProcessUnitIntegrationTest { process = Runtime.getRuntime().exec(String.format("sh -c ls %s", homeDirectory)); } StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), consumer); - Executors.newSingleThreadExecutor().submit(streamGobbler); + + Future future = executorService.submit(streamGobbler); int exitCode = process.waitFor(); - Assert.assertEquals(0, exitCode); + + // verify the stream output from the process + assertDoesNotThrow(() -> future.get(10, TimeUnit.SECONDS)); + assertEquals(0, exitCode); } @Test @@ -54,8 +81,12 @@ public class JavaProcessUnitIntegrationTest { builder.directory(new File(homeDirectory)); Process process = builder.start(); StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), consumer); - Executors.newSingleThreadExecutor().submit(streamGobbler); + + Future future = executorService.submit(streamGobbler); int exitCode = process.waitFor(); - Assert.assertEquals(0, exitCode); + + // verify the stream output from the process + assertDoesNotThrow(() -> future.get(10, TimeUnit.SECONDS)); + assertEquals(0, exitCode); } } From fc41dd02beb147e656c39601b9c005fdcbf9050c Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Wed, 24 Nov 2021 22:52:41 +0100 Subject: [PATCH 22/65] JAVA-8362: Copy batchscheduler code to spring-batch-2 --- spring-batch-2/pom.xml | 9 +- .../batchscheduler/SpringBatchScheduler.java | 190 ++++++++++++++++++ .../SpringBatchSchedulerApplication.java | 14 ++ .../baeldung/batchscheduler/model/Book.java | 35 ++++ .../src/main/resources/application.properties | 7 + spring-batch-2/src/main/resources/books.csv | 4 + .../SpringBatchSchedulerIntegrationTest.java | 69 +++++++ spring-batch/repository.sqlite | Bin 73728 -> 73728 bytes 8 files changed, 326 insertions(+), 2 deletions(-) create mode 100644 spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java create mode 100644 spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchSchedulerApplication.java create mode 100644 spring-batch-2/src/main/java/com/baeldung/batchscheduler/model/Book.java create mode 100644 spring-batch-2/src/main/resources/books.csv create mode 100644 spring-batch-2/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java diff --git a/spring-batch-2/pom.xml b/spring-batch-2/pom.xml index c429c272bd..77779a0fcf 100644 --- a/spring-batch-2/pom.xml +++ b/spring-batch-2/pom.xml @@ -24,7 +24,6 @@ org.hsqldb hsqldb - ${hsqldb.version} runtime @@ -44,11 +43,17 @@ ${spring.batch.version} test + + org.awaitility + awaitility + ${awaitility.version} + test + 4.3.0 - 2.5.1 + 3.1.1 \ No newline at end of file diff --git a/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java new file mode 100644 index 0000000000..bfaa044376 --- /dev/null +++ b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java @@ -0,0 +1,190 @@ +package com.baeldung.batchscheduler; + +import com.baeldung.batchscheduler.model.Book; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.batch.core.Job; +import org.springframework.batch.core.JobExecution; +import org.springframework.batch.core.JobParametersBuilder; +import org.springframework.batch.core.Step; +import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; +import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; +import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; +import org.springframework.batch.core.launch.JobLauncher; +import org.springframework.batch.core.launch.support.SimpleJobLauncher; +import org.springframework.batch.core.repository.JobRepository; +import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean; +import org.springframework.batch.item.ItemWriter; +import org.springframework.batch.item.file.FlatFileItemReader; +import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder; +import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper; +import org.springframework.batch.support.transaction.ResourcelessTransactionManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.scheduling.TaskScheduler; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; +import org.springframework.scheduling.support.ScheduledMethodRunnable; + +import javax.sql.DataSource; +import java.util.Date; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +@Configuration +@EnableBatchProcessing +@EnableScheduling +public class SpringBatchScheduler { + + private final Logger logger = LoggerFactory.getLogger(SpringBatchScheduler.class); + + private AtomicBoolean enabled = new AtomicBoolean(true); + + private AtomicInteger batchRunCounter = new AtomicInteger(0); + + private final Map> scheduledTasks = new IdentityHashMap<>(); + + @Autowired + private JobBuilderFactory jobBuilderFactory; + + @Autowired + private StepBuilderFactory stepBuilderFactory; + + @Autowired + private JobLauncher jobLauncher; + + @Scheduled(fixedRate = 2000) + public void launchJob() throws Exception { + Date date = new Date(); + logger.debug("scheduler starts at " + date); + if (enabled.get()) { + JobExecution jobExecution = jobLauncher.run(job(), new JobParametersBuilder().addDate("launchDate", date) + .toJobParameters()); + batchRunCounter.incrementAndGet(); + logger.debug("Batch job ends with status as " + jobExecution.getStatus()); + } + logger.debug("scheduler ends "); + } + + public void stop() { + enabled.set(false); + } + + public void start() { + enabled.set(true); + } + + @Bean + public TaskScheduler poolScheduler() { + return new CustomTaskScheduler(); + } + + private class CustomTaskScheduler extends ThreadPoolTaskScheduler { + + private static final long serialVersionUID = -7142624085505040603L; + + @Override + public ScheduledFuture scheduleAtFixedRate(Runnable task, long period) { + ScheduledFuture future = super.scheduleAtFixedRate(task, period); + + ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task; + scheduledTasks.put(runnable.getTarget(), future); + + return future; + } + + } + + public void cancelFutureSchedulerTasks() { + scheduledTasks.forEach((k, v) -> { + if (k instanceof SpringBatchScheduler) { + v.cancel(false); + } + }); + } + + @Bean + public Job job() { + return jobBuilderFactory.get("job") + .start(readBooks()) + .build(); + } + +// @Bean +// public JobLauncher jobLauncher() throws Exception { +// SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); +// jobLauncher.setJobRepository(jobRepository()); +// jobLauncher.afterPropertiesSet(); +// return jobLauncher; +// } + +// @Bean +// public JobRepository jobRepository() throws Exception { +// JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); +// factory.setDataSource(dataSource()); +// factory.setDatabaseType("HSQL"); +// factory.setTransactionManager(new ResourcelessTransactionManager()); +// return factory.getObject(); +// } + +// @Bean +// public DataSource dataSource() { +// DriverManagerDataSource dataSource = new DriverManagerDataSource(); +// dataSource.setDriverClassName("org.hsqldb.jdbc.JDBCDriver"); +// dataSource.setUrl("jdbc:hsqldb:mem:testdb"); +// dataSource.setUsername("sa"); +// dataSource.setPassword(""); +// return dataSource; +// } + + @Bean + protected Step readBooks() { + return stepBuilderFactory.get("readBooks") + . chunk(2) + .reader(reader()) + .writer(writer()) + .build(); + } + + @Bean + public FlatFileItemReader reader() { + return new FlatFileItemReaderBuilder().name("bookItemReader") + .resource(new ClassPathResource("books.csv")) + .delimited() + .names(new String[] { "id", "name" }) + .fieldSetMapper(new BeanWrapperFieldSetMapper() { + { + setTargetType(Book.class); + } + }) + .build(); + } + + @Bean + public ItemWriter writer() { + return new ItemWriter() { + + @Override + public void write(List items) throws Exception { + logger.debug("writer..." + items.size()); + for (Book item : items) { + logger.debug(item.toString()); + } + + } + }; + } + + public AtomicInteger getBatchRunCounter() { + return batchRunCounter; + } + +} diff --git a/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchSchedulerApplication.java b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchSchedulerApplication.java new file mode 100644 index 0000000000..5b89163777 --- /dev/null +++ b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchSchedulerApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.batchscheduler; + +import com.baeldung.batch.SpringBootBatchProcessingApplication; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBatchSchedulerApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBatchSchedulerApplication.class, args); + } + +} diff --git a/spring-batch-2/src/main/java/com/baeldung/batchscheduler/model/Book.java b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/model/Book.java new file mode 100644 index 0000000000..7deedeb63e --- /dev/null +++ b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/model/Book.java @@ -0,0 +1,35 @@ +package com.baeldung.batchscheduler.model; + +public class Book { + private int id; + private String name; + + public Book() {} + + public Book(int id, String name) { + super(); + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String toString() { + return "Book [id=" + id + ", name=" + name + "]"; + } + +} diff --git a/spring-batch-2/src/main/resources/application.properties b/spring-batch-2/src/main/resources/application.properties index 0b8c56d3f8..5b34d9e93b 100644 --- a/spring-batch-2/src/main/resources/application.properties +++ b/spring-batch-2/src/main/resources/application.properties @@ -1 +1,8 @@ +spring.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver +spring.datasource.url=jdbc:hsqldb:mem:testdb;DB_CLOSE_DELAY=-1;hsqldb.tx=mvcc +spring.datasource.username=sa +spring.datasource.password= + +spring.batch.jdbc.initialize-schema=always + file.input=coffee-list.csv \ No newline at end of file diff --git a/spring-batch-2/src/main/resources/books.csv b/spring-batch-2/src/main/resources/books.csv new file mode 100644 index 0000000000..af68e986a2 --- /dev/null +++ b/spring-batch-2/src/main/resources/books.csv @@ -0,0 +1,4 @@ +1,SHARP OBJECTS (MOVIE TIE-IN): A NOVEL +2,ARTEMIS: A NOVEL +3,HER PRETTY FACE +4,ALL WE EVER WANTED \ No newline at end of file diff --git a/spring-batch-2/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java b/spring-batch-2/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java new file mode 100644 index 0000000000..64a414fdbf --- /dev/null +++ b/spring-batch-2/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java @@ -0,0 +1,69 @@ +package com.baeldung.batchscheduler; + +import com.baeldung.batchscheduler.SpringBatchScheduler; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.batch.test.context.SpringBatchTest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.PropertySource; +import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.awaitility.Awaitility.await; +import static java.util.concurrent.TimeUnit.*; + +@SpringBatchTest +@SpringBootTest +@DirtiesContext +@PropertySource("classpath:application.properties") +@RunWith(SpringRunner.class) +public class SpringBatchSchedulerIntegrationTest { + + @Autowired + private ApplicationContext context; + + @Test + public void stopJobsWhenSchedulerDisabled() throws Exception { + SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class); + await().untilAsserted(() -> Assert.assertEquals(2, schedulerBean.getBatchRunCounter() + .get())); + schedulerBean.stop(); + await().atLeast(3, SECONDS); + + Assert.assertEquals(2, schedulerBean.getBatchRunCounter() + .get()); + } + + @Test + public void stopJobSchedulerWhenSchedulerDestroyed() throws Exception { + ScheduledAnnotationBeanPostProcessor bean = context.getBean(ScheduledAnnotationBeanPostProcessor.class); + SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class); + await().untilAsserted(() -> Assert.assertEquals(2, schedulerBean.getBatchRunCounter() + .get())); + bean.postProcessBeforeDestruction(schedulerBean, "SpringBatchScheduler"); + await().atLeast(3, SECONDS); + + Assert.assertEquals(2, schedulerBean.getBatchRunCounter() + .get()); + } + + @Test + public void stopJobSchedulerWhenFutureTasksCancelled() throws Exception { + SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class); + await().untilAsserted(() -> Assert.assertEquals(2, schedulerBean.getBatchRunCounter() + .get())); + schedulerBean.cancelFutureSchedulerTasks(); + await().atLeast(3, SECONDS); + + Assert.assertEquals(2, schedulerBean.getBatchRunCounter() + .get()); + } + + +} diff --git a/spring-batch/repository.sqlite b/spring-batch/repository.sqlite index a2b87ffa00f315b4084437ce2f5f639d47469027..b6a954554c9659b0f486c8af45bd69b710e61a0f 100644 GIT binary patch delta 852 zcma)3O-NKx6n;PVzBlvkyZ0)Z|IOq`F%XLL{~|P<@r9W)n$1E>{F&hm{hGm4WLT4% zHZIgx=qjb8MG%y4Aw-mdixwh6n-&HMErihAr4rG56Ana++I;8ZeBU|eo^vw`AhQ6* z%GurViU_;=s&AH-A-u)VW%`JAQ#aWmD`b|WNtl%2Eu%7T6`yw_$k+;^m#!rOAzyze zl=S%gwf;oHn@DMj=2tYYrumMgf&sr<+IM~tgEfw&Gd?}xzq`X0o zlBl(t&Z?+>rsk-Tc8swE;XQ^7lb>{jRN*~?9NNGgZcq?q|6?rLH~wp?WVF^)=L@Jr z-~+6_Di#X30`hfPs%HQYa53P0tiH|{2&kOrk6X036cus2hYdHzBh9@nZQV>rYym|++sE-`e6Zqp6= znZBV@G)>!WvbZ5Gncbd=oD1o1r(K*&vVtK`Z5E5NS&cbnZU*E%1q%%&5yo83WU}{|$?DKd zsB`l+!2UpmHZaHt0$hd@uoF7K7w{Ymngcq)Jq5`O%R&g9P7KYxtPUrSWHD-C%WkAC u+TNY4L5N~4 z(N#zzO0cxhn}alh+F8gV1i`|>gK%6Uq&e_Je<3E zh9$TJZ*U)Hu@j!bhhxZrs}jAPVD(ByL`TN^+|#9U@uH!_X#(r;hCbZE33lTGmLRRe z{h-o4-A!D!aC6Y`ZmkfvW6T_VmtKKVZbzs&V0b^xW-i-IbL78_L}fT&_8IQ@Olop| z`lCBPmHjd^o=r{2?@1ceIG^AHR&W=WF{^P7Jb|xqKS23&LrtwVD-*bG+;P6y9Sw6b zFG^O`it<@jR*B#ivo?lpMmATxtHZcAw&p6iT8}0~fCOZKG!jCja0otQ9e?8^o?{7f z_(?dr`^$2+Gy46(2a<13E-I(=6!HFE*oq$gLH53&-Y$4DB&Z Date: Wed, 24 Nov 2021 23:18:00 +0100 Subject: [PATCH 23/65] JAVA-8362: Switch to H2 db --- spring-batch-2/pom.xml | 5 ++- .../batchscheduler/SpringBatchScheduler.java | 36 ++----------------- .../src/main/resources/application.properties | 7 +--- .../SpringBatchSchedulerIntegrationTest.java | 2 +- 4 files changed, 6 insertions(+), 44 deletions(-) diff --git a/spring-batch-2/pom.xml b/spring-batch-2/pom.xml index 77779a0fcf..12d31aca14 100644 --- a/spring-batch-2/pom.xml +++ b/spring-batch-2/pom.xml @@ -22,9 +22,8 @@ spring-boot-starter-batch - org.hsqldb - hsqldb - runtime + com.h2database + h2 org.springframework.boot diff --git a/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java index bfaa044376..c830a41855 100644 --- a/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java +++ b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java @@ -11,26 +11,20 @@ import org.springframework.batch.core.configuration.annotation.EnableBatchProces import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.core.launch.JobLauncher; -import org.springframework.batch.core.launch.support.SimpleJobLauncher; -import org.springframework.batch.core.repository.JobRepository; -import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.file.FlatFileItemReader; import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder; import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper; -import org.springframework.batch.support.transaction.ResourcelessTransactionManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; -import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.support.ScheduledMethodRunnable; -import javax.sql.DataSource; import java.util.Date; import java.util.IdentityHashMap; import java.util.List; @@ -113,38 +107,12 @@ public class SpringBatchScheduler { @Bean public Job job() { - return jobBuilderFactory.get("job") + return jobBuilderFactory + .get("job") .start(readBooks()) .build(); } -// @Bean -// public JobLauncher jobLauncher() throws Exception { -// SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); -// jobLauncher.setJobRepository(jobRepository()); -// jobLauncher.afterPropertiesSet(); -// return jobLauncher; -// } - -// @Bean -// public JobRepository jobRepository() throws Exception { -// JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); -// factory.setDataSource(dataSource()); -// factory.setDatabaseType("HSQL"); -// factory.setTransactionManager(new ResourcelessTransactionManager()); -// return factory.getObject(); -// } - -// @Bean -// public DataSource dataSource() { -// DriverManagerDataSource dataSource = new DriverManagerDataSource(); -// dataSource.setDriverClassName("org.hsqldb.jdbc.JDBCDriver"); -// dataSource.setUrl("jdbc:hsqldb:mem:testdb"); -// dataSource.setUsername("sa"); -// dataSource.setPassword(""); -// return dataSource; -// } - @Bean protected Step readBooks() { return stepBuilderFactory.get("readBooks") diff --git a/spring-batch-2/src/main/resources/application.properties b/spring-batch-2/src/main/resources/application.properties index 5b34d9e93b..8d21bbe1c0 100644 --- a/spring-batch-2/src/main/resources/application.properties +++ b/spring-batch-2/src/main/resources/application.properties @@ -1,8 +1,3 @@ -spring.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver -spring.datasource.url=jdbc:hsqldb:mem:testdb;DB_CLOSE_DELAY=-1;hsqldb.tx=mvcc -spring.datasource.username=sa -spring.datasource.password= - -spring.batch.jdbc.initialize-schema=always +#spring.batch.jdbc.initialize-schema=embedded file.input=coffee-list.csv \ No newline at end of file diff --git a/spring-batch-2/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java b/spring-batch-2/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java index 64a414fdbf..61e5a1dd74 100644 --- a/spring-batch-2/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java +++ b/spring-batch-2/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java @@ -29,7 +29,7 @@ public class SpringBatchSchedulerIntegrationTest { private ApplicationContext context; @Test - public void stopJobsWhenSchedulerDisabled() throws Exception { + public void stopJobsWhenSchedulerDisabled() { SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class); await().untilAsserted(() -> Assert.assertEquals(2, schedulerBean.getBatchRunCounter() .get())); From 5500caa38084dc19436a06b9b9a75821f5886ff8 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Wed, 24 Nov 2021 23:20:22 +0100 Subject: [PATCH 24/65] JAVA-8362: Cleanup --- .../batchscheduler/SpringBatchSchedulerApplication.java | 1 - spring-batch-2/src/main/resources/application.properties | 2 -- 2 files changed, 3 deletions(-) diff --git a/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchSchedulerApplication.java b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchSchedulerApplication.java index 5b89163777..349a359efb 100644 --- a/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchSchedulerApplication.java +++ b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchSchedulerApplication.java @@ -1,6 +1,5 @@ package com.baeldung.batchscheduler; -import com.baeldung.batch.SpringBootBatchProcessingApplication; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-batch-2/src/main/resources/application.properties b/spring-batch-2/src/main/resources/application.properties index 8d21bbe1c0..0b8c56d3f8 100644 --- a/spring-batch-2/src/main/resources/application.properties +++ b/spring-batch-2/src/main/resources/application.properties @@ -1,3 +1 @@ -#spring.batch.jdbc.initialize-schema=embedded - file.input=coffee-list.csv \ No newline at end of file From c7dd49bcd8d25cc8be131ba0f4a6ef785433d373 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Thu, 25 Nov 2021 09:18:23 +0100 Subject: [PATCH 25/65] JAVA-8362: Remove batchscheduler code from spring-batch module --- .../batchscheduler/SpringBatchScheduler.java | 184 ------------------ .../baeldung/batchscheduler/model/Book.java | 35 ---- .../SpringBatchSchedulerIntegrationTest.java | 61 ------ 3 files changed, 280 deletions(-) delete mode 100644 spring-batch/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java delete mode 100644 spring-batch/src/main/java/com/baeldung/batchscheduler/model/Book.java delete mode 100644 spring-batch/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java diff --git a/spring-batch/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java b/spring-batch/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java deleted file mode 100644 index cff4e96c89..0000000000 --- a/spring-batch/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java +++ /dev/null @@ -1,184 +0,0 @@ -package com.baeldung.batchscheduler; - -import com.baeldung.batchscheduler.model.Book; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.batch.core.Job; -import org.springframework.batch.core.JobExecution; -import org.springframework.batch.core.JobParametersBuilder; -import org.springframework.batch.core.Step; -import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; -import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; -import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; -import org.springframework.batch.core.launch.JobLauncher; -import org.springframework.batch.core.launch.support.SimpleJobLauncher; -import org.springframework.batch.core.repository.JobRepository; -import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean; -import org.springframework.batch.item.ItemWriter; -import org.springframework.batch.item.file.FlatFileItemReader; -import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder; -import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper; -import org.springframework.batch.support.transaction.ResourcelessTransactionManager; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.io.ClassPathResource; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.scheduling.TaskScheduler; -import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; -import org.springframework.scheduling.support.ScheduledMethodRunnable; - -import javax.sql.DataSource; -import java.util.Date; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - -@Configuration -@EnableBatchProcessing -@EnableScheduling -public class SpringBatchScheduler { - - private final Logger logger = LoggerFactory.getLogger(SpringBatchScheduler.class); - - private AtomicBoolean enabled = new AtomicBoolean(true); - - private AtomicInteger batchRunCounter = new AtomicInteger(0); - - private final Map> scheduledTasks = new IdentityHashMap<>(); - - @Autowired - private JobBuilderFactory jobBuilderFactory; - - @Autowired - private StepBuilderFactory stepBuilderFactory; - - @Scheduled(fixedRate = 2000) - public void launchJob() throws Exception { - Date date = new Date(); - logger.debug("scheduler starts at " + date); - if (enabled.get()) { - JobExecution jobExecution = jobLauncher().run(job(), new JobParametersBuilder().addDate("launchDate", date) - .toJobParameters()); - batchRunCounter.incrementAndGet(); - logger.debug("Batch job ends with status as " + jobExecution.getStatus()); - } - logger.debug("scheduler ends "); - } - - public void stop() { - enabled.set(false); - } - - public void start() { - enabled.set(true); - } - - @Bean - public TaskScheduler poolScheduler() { - return new CustomTaskScheduler(); - } - - private class CustomTaskScheduler extends ThreadPoolTaskScheduler { - - private static final long serialVersionUID = -7142624085505040603L; - - @Override - public ScheduledFuture scheduleAtFixedRate(Runnable task, long period) { - ScheduledFuture future = super.scheduleAtFixedRate(task, period); - - ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task; - scheduledTasks.put(runnable.getTarget(), future); - - return future; - } - - } - - public void cancelFutureSchedulerTasks() { - scheduledTasks.forEach((k, v) -> { - if (k instanceof SpringBatchScheduler) { - v.cancel(false); - } - }); - } - - @Bean - public Job job() { - return jobBuilderFactory.get("job") - .start(readBooks()) - .build(); - } - - @Bean - public JobLauncher jobLauncher() throws Exception { - SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); - jobLauncher.setJobRepository(jobRepository()); - jobLauncher.afterPropertiesSet(); - return jobLauncher; - } - - @Bean - public JobRepository jobRepository() throws Exception { - JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); - factory.setDataSource(dataSource()); - factory.setTransactionManager(new ResourcelessTransactionManager()); - return factory.getObject(); - } - - @Bean - public DataSource dataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("org.sqlite.JDBC"); - dataSource.setUrl("jdbc:sqlite:repository.sqlite"); - return dataSource; - } - - @Bean - protected Step readBooks() { - return stepBuilderFactory.get("readBooks") - . chunk(2) - .reader(reader()) - .writer(writer()) - .build(); - } - - @Bean - public FlatFileItemReader reader() { - return new FlatFileItemReaderBuilder().name("bookItemReader") - .resource(new ClassPathResource("books.csv")) - .delimited() - .names(new String[] { "id", "name" }) - .fieldSetMapper(new BeanWrapperFieldSetMapper() { - { - setTargetType(Book.class); - } - }) - .build(); - } - - @Bean - public ItemWriter writer() { - return new ItemWriter() { - - @Override - public void write(List items) throws Exception { - logger.debug("writer..." + items.size()); - for (Book item : items) { - logger.debug(item.toString()); - } - - } - }; - } - - public AtomicInteger getBatchRunCounter() { - return batchRunCounter; - } - -} diff --git a/spring-batch/src/main/java/com/baeldung/batchscheduler/model/Book.java b/spring-batch/src/main/java/com/baeldung/batchscheduler/model/Book.java deleted file mode 100644 index 8ee986c729..0000000000 --- a/spring-batch/src/main/java/com/baeldung/batchscheduler/model/Book.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.batchscheduler.model; - -public class Book { - private int id; - private String name; - - public Book() {} - - public Book(int id, String name) { - super(); - this.id = id; - this.name = name; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String toString() { - return "Book [id=" + id + ", name=" + name + "]"; - } - -} diff --git a/spring-batch/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java b/spring-batch/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java deleted file mode 100644 index 81877fbc39..0000000000 --- a/spring-batch/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.batchscheduler; - -import com.baeldung.batchscheduler.SpringBatchScheduler; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import static org.awaitility.Awaitility.await; -import static java.util.concurrent.TimeUnit.*; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = SpringBatchScheduler.class) -public class SpringBatchSchedulerIntegrationTest { - - @Autowired - private ApplicationContext context; - - @Test - public void stopJobsWhenSchedulerDisabled() throws Exception { - SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class); - await().untilAsserted(() -> Assert.assertEquals(2, schedulerBean.getBatchRunCounter() - .get())); - schedulerBean.stop(); - await().atLeast(3, SECONDS); - - Assert.assertEquals(2, schedulerBean.getBatchRunCounter() - .get()); - } - - @Test - public void stopJobSchedulerWhenSchedulerDestroyed() throws Exception { - ScheduledAnnotationBeanPostProcessor bean = context.getBean(ScheduledAnnotationBeanPostProcessor.class); - SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class); - await().untilAsserted(() -> Assert.assertEquals(2, schedulerBean.getBatchRunCounter() - .get())); - bean.postProcessBeforeDestruction(schedulerBean, "SpringBatchScheduler"); - await().atLeast(3, SECONDS); - - Assert.assertEquals(2, schedulerBean.getBatchRunCounter() - .get()); - } - - @Test - public void stopJobSchedulerWhenFutureTasksCancelled() throws Exception { - SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class); - await().untilAsserted(() -> Assert.assertEquals(2, schedulerBean.getBatchRunCounter() - .get())); - schedulerBean.cancelFutureSchedulerTasks(); - await().atLeast(3, SECONDS); - - Assert.assertEquals(2, schedulerBean.getBatchRunCounter() - .get()); - } - - -} From 084249d5d18349957fb6919569610142b665ed44 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Thu, 25 Nov 2021 09:22:07 +0100 Subject: [PATCH 26/65] JAVA-8362: Remove awaitility dependency --- spring-batch/pom.xml | 7 ------- 1 file changed, 7 deletions(-) diff --git a/spring-batch/pom.xml b/spring-batch/pom.xml index 9879a4777f..32126fec9b 100644 --- a/spring-batch/pom.xml +++ b/spring-batch/pom.xml @@ -82,12 +82,6 @@ hsqldb runtime - - org.awaitility - awaitility - ${awaitility.version} - test - @@ -97,7 +91,6 @@ 4.1 2.3.1 2.12.3 - 3.1.1 \ No newline at end of file From 55d62ea210460a86e26f23ce72dc7838a157dfe8 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Thu, 25 Nov 2021 09:25:07 +0100 Subject: [PATCH 27/65] JAVA-8362: Update README.md files --- spring-batch-2/README.md | 2 ++ spring-batch/README.md | 2 +- spring-batch/src/main/resources/books.csv | 4 ---- 3 files changed, 3 insertions(+), 5 deletions(-) delete mode 100644 spring-batch/src/main/resources/books.csv diff --git a/spring-batch-2/README.md b/spring-batch-2/README.md index 08bf1933db..9b5d59f0b9 100644 --- a/spring-batch-2/README.md +++ b/spring-batch-2/README.md @@ -1,3 +1,5 @@ ### Relevant Articles: - [Spring Boot With Spring Batch](https://www.baeldung.com/spring-boot-spring-batch) +- [How to Trigger and Stop a Scheduled Spring Batch Job](https://www.baeldung.com/spring-batch-start-stop-job) +- More articles [[<-- prev]](/spring-batch) diff --git a/spring-batch/README.md b/spring-batch/README.md index 3a89459629..b87a2149a0 100644 --- a/spring-batch/README.md +++ b/spring-batch/README.md @@ -7,8 +7,8 @@ This module contains articles about Spring Batch - [Introduction to Spring Batch](https://www.baeldung.com/introduction-to-spring-batch) - [Spring Batch using Partitioner](https://www.baeldung.com/spring-batch-partitioner) - [Spring Batch – Tasklets vs Chunks](https://www.baeldung.com/spring-batch-tasklet-chunk) -- [How to Trigger and Stop a Scheduled Spring Batch Job](https://www.baeldung.com/spring-batch-start-stop-job) - [Configuring Skip Logic in Spring Batch](https://www.baeldung.com/spring-batch-skip-logic) - [Testing a Spring Batch Job](https://www.baeldung.com/spring-batch-testing-job) - [Configuring Retry Logic in Spring Batch](https://www.baeldung.com/spring-batch-retry-logic) - [Conditional Flow in Spring Batch](https://www.baeldung.com/spring-batch-conditional-flow) +- More articles [[next -->]](/spring-batch-2) diff --git a/spring-batch/src/main/resources/books.csv b/spring-batch/src/main/resources/books.csv deleted file mode 100644 index af68e986a2..0000000000 --- a/spring-batch/src/main/resources/books.csv +++ /dev/null @@ -1,4 +0,0 @@ -1,SHARP OBJECTS (MOVIE TIE-IN): A NOVEL -2,ARTEMIS: A NOVEL -3,HER PRETTY FACE -4,ALL WE EVER WANTED \ No newline at end of file From 41d7b82a24f0857541e547e24b8d687ad85098a0 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Thu, 25 Nov 2021 12:12:18 +0200 Subject: [PATCH 28/65] Delete README.md --- .../src/test/java/com/baeldung/applicationcontext/README.md | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 spring-core/src/test/java/com/baeldung/applicationcontext/README.md diff --git a/spring-core/src/test/java/com/baeldung/applicationcontext/README.md b/spring-core/src/test/java/com/baeldung/applicationcontext/README.md deleted file mode 100644 index a626417d47..0000000000 --- a/spring-core/src/test/java/com/baeldung/applicationcontext/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Intro to the Spring ClassPathXmlApplicationContext](http://www.baeldung.com/spring-classpathxmlapplicationcontext) From 5d2d962bf178fb2c9b31411ba334fac50f994ec5 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Thu, 25 Nov 2021 12:12:38 +0200 Subject: [PATCH 29/65] Update README.md --- spring-core/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-core/README.md b/spring-core/README.md index b8d46f6b34..3f0fe4b4e4 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -11,5 +11,6 @@ This module contains articles about core Spring functionality - [Spring Application Context Events](https://www.baeldung.com/spring-context-events) - [What is a Spring Bean?](https://www.baeldung.com/spring-bean) - [Spring PostConstruct and PreDestroy Annotations](https://www.baeldung.com/spring-postconstruct-predestroy) +- [Intro to the Spring ClassPathXmlApplicationContext](http://www.baeldung.com/spring-classpathxmlapplicationcontext) - More articles: [[next -->]](/spring-core-2) From fab1638eebbdfab352c662410114e11f875f1355 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Thu, 25 Nov 2021 13:10:58 +0100 Subject: [PATCH 30/65] JAVA-8363: Move etag code to spring-boot-mvc-3 --- .../src/main/java/com/baeldung/mime/Foo.java | 93 +++++++++++++++++++ .../java/com/baeldung/mime/WebConfig.java | 28 ++++++ .../java/com/baeldung/mime/FooLiveTest.java | 7 +- .../com/baeldung/mime/JacksonMarshaller.java | 2 +- .../com/baeldung/mime/XStreamMarshaller.java | 2 +- spring-boot-modules/spring-boot-mvc-3/pom.xml | 8 ++ .../src/main/java/com/baeldung/etag/Foo.java | 3 +- .../java/com/baeldung/etag/FooController.java | 4 +- .../main/java/com/baeldung/etag/FooDao.java | 0 .../etag/SpringBootEtagApplication.java | 0 .../java/com/baeldung/etag/WebConfig.java | 0 .../src/main/resources/WEB-INF/web.xml | 0 .../baeldung/etag/EtagIntegrationTest.java | 20 ++-- 13 files changed, 145 insertions(+), 22 deletions(-) create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/Foo.java create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/WebConfig.java rename spring-boot-modules/{spring-boot-mvc-2 => spring-boot-mvc-3}/src/main/java/com/baeldung/etag/Foo.java (99%) rename spring-boot-modules/{spring-boot-mvc-2 => spring-boot-mvc-3}/src/main/java/com/baeldung/etag/FooController.java (100%) rename spring-boot-modules/{spring-boot-mvc-2 => spring-boot-mvc-3}/src/main/java/com/baeldung/etag/FooDao.java (100%) rename spring-boot-modules/{spring-boot-mvc-2 => spring-boot-mvc-3}/src/main/java/com/baeldung/etag/SpringBootEtagApplication.java (100%) rename spring-boot-modules/{spring-boot-mvc-2 => spring-boot-mvc-3}/src/main/java/com/baeldung/etag/WebConfig.java (100%) rename spring-boot-modules/{spring-boot-mvc-2 => spring-boot-mvc-3}/src/main/resources/WEB-INF/web.xml (100%) rename spring-boot-modules/{spring-boot-mvc-2 => spring-boot-mvc-3}/src/test/java/com/baeldung/etag/EtagIntegrationTest.java (99%) diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/Foo.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/Foo.java new file mode 100644 index 0000000000..a8e379fc79 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/Foo.java @@ -0,0 +1,93 @@ +package com.baeldung.mime; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Version; +import java.io.Serializable; + +@Entity +public class Foo implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + @Column(nullable = false) + private String name; + + @Version + private long version; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + this.name = name; + } + + // API + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public long getVersion() { + return version; + } + + public void setVersion(long version) { + this.version = version; + } + + // + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.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 Foo other = (Foo) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Foo [name=").append(name).append("]"); + return builder.toString(); + } +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/WebConfig.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/WebConfig.java new file mode 100644 index 0000000000..2c9680f628 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/WebConfig.java @@ -0,0 +1,28 @@ +package com.baeldung.mime; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.ShallowEtagHeaderFilter; + +@Configuration +public class WebConfig { + + // Etags + + // If we're not using Spring Boot we can make use of + // AbstractAnnotationConfigDispatcherServletInitializer#getServletFilters + @Bean + public FilterRegistrationBean shallowEtagHeaderFilter() { + FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean<>( new ShallowEtagHeaderFilter()); + filterRegistrationBean.addUrlPatterns("/foos/*"); + filterRegistrationBean.setName("etagFilter"); + return filterRegistrationBean; + } + + // We can also just declare the filter directly + // @Bean + // public ShallowEtagHeaderFilter shallowEtagHeaderFilter() { + // return new ShallowEtagHeaderFilter(); + // } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java index e65b106ead..f4aa96b53a 100644 --- a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java @@ -14,15 +14,12 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.baeldung.etag.Foo; -import com.baeldung.etag.WebConfig; - import io.restassured.RestAssured; import io.restassured.response.Response; @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes= WebConfig.class, webEnvironment = WebEnvironment.RANDOM_PORT) -@ComponentScan({"com.baeldung.mime", "com.baeldung.etag"}) +@SpringBootTest(classes = WebConfig.class, webEnvironment = WebEnvironment.RANDOM_PORT) +@ComponentScan({"com.baeldung.mime"}) @EnableAutoConfiguration @ActiveProfiles("test") public class FooLiveTest { diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/JacksonMarshaller.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/JacksonMarshaller.java index 9dee0ef2cd..c6d14a9427 100644 --- a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/JacksonMarshaller.java +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/JacksonMarshaller.java @@ -7,7 +7,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; -import com.baeldung.etag.Foo; +import com.baeldung.mime.Foo; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/XStreamMarshaller.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/XStreamMarshaller.java index 2c67694e83..8a4188ceca 100644 --- a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/XStreamMarshaller.java +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/XStreamMarshaller.java @@ -4,7 +4,7 @@ import java.util.List; import org.springframework.http.MediaType; -import com.baeldung.etag.Foo; +import com.baeldung.mime.Foo; import com.thoughtworks.xstream.XStream; public final class XStreamMarshaller implements IMarshaller { diff --git a/spring-boot-modules/spring-boot-mvc-3/pom.xml b/spring-boot-modules/spring-boot-mvc-3/pom.xml index dee217862d..43a492786e 100644 --- a/spring-boot-modules/spring-boot-mvc-3/pom.xml +++ b/spring-boot-modules/spring-boot-mvc-3/pom.xml @@ -27,6 +27,14 @@ org.springframework.boot spring-boot-starter-thymeleaf + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + commons-io commons-io diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/Foo.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/Foo.java similarity index 99% rename from spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/Foo.java rename to spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/Foo.java index e553ca1b72..9790bca663 100644 --- a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/Foo.java +++ b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/Foo.java @@ -1,13 +1,12 @@ package com.baeldung.etag; -import java.io.Serializable; - import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Version; +import java.io.Serializable; @Entity public class Foo implements Serializable { diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooController.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/FooController.java similarity index 100% rename from spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooController.java rename to spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/FooController.java index 58f366501d..d40a5e7809 100644 --- a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooController.java +++ b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/FooController.java @@ -1,7 +1,5 @@ package com.baeldung.etag; -import javax.servlet.http.HttpServletResponse; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -16,6 +14,8 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; +import javax.servlet.http.HttpServletResponse; + @RestController @RequestMapping(value = "/foos") public class FooController { diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooDao.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/FooDao.java similarity index 100% rename from spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooDao.java rename to spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/FooDao.java diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/SpringBootEtagApplication.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/SpringBootEtagApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/SpringBootEtagApplication.java rename to spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/SpringBootEtagApplication.java diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/WebConfig.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/WebConfig.java similarity index 100% rename from spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/WebConfig.java rename to spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/WebConfig.java diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/WEB-INF/web.xml b/spring-boot-modules/spring-boot-mvc-3/src/main/resources/WEB-INF/web.xml similarity index 100% rename from spring-boot-modules/spring-boot-mvc-2/src/main/resources/WEB-INF/web.xml rename to spring-boot-modules/spring-boot-mvc-3/src/main/resources/WEB-INF/web.xml diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/etag/EtagIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-3/src/test/java/com/baeldung/etag/EtagIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/etag/EtagIntegrationTest.java rename to spring-boot-modules/spring-boot-mvc-3/src/test/java/com/baeldung/etag/EtagIntegrationTest.java index 88c5ae1686..97de6d06f1 100644 --- a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/etag/EtagIntegrationTest.java +++ b/spring-boot-modules/spring-boot-mvc-3/src/test/java/com/baeldung/etag/EtagIntegrationTest.java @@ -1,10 +1,10 @@ package com.baeldung.etag; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.restassured.RestAssured; +import io.restassured.http.ContentType; +import io.restassured.response.Response; import org.assertj.core.util.Preconditions; import org.junit.Ignore; import org.junit.Test; @@ -18,12 +18,10 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.restassured.RestAssured; -import io.restassured.http.ContentType; -import io.restassured.response.Response; +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) From 9b494ef51345ef5ee053769ad430dc115a6bd3e2 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Thu, 25 Nov 2021 13:25:40 +0100 Subject: [PATCH 31/65] JAVA-8363: Fix FooLiveTest - separate mime from etag code --- .../java/com/baeldung/mime/FooController.java | 36 +++++++++++++++++++ .../main/java/com/baeldung/mime/FooDao.java | 8 +++++ .../java/com/baeldung/mime/WebConfig.java | 28 --------------- .../java/com/baeldung/mime/FooLiveTest.java | 6 ++-- 4 files changed, 47 insertions(+), 31 deletions(-) create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/FooController.java create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/FooDao.java delete mode 100644 spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/WebConfig.java diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/FooController.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/FooController.java new file mode 100644 index 0000000000..d7da9bd849 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/FooController.java @@ -0,0 +1,36 @@ +package com.baeldung.mime; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +import javax.servlet.http.HttpServletResponse; + +@RestController +@RequestMapping(value = "/foos") +public class FooController { + + @Autowired + private FooDao fooDao; + + @GetMapping(value = "/{id}") + public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { + return fooDao.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + } + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { + return fooDao.save(resource); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/FooDao.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/FooDao.java new file mode 100644 index 0000000000..9fc99e1124 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/FooDao.java @@ -0,0 +1,8 @@ +package com.baeldung.mime; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface FooDao extends CrudRepository{ +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/WebConfig.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/WebConfig.java deleted file mode 100644 index 2c9680f628..0000000000 --- a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/WebConfig.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.mime; - -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.filter.ShallowEtagHeaderFilter; - -@Configuration -public class WebConfig { - - // Etags - - // If we're not using Spring Boot we can make use of - // AbstractAnnotationConfigDispatcherServletInitializer#getServletFilters - @Bean - public FilterRegistrationBean shallowEtagHeaderFilter() { - FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean<>( new ShallowEtagHeaderFilter()); - filterRegistrationBean.addUrlPatterns("/foos/*"); - filterRegistrationBean.setName("etagFilter"); - return filterRegistrationBean; - } - - // We can also just declare the filter directly - // @Bean - // public ShallowEtagHeaderFilter shallowEtagHeaderFilter() { - // return new ShallowEtagHeaderFilter(); - // } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java index f4aa96b53a..86dd4915b4 100644 --- a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java @@ -18,7 +18,7 @@ import io.restassured.RestAssured; import io.restassured.response.Response; @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = WebConfig.class, webEnvironment = WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = FooController.class, webEnvironment = WebEnvironment.RANDOM_PORT) @ComponentScan({"com.baeldung.mime"}) @EnableAutoConfiguration @ActiveProfiles("test") @@ -44,12 +44,12 @@ public class FooLiveTest { createAsUri(resource); } - private final String createAsUri(final Foo resource) { + private String createAsUri(final Foo resource) { final Response response = createAsResponse(resource); return getURL() + "/" + response.getBody().as(Foo.class).getId(); } - private final Response createAsResponse(final Foo resource) { + private Response createAsResponse(final Foo resource) { final String resourceAsString = marshaller.encode(resource); return RestAssured.given() From e518eb72a8e9304786b3c0cdb1559a8b6e07e660 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Thu, 25 Nov 2021 13:26:46 +0100 Subject: [PATCH 32/65] JAVA-8363: Update README.md files --- spring-boot-modules/spring-boot-mvc-2/README.md | 1 - spring-boot-modules/spring-boot-mvc-3/README.md | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot-modules/spring-boot-mvc-2/README.md b/spring-boot-modules/spring-boot-mvc-2/README.md index f9becb721f..0d0e05daf0 100644 --- a/spring-boot-modules/spring-boot-mvc-2/README.md +++ b/spring-boot-modules/spring-boot-mvc-2/README.md @@ -7,7 +7,6 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [Functional Controllers in Spring MVC](https://www.baeldung.com/spring-mvc-functional-controllers) - [Specify an Array of Strings as Body Parameters in Swagger](https://www.baeldung.com/swagger-body-array-of-strings) - [Swagger @ApiParam vs @ApiModelProperty](https://www.baeldung.com/swagger-apiparam-vs-apimodelproperty) -- [ETags for REST with Spring](https://www.baeldung.com/etags-for-rest-with-spring) - [Testing REST with multiple MIME types](https://www.baeldung.com/testing-rest-api-with-multiple-media-types) - [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) diff --git a/spring-boot-modules/spring-boot-mvc-3/README.md b/spring-boot-modules/spring-boot-mvc-3/README.md index f9c6989b3c..fa24ac11ed 100644 --- a/spring-boot-modules/spring-boot-mvc-3/README.md +++ b/spring-boot-modules/spring-boot-mvc-3/README.md @@ -10,4 +10,5 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [Differences in @Valid and @Validated Annotations in Spring](https://www.baeldung.com/spring-valid-vs-validated) - [CharacterEncodingFilter In SpringBoot](https://www.baeldung.com/spring-boot-characterencodingfilter) - [HandlerInterceptors vs. Filters in Spring MVC](https://www.baeldung.com/spring-mvc-handlerinterceptor-vs-filter) +- [ETags for REST with Spring](https://www.baeldung.com/etags-for-rest-with-spring) - More articles: [[prev -->]](/spring-boot-modules/spring-boot-mvc-2) From 49b8975ebc5f4a158a8309ceb34c03f63b82117b Mon Sep 17 00:00:00 2001 From: Yavuz Tas <12643010+yavuztas@users.noreply.github.com> Date: Thu, 25 Nov 2021 17:45:26 +0100 Subject: [PATCH 33/65] BAEL-5192 Code samples for the article (#11483) * BAEL-5192 implement code samples * BAEL-5192 simplify some methods * BAEL-5192 remove duplicated test method Co-authored-by: Yavuz Tas --- .../baeldung/jackson/booleanAsInt/Game.java | 49 +++++++ .../GameAnnotatedByJsonFormat.java | 56 ++++++++ ...meAnnotatedByJsonSerializeDeserialize.java | 58 ++++++++ .../NumericBooleanDeserializer.java | 23 +++ .../NumericBooleanSerializer.java | 15 ++ .../BooleanAsIntegerUnitTest.java | 132 ++++++++++++++++++ 6 files changed, 333 insertions(+) create mode 100644 jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/Game.java create mode 100644 jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/GameAnnotatedByJsonFormat.java create mode 100644 jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/GameAnnotatedByJsonSerializeDeserialize.java create mode 100644 jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/NumericBooleanDeserializer.java create mode 100644 jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/NumericBooleanSerializer.java create mode 100644 jackson-modules/jackson-conversions-2/src/test/java/com/baeldung/jackson/booleanAsInt/BooleanAsIntegerUnitTest.java diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/Game.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/Game.java new file mode 100644 index 0000000000..0ad77640d4 --- /dev/null +++ b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/Game.java @@ -0,0 +1,49 @@ +package com.baeldung.jackson.booleanAsInt; + +public class Game { + + private Long id; + private String name; + private Boolean paused; + private Boolean over; + + public Game() { + } + + public Game(Long id, String name) { + this.id = id; + this.name = name; + } + + public Long getId() { + return this.id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public Boolean isPaused() { + return paused; + } + + public void setPaused(Boolean paused) { + this.paused = paused; + } + + public Boolean isOver() { + return over; + } + + public void setOver(Boolean over) { + this.over = over; + } +} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/GameAnnotatedByJsonFormat.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/GameAnnotatedByJsonFormat.java new file mode 100644 index 0000000000..b97625fa6b --- /dev/null +++ b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/GameAnnotatedByJsonFormat.java @@ -0,0 +1,56 @@ +package com.baeldung.jackson.booleanAsInt; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonFormat.Shape; + +public class GameAnnotatedByJsonFormat { + + private Long id; + private String name; + + @JsonFormat(shape = Shape.NUMBER) + private boolean paused; + + @JsonFormat(shape = Shape.NUMBER) + private boolean over; + + public GameAnnotatedByJsonFormat() { + } + + public GameAnnotatedByJsonFormat(Long id, String name) { + this.id = id; + this.name = name; + } + + public Long getId() { + return this.id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public boolean isPaused() { + return paused; + } + + public void setPaused(boolean paused) { + this.paused = paused; + } + + public boolean isOver() { + return over; + } + + public void setOver(boolean over) { + this.over = over; + } +} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/GameAnnotatedByJsonSerializeDeserialize.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/GameAnnotatedByJsonSerializeDeserialize.java new file mode 100644 index 0000000000..50c6d96009 --- /dev/null +++ b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/GameAnnotatedByJsonSerializeDeserialize.java @@ -0,0 +1,58 @@ +package com.baeldung.jackson.booleanAsInt; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +public class GameAnnotatedByJsonSerializeDeserialize { + + private Long id; + private String name; + + @JsonSerialize(using = NumericBooleanSerializer.class) + @JsonDeserialize(using = NumericBooleanDeserializer.class) + private Boolean paused; + + @JsonSerialize(using = NumericBooleanSerializer.class) + @JsonDeserialize(using = NumericBooleanDeserializer.class) + private Boolean over; + + public GameAnnotatedByJsonSerializeDeserialize() { + } + + public GameAnnotatedByJsonSerializeDeserialize(Long id, String name) { + this.id = id; + this.name = name; + } + + public Long getId() { + return this.id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public Boolean isPaused() { + return paused; + } + + public void setPaused(Boolean paused) { + this.paused = paused; + } + + public Boolean isOver() { + return over; + } + + public void setOver(Boolean over) { + this.over = over; + } +} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/NumericBooleanDeserializer.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/NumericBooleanDeserializer.java new file mode 100644 index 0000000000..e9cb41e91d --- /dev/null +++ b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/NumericBooleanDeserializer.java @@ -0,0 +1,23 @@ +package com.baeldung.jackson.booleanAsInt; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import java.io.IOException; + +public class NumericBooleanDeserializer extends JsonDeserializer { + + @Override + public Boolean deserialize(JsonParser p, DeserializationContext ctxt) + throws IOException { + if ("1".equals(p.getText())) { + return Boolean.TRUE; + } + if ("0".equals(p.getText())) { + return Boolean.FALSE; + } + // for other than "1" or "0" throw exception by using Jackson internals + throw ctxt.weirdStringException(p.getText(), Boolean.class, "only \"1\" or \"0\" recognized"); + } + +} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/NumericBooleanSerializer.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/NumericBooleanSerializer.java new file mode 100644 index 0000000000..e9f7112b53 --- /dev/null +++ b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/NumericBooleanSerializer.java @@ -0,0 +1,15 @@ +package com.baeldung.jackson.booleanAsInt; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import java.io.IOException; + +public class NumericBooleanSerializer extends JsonSerializer { + + @Override + public void serialize(Boolean value, JsonGenerator gen, SerializerProvider serializers) + throws IOException { + gen.writeString(value ? "1" : "0"); + } +} diff --git a/jackson-modules/jackson-conversions-2/src/test/java/com/baeldung/jackson/booleanAsInt/BooleanAsIntegerUnitTest.java b/jackson-modules/jackson-conversions-2/src/test/java/com/baeldung/jackson/booleanAsInt/BooleanAsIntegerUnitTest.java new file mode 100644 index 0000000000..976f3f4915 --- /dev/null +++ b/jackson-modules/jackson-conversions-2/src/test/java/com/baeldung/jackson/booleanAsInt/BooleanAsIntegerUnitTest.java @@ -0,0 +1,132 @@ +package com.baeldung.jackson.booleanAsInt; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonFormat.Shape; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.exc.InvalidFormatException; +import com.fasterxml.jackson.databind.module.SimpleModule; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class BooleanAsIntegerUnitTest { + + private ObjectMapper mapper; + + @BeforeEach + public void setup() { + mapper = new ObjectMapper(); + } + + @Test + public void givenBoolean_serializedAsInteger() throws Exception { + GameAnnotatedByJsonFormat + game = new GameAnnotatedByJsonFormat(1L, "My Game"); + game.setPaused(true); + game.setOver(false); + String json = mapper.writeValueAsString(game); + + assertThat(json) + .isEqualTo("{\"id\":1,\"name\":\"My Game\",\"paused\":1,\"over\":0}"); + } + + @Test + public void givenInteger_deserializedAsBooleanByDefault() throws Exception { + // Integer "1" and "0" values deserialized correctly out of the box. + // No configuration or @JsonFormat annotation needed. + String json = "{\"id\":1,\"name\":\"My Game\",\"paused\":1,\"over\":0}"; + Game game = mapper.readValue(json, Game.class); + + assertThat(game.isPaused()).isEqualTo(true); + assertThat(game.isOver()).isEqualTo(false); + } + + @Test + public void givenBoolean_serializedAsIntegerGlobally() throws Exception { + // global configuration override for the type Boolean + mapper.configOverride(Boolean.class) + .setFormat(JsonFormat.Value.forShape(Shape.NUMBER)); + + Game game = new Game(1L, "My Game"); + game.setPaused(true); + game.setOver(false); + String json = mapper.writeValueAsString(game); + + assertThat(json) + .isEqualTo("{\"id\":1,\"name\":\"My Game\",\"paused\":1,\"over\":0}"); + } + + @Test + public void givenBooleanWithCustomSerializer_serializedAsNumericString() throws Exception { + GameAnnotatedByJsonSerializeDeserialize + game = new GameAnnotatedByJsonSerializeDeserialize(1L, "My Game"); + game.setPaused(true); + game.setOver(false); + String json = mapper.writeValueAsString(game); + + assertThat(json) + .isEqualTo("{\"id\":1,\"name\":\"My Game\",\"paused\":\"1\",\"over\":\"0\"}"); + } + + @Test + public void givenNumericStringWithCustomDeserializer_deserializedAsBoolean() throws Exception { + String json = "{\"id\":1,\"name\":\"My Game\",\"paused\":\"1\",\"over\":\"0\"}"; + GameAnnotatedByJsonSerializeDeserialize + game = mapper.readValue(json, GameAnnotatedByJsonSerializeDeserialize.class); + + assertThat(game.isPaused()).isEqualTo(true); + assertThat(game.isOver()).isEqualTo(false); + } + + @Test + public void givenBooleanWithCustomSerializer_serializedAsNumericStringGlobally() throws Exception { + // setting serializers globally + SimpleModule module = new SimpleModule(); + module.addSerializer(Boolean.class, new NumericBooleanSerializer()); + mapper.registerModule(module); + + Game game = new Game(1L, "My Game"); + game.setPaused(true); + game.setOver(false); + String json = mapper.writeValueAsString(game); + + assertThat(json) + .isEqualTo("{\"id\":1,\"name\":\"My Game\",\"paused\":\"1\",\"over\":\"0\"}"); + } + + @Test + public void givenNumericStringWithCustomDeserializer_deserializedAsBooleanGlobally() throws Exception { + // setting deserializers globally + SimpleModule module = new SimpleModule(); + module.addDeserializer(Boolean.class, new NumericBooleanDeserializer()); + mapper.registerModule(module); + + String json = "{\"id\":1,\"name\":\"My Game\",\"paused\":\"1\",\"over\":\"0\"}"; + Game game = mapper.readValue(json, Game.class); + + assertThat(game.isPaused()).isEqualTo(true); + assertThat(game.isOver()).isEqualTo(false); + } + + @Test + public void givenInvalidStringWithCustomDeserializer_throwsInvalidFormatException() { + // another number other than "1" or "0" + String json = "{\"id\":1,\"name\":\"My Game\",\"paused\":\"5\"}"; + InvalidFormatException e = Assertions.assertThrows( + InvalidFormatException.class, () -> mapper.readValue(json, GameAnnotatedByJsonSerializeDeserialize.class) + ); + + assertThat(e.getValue()).isEqualTo("5"); + + // non-numeric string + String json2 = "{\"id\":1,\"name\":\"My Game\",\"paused\":\"xxx\"}"; + InvalidFormatException e2 = Assertions.assertThrows( + InvalidFormatException.class, () -> mapper.readValue(json2, GameAnnotatedByJsonSerializeDeserialize.class) + ); + + assertThat(e2.getValue()).isEqualTo("xxx"); + } + +} From 88e143feca1d4eae832f0a4fe9e6e5712cdc4354 Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Thu, 25 Nov 2021 19:05:06 +0000 Subject: [PATCH 34/65] [BAEL-44346] Update to use ReaderInputStream from Commons --- .../readertox/JavaReaderToXUnitTest.java | 58 +++++++++++++++++-- 1 file changed, 53 insertions(+), 5 deletions(-) diff --git a/core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/readertox/JavaReaderToXUnitTest.java b/core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/readertox/JavaReaderToXUnitTest.java index 72813df9b1..fa3c34d479 100644 --- a/core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/readertox/JavaReaderToXUnitTest.java +++ b/core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/readertox/JavaReaderToXUnitTest.java @@ -1,7 +1,7 @@ package com.baeldung.readertox; import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.ByteArrayInputStream; import java.io.File; @@ -17,6 +17,7 @@ import java.nio.charset.StandardCharsets; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.CharSequenceReader; +import org.apache.commons.io.input.ReaderInputStream; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -181,7 +182,7 @@ public class JavaReaderToXUnitTest { } @Test - public void givenUsingCommonsIO_whenConvertingReaderIntoInputStream() throws IOException { + public void givenUsingCommonsIOUtils_whenConvertingReaderIntoInputStream() throws IOException { final Reader initialReader = new StringReader("With Commons IO"); final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader)); @@ -191,7 +192,7 @@ public class JavaReaderToXUnitTest { } @Test - public void givenUsingCommonsIO_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException { + public void givenUsingCommonsIOUtils_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException { String initialString = "With Commons IO"; final Reader initialReader = new StringReader(initialString); @@ -204,6 +205,30 @@ public class JavaReaderToXUnitTest { targetStream.close(); } + @Test + public void givenUsingCommonsIOReaderInputStream_whenConvertingReaderIntoInputStream() throws IOException { + final Reader initialReader = new StringReader("With Commons IO"); + + final InputStream targetStream = new ReaderInputStream(initialReader); + + initialReader.close(); + targetStream.close(); + } + + @Test + public void givenUsingCommonsIOReaderInputStream_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException { + String initialString = "With Commons IO"; + final Reader initialReader = new StringReader(initialString); + + final InputStream targetStream = new ReaderInputStream(initialReader); + + final String finalString = IOUtils.toString(targetStream); + assertThat(finalString, equalTo(initialString)); + + initialReader.close(); + targetStream.close(); + } + // tests - Reader to InputStream with encoding @Test @@ -233,7 +258,7 @@ public class JavaReaderToXUnitTest { } @Test - public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding() throws IOException { + public void givenUsingCommonsIOUtils_whenConvertingReaderIntoInputStreamWithEncoding() throws IOException { final Reader initialReader = new StringReader("With Commons IO"); final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8); @@ -243,7 +268,7 @@ public class JavaReaderToXUnitTest { } @Test - public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding_thenCorrect() throws IOException { + public void givenUsingCommonsIOUtils_whenConvertingReaderIntoInputStreamWithEncoding_thenCorrect() throws IOException { String initialString = "With Commons IO"; final Reader initialReader = new StringReader(initialString); final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8); @@ -255,4 +280,27 @@ public class JavaReaderToXUnitTest { targetStream.close(); } + @Test + public void givenUsingCommonsIOReaderInputStream_whenConvertingReaderIntoInputStreamWithEncoding() throws IOException { + final Reader initialReader = new StringReader("With Commons IO"); + + final InputStream targetStream = new ReaderInputStream(initialReader, Charsets.UTF_8); + + initialReader.close(); + targetStream.close(); + } + + @Test + public void givenUsingCommonsIOReaderInputStream_whenConvertingReaderIntoInputStreamWithEncoding_thenCorrect() throws IOException { + String initialString = "With Commons IO"; + final Reader initialReader = new StringReader(initialString); + + final InputStream targetStream = new ReaderInputStream(initialReader, Charsets.UTF_8); + + String finalString = IOUtils.toString(targetStream, Charsets.UTF_8); + assertThat(finalString, equalTo(initialString)); + + initialReader.close(); + targetStream.close(); + } } From 6d5ae33f5b5e56ca8c28b1f746ab5f3b83f3466b Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Thu, 25 Nov 2021 19:51:32 +0000 Subject: [PATCH 35/65] [JAVA-8355] Move article code to spring-testing-2 module --- testing-modules/spring-testing-2/README.md | 1 + .../baeldung/testexecutionlisteners/AdditionService.java | 0 .../testexecutionlisteners/AdditionServiceUnitTest.java | 5 +++-- .../CustomTestExecutionListener.java | 0 .../TestExecutionListenersWithMergeModeUnitTest.java | 7 ++++--- .../TestExecutionListenersWithoutMergeModeUnitTest.java | 5 +++-- testing-modules/spring-testing/README.md | 1 - 7 files changed, 11 insertions(+), 8 deletions(-) rename testing-modules/{spring-testing => spring-testing-2}/src/main/java/com/baeldung/testexecutionlisteners/AdditionService.java (100%) rename testing-modules/{spring-testing => spring-testing-2}/src/test/java/com/baeldung/testexecutionlisteners/AdditionServiceUnitTest.java (92%) rename testing-modules/{spring-testing => spring-testing-2}/src/test/java/com/baeldung/testexecutionlisteners/CustomTestExecutionListener.java (100%) rename testing-modules/{spring-testing => spring-testing-2}/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithMergeModeUnitTest.java (93%) rename testing-modules/{spring-testing => spring-testing-2}/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithoutMergeModeUnitTest.java (94%) diff --git a/testing-modules/spring-testing-2/README.md b/testing-modules/spring-testing-2/README.md index 16b47adeac..434388d683 100644 --- a/testing-modules/spring-testing-2/README.md +++ b/testing-modules/spring-testing-2/README.md @@ -3,3 +3,4 @@ - [Guide to @DynamicPropertySource in Spring](https://www.baeldung.com/spring-dynamicpropertysource) - [Concurrent Test Execution in Spring 5](https://www.baeldung.com/spring-5-concurrent-tests) - [Spring 5 Testing with @EnabledIf Annotation](https://www.baeldung.com/spring-5-enabledIf) +- [The Spring TestExecutionListener](https://www.baeldung.com/spring-testexecutionlistener) diff --git a/testing-modules/spring-testing/src/main/java/com/baeldung/testexecutionlisteners/AdditionService.java b/testing-modules/spring-testing-2/src/main/java/com/baeldung/testexecutionlisteners/AdditionService.java similarity index 100% rename from testing-modules/spring-testing/src/main/java/com/baeldung/testexecutionlisteners/AdditionService.java rename to testing-modules/spring-testing-2/src/main/java/com/baeldung/testexecutionlisteners/AdditionService.java diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/AdditionServiceUnitTest.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/AdditionServiceUnitTest.java similarity index 92% rename from testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/AdditionServiceUnitTest.java rename to testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/AdditionServiceUnitTest.java index bbe537a3ce..6c5d08f478 100644 --- a/testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/AdditionServiceUnitTest.java +++ b/testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/AdditionServiceUnitTest.java @@ -1,7 +1,5 @@ package com.baeldung.testexecutionlisteners; -import static org.junit.Assert.assertThat; - import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -9,9 +7,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; +import static org.hamcrest.MatcherAssert.assertThat; + @RunWith(SpringRunner.class) @ContextConfiguration(classes = AdditionService.class) public class AdditionServiceUnitTest { + @Autowired private AdditionService additionService; diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/CustomTestExecutionListener.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/CustomTestExecutionListener.java similarity index 100% rename from testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/CustomTestExecutionListener.java rename to testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/CustomTestExecutionListener.java diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithMergeModeUnitTest.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithMergeModeUnitTest.java similarity index 93% rename from testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithMergeModeUnitTest.java rename to testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithMergeModeUnitTest.java index 44937aa755..de1501c54d 100644 --- a/testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithMergeModeUnitTest.java +++ b/testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithMergeModeUnitTest.java @@ -1,7 +1,5 @@ package com.baeldung.testexecutionlisteners; -import static org.junit.Assert.assertThat; - import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -11,11 +9,14 @@ import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.TestExecutionListeners.MergeMode; import org.springframework.test.context.junit4.SpringRunner; +import static org.hamcrest.MatcherAssert.assertThat; + @RunWith(SpringRunner.class) -@TestExecutionListeners(value = { CustomTestExecutionListener.class }, +@TestExecutionListeners(value = { CustomTestExecutionListener.class }, mergeMode = MergeMode.MERGE_WITH_DEFAULTS) @ContextConfiguration(classes = AdditionService.class) public class TestExecutionListenersWithMergeModeUnitTest { + @Autowired private AdditionService additionService; diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithoutMergeModeUnitTest.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithoutMergeModeUnitTest.java similarity index 94% rename from testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithoutMergeModeUnitTest.java rename to testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithoutMergeModeUnitTest.java index e25ab9f381..b4cc861c29 100644 --- a/testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithoutMergeModeUnitTest.java +++ b/testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithoutMergeModeUnitTest.java @@ -1,7 +1,5 @@ package com.baeldung.testexecutionlisteners; -import static org.junit.Assert.assertThat; - import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -11,11 +9,14 @@ import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; +import static org.hamcrest.MatcherAssert.assertThat; + @RunWith(SpringRunner.class) @TestExecutionListeners(value = {CustomTestExecutionListener.class, DependencyInjectionTestExecutionListener.class}) @ContextConfiguration(classes = AdditionService.class) public class TestExecutionListenersWithoutMergeModeUnitTest { + @Autowired private AdditionService additionService; diff --git a/testing-modules/spring-testing/README.md b/testing-modules/spring-testing/README.md index a4de9c5c57..2427dfabbe 100644 --- a/testing-modules/spring-testing/README.md +++ b/testing-modules/spring-testing/README.md @@ -7,4 +7,3 @@ - [Using SpringJUnit4ClassRunner with Parameterized](https://www.baeldung.com/springjunit4classrunner-parameterized) - [Override Properties in Spring’s Tests](https://www.baeldung.com/spring-tests-override-properties) - [A Quick Guide to @DirtiesContext](https://www.baeldung.com/spring-dirtiescontext) -- [The Spring TestExecutionListener](https://www.baeldung.com/spring-testexecutionlistener) From b11a9bf4a475cbcc84d3f893c2b89236c348b63b Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Fri, 26 Nov 2021 10:40:22 +0200 Subject: [PATCH 36/65] disable tests until they are fixed --- .../version/{VersionUnitTest.java => VersionManualTest.java} | 3 ++- .../java/com/baeldung/java9/modules/ModuleAPIUnitTest.java | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) rename core-java-modules/core-java-11-2/src/test/java/com/baeldung/version/{VersionUnitTest.java => VersionManualTest.java} (92%) diff --git a/core-java-modules/core-java-11-2/src/test/java/com/baeldung/version/VersionUnitTest.java b/core-java-modules/core-java-11-2/src/test/java/com/baeldung/version/VersionManualTest.java similarity index 92% rename from core-java-modules/core-java-11-2/src/test/java/com/baeldung/version/VersionUnitTest.java rename to core-java-modules/core-java-11-2/src/test/java/com/baeldung/version/VersionManualTest.java index 128c7f60f4..74035a3e2f 100644 --- a/core-java-modules/core-java-11-2/src/test/java/com/baeldung/version/VersionUnitTest.java +++ b/core-java-modules/core-java-11-2/src/test/java/com/baeldung/version/VersionManualTest.java @@ -5,7 +5,8 @@ import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -public class VersionUnitTest { +// manual test as the runtime JDK version can be different depending on where the test is run +public class VersionManualTest { @Test public void givenJava_whenUsingRuntime_thenGetVersion() { diff --git a/core-java-modules/core-java-9-jigsaw/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java b/core-java-modules/core-java-9-jigsaw/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java index b909636b56..f6ea266676 100644 --- a/core-java-modules/core-java-9-jigsaw/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java +++ b/core-java-modules/core-java-9-jigsaw/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java @@ -16,6 +16,7 @@ import java.util.stream.Collectors; import org.junit.Before; import org.junit.Test; +import org.junit.Ignore; public class ModuleAPIUnitTest { @@ -110,6 +111,7 @@ public class ModuleAPIUnitTest { } @Test + @Ignore // fixing in http://team.baeldung.com/browse/JAVA-8679 public void givenModules_whenAccessingModuleDescriptorProvides_thenProvidesAreReturned() { Set javaBaseProvides = javaBaseModule.getDescriptor().provides(); Set javaSqlProvides = javaSqlModule.getDescriptor().provides(); From ebc6f49564a28bcd729e15b7ece5c01edfc80ce0 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Fri, 26 Nov 2021 10:56:49 +0100 Subject: [PATCH 37/65] JAVA-8699: Use @KeycloakConfiguration annotation --- .../main/java/com/baeldung/keycloak/SecurityConfig.java | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java index 895ac8c562..78023aff8f 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java @@ -1,24 +1,19 @@ package com.baeldung.keycloak; import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver; -import org.keycloak.adapters.springsecurity.KeycloakSecurityComponents; +import org.keycloak.adapters.springsecurity.KeycloakConfiguration; import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider; import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; 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.core.authority.mapping.SimpleAuthorityMapper; import org.springframework.security.core.session.SessionRegistryImpl; import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy; import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; -@Configuration -@EnableWebSecurity -@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class) +@KeycloakConfiguration class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter { // Submits the KeycloakAuthenticationProvider to the AuthenticationManager @Autowired From 6a2f78d4abb351006a963e83210ca5d6a9160cfa Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Fri, 26 Nov 2021 13:17:01 +0100 Subject: [PATCH 38/65] JAVA-8709: Extract commons-collections4.version property to the main pom.xml --- algorithms-miscellaneous-3/pom.xml | 4 +--- core-java-modules/core-java-10/pom.xml | 1 - core-java-modules/core-java-8/pom.xml | 5 ----- core-java-modules/core-java-9/pom.xml | 1 - core-java-modules/core-java-collections-2/pom.xml | 1 - core-java-modules/core-java-collections-array-list/pom.xml | 4 ---- core-java-modules/core-java-collections-list-2/pom.xml | 4 ---- core-java-modules/core-java-collections-list-3/pom.xml | 1 - core-java-modules/core-java-collections-list/pom.xml | 4 ---- core-java-modules/core-java-collections-maps-2/pom.xml | 1 - core-java-modules/core-java-collections-maps/pom.xml | 4 ---- core-java-modules/core-java-collections-set/pom.xml | 1 - core-java-modules/core-java-concurrency-advanced/pom.xml | 1 - core-java-modules/core-java-os/pom.xml | 1 - gson/pom.xml | 3 --- guava-modules/guava-collections-list/pom.xml | 3 --- guava-modules/guava-collections/pom.xml | 3 --- java-collections-conversions/pom.xml | 4 ---- java-collections-maps-3/pom.xml | 1 - json/pom.xml | 1 - libraries-6/pom.xml | 1 - libraries-apache-commons-collections/pom.xml | 3 +-- pom.xml | 1 + spring-5-reactive-client/pom.xml | 1 - spring-5-reactive-security/pom.xml | 1 - spring-5-reactive/pom.xml | 1 - spring-5/pom.xml | 1 - testing-modules/testing-assertions/pom.xml | 4 ---- video-tutorials/jackson-annotations/pom.xml | 1 - xml/pom.xml | 1 - 30 files changed, 3 insertions(+), 60 deletions(-) diff --git a/algorithms-miscellaneous-3/pom.xml b/algorithms-miscellaneous-3/pom.xml index 525a2556de..11a64eba8b 100644 --- a/algorithms-miscellaneous-3/pom.xml +++ b/algorithms-miscellaneous-3/pom.xml @@ -37,7 +37,7 @@ org.apache.commons commons-lang3 - ${commons.lang3.version} + ${commons-lang3.version} pl.pragmatists @@ -63,10 +63,8 @@ - 4.3 28.0-jre 2.6.0 - 3.8.1 1.1.0 diff --git a/core-java-modules/core-java-10/pom.xml b/core-java-modules/core-java-10/pom.xml index c3406751dc..e2ac8db919 100644 --- a/core-java-modules/core-java-10/pom.xml +++ b/core-java-modules/core-java-10/pom.xml @@ -39,7 +39,6 @@ 10 10 - 4.1 \ No newline at end of file diff --git a/core-java-modules/core-java-8/pom.xml b/core-java-modules/core-java-8/pom.xml index 85e289280b..89925bdbbb 100644 --- a/core-java-modules/core-java-8/pom.xml +++ b/core-java-modules/core-java-8/pom.xml @@ -43,9 +43,4 @@ - - - 4.1 - - \ No newline at end of file diff --git a/core-java-modules/core-java-9/pom.xml b/core-java-modules/core-java-9/pom.xml index 03a097e7a9..274d9ccb43 100644 --- a/core-java-modules/core-java-9/pom.xml +++ b/core-java-modules/core-java-9/pom.xml @@ -76,7 +76,6 @@ 1.9 1.9 25.1-jre - 4.1 \ No newline at end of file diff --git a/core-java-modules/core-java-collections-2/pom.xml b/core-java-modules/core-java-collections-2/pom.xml index 23100b1d87..e78f7b5dda 100644 --- a/core-java-modules/core-java-collections-2/pom.xml +++ b/core-java-modules/core-java-collections-2/pom.xml @@ -44,7 +44,6 @@ 7.1.0 - 4.1 1.3 diff --git a/core-java-modules/core-java-collections-array-list/pom.xml b/core-java-modules/core-java-collections-array-list/pom.xml index ca9c173947..6b040739e8 100644 --- a/core-java-modules/core-java-collections-array-list/pom.xml +++ b/core-java-modules/core-java-collections-array-list/pom.xml @@ -22,8 +22,4 @@ - - 4.1 - - \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-2/pom.xml b/core-java-modules/core-java-collections-list-2/pom.xml index 7876b19cf9..59ab8c5f27 100644 --- a/core-java-modules/core-java-collections-list-2/pom.xml +++ b/core-java-modules/core-java-collections-list-2/pom.xml @@ -28,8 +28,4 @@ - - 4.1 - - \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-3/pom.xml b/core-java-modules/core-java-collections-list-3/pom.xml index 9238939df7..3bb0fb4a33 100644 --- a/core-java-modules/core-java-collections-list-3/pom.xml +++ b/core-java-modules/core-java-collections-list-3/pom.xml @@ -54,7 +54,6 @@ - 4.1 3.0.2 8.1.0 1.2.0 diff --git a/core-java-modules/core-java-collections-list/pom.xml b/core-java-modules/core-java-collections-list/pom.xml index b60906d1ba..0cc8828a0d 100644 --- a/core-java-modules/core-java-collections-list/pom.xml +++ b/core-java-modules/core-java-collections-list/pom.xml @@ -27,8 +27,4 @@ - - 4.1 - - \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps-2/pom.xml b/core-java-modules/core-java-collections-maps-2/pom.xml index 060796fafa..36b15c24d5 100644 --- a/core-java-modules/core-java-collections-maps-2/pom.xml +++ b/core-java-modules/core-java-collections-maps-2/pom.xml @@ -55,7 +55,6 @@ 0.6.5 - 4.1 1.7.0 8.2.0 0.7.2 diff --git a/core-java-modules/core-java-collections-maps/pom.xml b/core-java-modules/core-java-collections-maps/pom.xml index 66aca9c1b2..34b878df53 100644 --- a/core-java-modules/core-java-collections-maps/pom.xml +++ b/core-java-modules/core-java-collections-maps/pom.xml @@ -22,8 +22,4 @@ - - 4.1 - - \ No newline at end of file diff --git a/core-java-modules/core-java-collections-set/pom.xml b/core-java-modules/core-java-collections-set/pom.xml index 359c0fc86f..0b6e324c78 100644 --- a/core-java-modules/core-java-collections-set/pom.xml +++ b/core-java-modules/core-java-collections-set/pom.xml @@ -49,7 +49,6 @@ 11 11 - 4.3 2.8.5 diff --git a/core-java-modules/core-java-concurrency-advanced/pom.xml b/core-java-modules/core-java-concurrency-advanced/pom.xml index a026bdb2cd..b50a66cefc 100644 --- a/core-java-modules/core-java-concurrency-advanced/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced/pom.xml @@ -56,7 +56,6 @@ 21.0 3.6.1 - 4.1 4.01 1.7.0 diff --git a/core-java-modules/core-java-os/pom.xml b/core-java-modules/core-java-os/pom.xml index 970c8a562a..c24824dfb7 100644 --- a/core-java-modules/core-java-os/pom.xml +++ b/core-java-modules/core-java-os/pom.xml @@ -69,7 +69,6 @@ - 4.1 4.01 1.8.9 1.9 diff --git a/gson/pom.xml b/gson/pom.xml index a928d87b61..082e53baf0 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -61,10 +61,7 @@ - 2.8.0 - - 4.1 2.9.6 diff --git a/guava-modules/guava-collections-list/pom.xml b/guava-modules/guava-collections-list/pom.xml index 1b989e79b0..6863b4011c 100644 --- a/guava-modules/guava-collections-list/pom.xml +++ b/guava-modules/guava-collections-list/pom.xml @@ -45,9 +45,6 @@ - - 4.1 - 2.0.0.0 diff --git a/guava-modules/guava-collections/pom.xml b/guava-modules/guava-collections/pom.xml index 7929283616..9283107023 100644 --- a/guava-modules/guava-collections/pom.xml +++ b/guava-modules/guava-collections/pom.xml @@ -50,10 +50,7 @@ - - 4.1 0.9.12 - 2.0.0.0 diff --git a/java-collections-conversions/pom.xml b/java-collections-conversions/pom.xml index ae800b21c1..7f5ba38e3e 100644 --- a/java-collections-conversions/pom.xml +++ b/java-collections-conversions/pom.xml @@ -38,8 +38,4 @@ - - 4.4 - - \ No newline at end of file diff --git a/java-collections-maps-3/pom.xml b/java-collections-maps-3/pom.xml index 6f724ab5ef..81466b17ba 100644 --- a/java-collections-maps-3/pom.xml +++ b/java-collections-maps-3/pom.xml @@ -30,7 +30,6 @@ - 4.1 5.2.5.RELEASE diff --git a/json/pom.xml b/json/pom.xml index 2919a3a4ee..dfe42ee4c1 100644 --- a/json/pom.xml +++ b/json/pom.xml @@ -74,7 +74,6 @@ 1.4.1 1.2.21 1.0 - 4.1 1.0.1 20171018 2.8.5 diff --git a/libraries-6/pom.xml b/libraries-6/pom.xml index accf5f3a9a..3b932f2bd2 100644 --- a/libraries-6/pom.xml +++ b/libraries-6/pom.xml @@ -146,7 +146,6 @@ 3.5-beta72 3.0 1.8.1 - 4.4 8.12.9 2.4.4 diff --git a/libraries-apache-commons-collections/pom.xml b/libraries-apache-commons-collections/pom.xml index 2cb73babe6..c1a158b16e 100644 --- a/libraries-apache-commons-collections/pom.xml +++ b/libraries-apache-commons-collections/pom.xml @@ -16,7 +16,7 @@ org.apache.commons commons-collections4 - ${commons.collections.version} + ${commons-collections4.version} org.hamcrest @@ -27,7 +27,6 @@ - 4.1 2.0.0.0 diff --git a/pom.xml b/pom.xml index 8a27d67d65..0aab7b3a02 100644 --- a/pom.xml +++ b/pom.xml @@ -1421,6 +1421,7 @@ 1.33 1.33 2.21.0 + 4.4 2.11.0 2.6 3.12.0 diff --git a/spring-5-reactive-client/pom.xml b/spring-5-reactive-client/pom.xml index 136f31b49e..4821d0fc6d 100644 --- a/spring-5-reactive-client/pom.xml +++ b/spring-5-reactive-client/pom.xml @@ -153,7 +153,6 @@ 1.1.3 1.0 1.0 - 4.1 1.1.6 4.0.1 diff --git a/spring-5-reactive-security/pom.xml b/spring-5-reactive-security/pom.xml index 267a683fa7..140c6b8296 100644 --- a/spring-5-reactive-security/pom.xml +++ b/spring-5-reactive-security/pom.xml @@ -123,7 +123,6 @@ 1.1.3 1.0 1.0 - 4.1 3.1.6.RELEASE diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index 408573198b..b9456c7181 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -153,7 +153,6 @@ 1.1.3 1.0 1.0 - 4.1 \ No newline at end of file diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 5799f3bc8f..1ac696e7bd 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -142,7 +142,6 @@ 1.0 1.5.6 - 4.1 ${project.build.directory}/generated-snippets 4.0.3 diff --git a/testing-modules/testing-assertions/pom.xml b/testing-modules/testing-assertions/pom.xml index 689ca35733..09f4291b78 100644 --- a/testing-modules/testing-assertions/pom.xml +++ b/testing-modules/testing-assertions/pom.xml @@ -26,8 +26,4 @@ - - 4.4 - - \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/pom.xml b/video-tutorials/jackson-annotations/pom.xml index 29f457964b..eaec50c1f7 100644 --- a/video-tutorials/jackson-annotations/pom.xml +++ b/video-tutorials/jackson-annotations/pom.xml @@ -116,7 +116,6 @@ 2.9.6 2.8.0 - 4.1 3.0.1 3.0.0 diff --git a/xml/pom.xml b/xml/pom.xml index 968682ee38..0764c9d145 100644 --- a/xml/pom.xml +++ b/xml/pom.xml @@ -355,7 +355,6 @@ 1.2.0 2.0.6 1.6.2 - 4.1 1.2.4.5 2.3.1 1.4.2 From 46b2848a644e074f57326f16952aa9cb98d18f83 Mon Sep 17 00:00:00 2001 From: davidmartinezbarua Date: Fri, 26 Nov 2021 10:56:17 -0300 Subject: [PATCH 39/65] Revert "Spring Webflux and @Cacheable Annotation" --- spring-5-webflux/pom.xml | 20 ---- .../com/baeldung/spring/caching/Item.java | 50 ---------- .../spring/caching/ItemRepository.java | 8 -- .../baeldung/spring/caching/ItemService.java | 42 -------- .../SpringWebfluxCachingApplication.java | 16 ---- .../resources/application-cache.properties | 2 - .../MonoFluxResultCachingLiveTest.java | 95 ------------------- 7 files changed, 233 deletions(-) delete mode 100644 spring-5-webflux/src/main/java/com/baeldung/spring/caching/Item.java delete mode 100644 spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemRepository.java delete mode 100644 spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemService.java delete mode 100644 spring-5-webflux/src/main/java/com/baeldung/spring/caching/SpringWebfluxCachingApplication.java delete mode 100644 spring-5-webflux/src/main/resources/application-cache.properties delete mode 100644 spring-5-webflux/src/test/java/com/baeldung/spring/caching/MonoFluxResultCachingLiveTest.java diff --git a/spring-5-webflux/pom.xml b/spring-5-webflux/pom.xml index d6afb686fc..69de83c227 100644 --- a/spring-5-webflux/pom.xml +++ b/spring-5-webflux/pom.xml @@ -66,31 +66,11 @@ - - io.projectreactor.addons - reactor-extra - 3.4.5 - - - com.github.ben-manes.caffeine - caffeine - 2.9.2 - - - org.springframework.boot - spring-boot-starter-data-mongodb-reactive - io.projectreactor reactor-test test - - org.testcontainers - mongodb - 1.16.2 - test - com.squareup.okhttp3 mockwebserver diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/Item.java b/spring-5-webflux/src/main/java/com/baeldung/spring/caching/Item.java deleted file mode 100644 index 7b79ff7503..0000000000 --- a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/Item.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.spring.caching; - -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; - -@Document -public class Item { - - @Id - private String _id; - private String name; - private double price; - - public Item(String name, double price) { - this.name = name; - this.price = price; - } - - public Item() { - } - - public String get_id() { - return _id; - } - - 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; - } - - @Override - public String toString() { - return "Item{" + - "id='" + _id + '\'' + - ", name='" + name + '\'' + - ", price=" + price + - '}'; - } -} diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemRepository.java b/spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemRepository.java deleted file mode 100644 index 27c97de36a..0000000000 --- a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.spring.caching; - -import org.springframework.data.mongodb.repository.ReactiveMongoRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface ItemRepository extends ReactiveMongoRepository { -} diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemService.java b/spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemService.java deleted file mode 100644 index b24b54521e..0000000000 --- a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemService.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.spring.caching; - -import com.github.benmanes.caffeine.cache.Caffeine; -import com.github.benmanes.caffeine.cache.LoadingCache; -import org.springframework.cache.annotation.Cacheable; -import org.springframework.stereotype.Service; -import reactor.cache.CacheMono; -import reactor.core.publisher.Mono; - -@Service -public class ItemService { - - private final ItemRepository repository; - private final LoadingCache cache; - - public ItemService(ItemRepository repository) { - this.repository = repository; - this.cache = Caffeine.newBuilder() - .build(this::getItem_withAddons); - } - - @Cacheable("items") - public Mono getItem(String id) { - return repository.findById(id); - } - - public Mono save(Item item) { - return repository.save(item); - } - - @Cacheable("items") - public Mono getItem_withCache(String id) { - return repository.findById(id).cache(); - } - - @Cacheable("items") - public Mono getItem_withAddons(String id) { - return CacheMono.lookup(cache.asMap(), id) - .onCacheMissResume(() -> repository.findById(id).cast(Object.class)).cast(Item.class); - } - -} diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/SpringWebfluxCachingApplication.java b/spring-5-webflux/src/main/java/com/baeldung/spring/caching/SpringWebfluxCachingApplication.java deleted file mode 100644 index 5266e33775..0000000000 --- a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/SpringWebfluxCachingApplication.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.spring.caching; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cache.annotation.EnableCaching; -import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; - -@SpringBootApplication -@EnableMongoRepositories -@EnableCaching -public class SpringWebfluxCachingApplication { - - public static void main(String[] args) { - SpringApplication.run(SpringWebfluxCachingApplication.class, args); - } -} diff --git a/spring-5-webflux/src/main/resources/application-cache.properties b/spring-5-webflux/src/main/resources/application-cache.properties deleted file mode 100644 index 23414da2dd..0000000000 --- a/spring-5-webflux/src/main/resources/application-cache.properties +++ /dev/null @@ -1,2 +0,0 @@ -logging.level.org.springframework.data.mongodb.core.ReactiveMongoTemplate=DEBUG -logging.level.org.springframework.cache=TRACE \ No newline at end of file diff --git a/spring-5-webflux/src/test/java/com/baeldung/spring/caching/MonoFluxResultCachingLiveTest.java b/spring-5-webflux/src/test/java/com/baeldung/spring/caching/MonoFluxResultCachingLiveTest.java deleted file mode 100644 index 322b3c5aa5..0000000000 --- a/spring-5-webflux/src/test/java/com/baeldung/spring/caching/MonoFluxResultCachingLiveTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.baeldung.spring.caching; - - -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.DynamicPropertyRegistry; -import org.springframework.test.context.DynamicPropertySource; -import org.testcontainers.containers.MongoDBContainer; -import org.testcontainers.utility.DockerImageName; -import reactor.core.publisher.Mono; - -import static org.assertj.core.api.Assertions.assertThat; - -@SpringBootTest -@ActiveProfiles("cache") -public class MonoFluxResultCachingLiveTest { - - - @Autowired - ItemService itemService; - - final static MongoDBContainer mongoDBContainer = new MongoDBContainer(DockerImageName.parse("mongo:4.0.10")); - - @DynamicPropertySource - static void mongoDbProperties(DynamicPropertyRegistry registry) { - mongoDBContainer.start(); - registry.add("spring.data.mongodb.uri", mongoDBContainer::getReplicaSetUrl); - } - -@Test -public void givenItem_whenGetItemIsCalled_thenMonoIsCached() { - Mono glass = itemService.save(new Item("glass", 1.00)); - - String id = glass.block().get_id(); - - Mono mono = itemService.getItem(id); - Item item = mono.block(); - - assertThat(item).isNotNull(); - assertThat(item.getName()).isEqualTo("glass"); - assertThat(item.getPrice()).isEqualTo(1.00); - - Mono mono2 = itemService.getItem(id); - Item item2 = mono2.block(); - - assertThat(item2).isNotNull(); - assertThat(item2.getName()).isEqualTo("glass"); - assertThat(item2.getPrice()).isEqualTo(1.00); -} - - @Test - public void givenItem_whenGetItemWithCacheIsCalled_thenMonoResultIsCached() { - Mono glass = itemService.save(new Item("glass", 1.00)); - - String id = glass.block().get_id(); - - Mono mono = itemService.getItem_withCache(id); - Item item = mono.block(); - - assertThat(item).isNotNull(); - assertThat(item.getName()).isEqualTo("glass"); - assertThat(item.getPrice()).isEqualTo(1.00); - - Mono mono2 = itemService.getItem_withCache(id); - Item item2 = mono2.block(); - - assertThat(item2).isNotNull(); - assertThat(item2.getName()).isEqualTo("glass"); - assertThat(item2.getPrice()).isEqualTo(1.00); - } - - @Test - public void givenItem_whenGetItemWithAddonsIsCalled_thenMonoResultIsCached() { - Mono glass = itemService.save(new Item("glass", 1.00)); - - String id = glass.block().get_id(); - - Mono mono = itemService.getItem_withAddons(id); - Item item = mono.block(); - - assertThat(item).isNotNull(); - assertThat(item.getName()).isEqualTo("glass"); - assertThat(item.getPrice()).isEqualTo(1.00); - - Mono mono2 = itemService.getItem_withAddons(id); - Item item2 = mono2.block(); - - assertThat(item2).isNotNull(); - assertThat(item2.getName()).isEqualTo("glass"); - assertThat(item2.getPrice()).isEqualTo(1.00); - } - -} From 2b043a7f1f66c5ca1b842d31a4a3019dd4c79042 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Fri, 26 Nov 2021 19:28:29 +0530 Subject: [PATCH 40/65] JAVA-8620: Fix references to parents --- aws-lambda/lambda/pom.xml | 3 +-- aws-lambda/pom.xml | 1 - cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml | 3 +-- cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml | 3 +-- cloud-foundry-uaa/pom.xml | 6 +++--- spf4j/spf4j-aspects-app/pom.xml | 5 ++--- spf4j/spf4j-core-app/pom.xml | 5 ++--- spring-boot-modules/spring-boot-camel/pom.xml | 7 +++---- spring-boot-modules/spring-boot-cassandre/pom.xml | 7 +++---- .../spring-boot-custom-starter/greeter/pom.xml | 5 ++--- .../parent-multi-module/application/pom.xml | 3 +-- .../parent-multi-module/library/pom.xml | 3 +-- .../spring-boot-custom-starter/parent-multi-module/pom.xml | 6 ++++++ spring-boot-modules/spring-boot-groovy/pom.xml | 7 +++---- .../property-exp-default-config/pom.xml | 5 ++--- spring-boot-modules/spring-boot-validation/pom.xml | 7 +++---- 16 files changed, 34 insertions(+), 42 deletions(-) diff --git a/aws-lambda/lambda/pom.xml b/aws-lambda/lambda/pom.xml index b2e5cc3b2d..8bfe7a0ade 100644 --- a/aws-lambda/lambda/pom.xml +++ b/aws-lambda/lambda/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-modules + aws-lambda 1.0.0-SNAPSHOT - ../../ diff --git a/aws-lambda/pom.xml b/aws-lambda/pom.xml index 3264356977..fc655f282d 100644 --- a/aws-lambda/pom.xml +++ b/aws-lambda/pom.xml @@ -11,7 +11,6 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT - ../ diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml b/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml index 74603bf0fb..7fcce181a3 100644 --- a/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml +++ b/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + cloud-foundry-uaa 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml index 276c8bbaa6..4dffd4d768 100644 --- a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml +++ b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + cloud-foundry-uaa 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/cloud-foundry-uaa/pom.xml b/cloud-foundry-uaa/pom.xml index 03a5b978d4..6ae43b2c08 100644 --- a/cloud-foundry-uaa/pom.xml +++ b/cloud-foundry-uaa/pom.xml @@ -4,14 +4,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 cloud-foundry-uaa - 0.0.1-SNAPSHOT cloud-foundry-uaa pom com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 diff --git a/spf4j/spf4j-aspects-app/pom.xml b/spf4j/spf4j-aspects-app/pom.xml index c4940b9c97..09ca41ea47 100644 --- a/spf4j/spf4j-aspects-app/pom.xml +++ b/spf4j/spf4j-aspects-app/pom.xml @@ -9,10 +9,9 @@ jar - com.baeldung - parent-modules + com.baeldung.spf4j + spf4j 1.0.0-SNAPSHOT - ../../ diff --git a/spf4j/spf4j-core-app/pom.xml b/spf4j/spf4j-core-app/pom.xml index 28c104afe1..2f7f3745f1 100644 --- a/spf4j/spf4j-core-app/pom.xml +++ b/spf4j/spf4j-core-app/pom.xml @@ -9,10 +9,9 @@ jar - com.baeldung - parent-modules + com.baeldung.spf4j + spf4j 1.0.0-SNAPSHOT - ../../ diff --git a/spring-boot-modules/spring-boot-camel/pom.xml b/spring-boot-modules/spring-boot-camel/pom.xml index 0069dfdbff..5d5e2ce6bd 100644 --- a/spring-boot-modules/spring-boot-camel/pom.xml +++ b/spring-boot-modules/spring-boot-camel/pom.xml @@ -9,10 +9,9 @@ spring-boot-camel - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT diff --git a/spring-boot-modules/spring-boot-cassandre/pom.xml b/spring-boot-modules/spring-boot-cassandre/pom.xml index 14849e50d7..1f2931a2bf 100644 --- a/spring-boot-modules/spring-boot-cassandre/pom.xml +++ b/spring-boot-modules/spring-boot-cassandre/pom.xml @@ -9,10 +9,9 @@ Cassandre trading bot tutorial - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter/pom.xml b/spring-boot-modules/spring-boot-custom-starter/greeter/pom.xml index f96880b1cf..5c0580d29a 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter/pom.xml +++ b/spring-boot-modules/spring-boot-custom-starter/greeter/pom.xml @@ -8,10 +8,9 @@ greeter - com.baeldung - parent-boot-2 + com.baeldung.spring-boot-modules + spring-boot-custom-starter 0.0.1-SNAPSHOT - ../../../parent-boot-2 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/application/pom.xml b/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/application/pom.xml index 1c26ec32d3..a00c3a3c57 100644 --- a/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/application/pom.xml +++ b/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/application/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-boot-2 + parent-multi-module 0.0.1-SNAPSHOT - ../../../../parent-boot-2 diff --git a/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/library/pom.xml b/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/library/pom.xml index 5d45de0d1d..6e7b3ce78a 100644 --- a/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/library/pom.xml +++ b/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/library/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-boot-2 + parent-multi-module 0.0.1-SNAPSHOT - ../../../../parent-boot-2 diff --git a/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/pom.xml b/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/pom.xml index 2a483a8fef..4bc8434d43 100644 --- a/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/pom.xml +++ b/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/pom.xml @@ -8,6 +8,12 @@ 0.0.1-SNAPSHOT pom + + com.baeldung.spring-boot-modules + spring-boot-custom-starter + 0.0.1-SNAPSHOT + + library application diff --git a/spring-boot-modules/spring-boot-groovy/pom.xml b/spring-boot-modules/spring-boot-groovy/pom.xml index ea9f3231cd..820bb0fd7a 100644 --- a/spring-boot-modules/spring-boot-groovy/pom.xml +++ b/spring-boot-modules/spring-boot-groovy/pom.xml @@ -10,10 +10,9 @@ Spring Boot Todo Application with Groovy - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT diff --git a/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/pom.xml b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/pom.xml index 496004b0e2..b1c44de9a9 100644 --- a/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/pom.xml +++ b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/pom.xml @@ -9,10 +9,9 @@ jar - com.baeldung - parent-boot-2 + com.baeldung.spring-boot-modules + spring-boot-property-exp 0.0.1-SNAPSHOT - ../../../parent-boot-2 diff --git a/spring-boot-modules/spring-boot-validation/pom.xml b/spring-boot-modules/spring-boot-validation/pom.xml index 86e0a47d0d..fa4e8439e6 100644 --- a/spring-boot-modules/spring-boot-validation/pom.xml +++ b/spring-boot-modules/spring-boot-validation/pom.xml @@ -8,10 +8,9 @@ 0.0.1-SNAPSHOT - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT From be2d84b1f6fccd16fff9d787843b1229dfe67fad Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Fri, 26 Nov 2021 22:19:21 +0530 Subject: [PATCH 41/65] JAVA-8287: Split or move java-jpa-3 module --- persistence-modules/java-jpa-3/README.md | 1 - persistence-modules/java-mongodb/README.md | 1 + .../field}/FieldExistenceLiveTest.java | 0 3 files changed, 1 insertion(+), 1 deletion(-) rename persistence-modules/java-mongodb/src/test/java/com/baeldung/{existence.field => existence/field}/FieldExistenceLiveTest.java (100%) diff --git a/persistence-modules/java-jpa-3/README.md b/persistence-modules/java-jpa-3/README.md index 202c97a830..aa33644b17 100644 --- a/persistence-modules/java-jpa-3/README.md +++ b/persistence-modules/java-jpa-3/README.md @@ -13,5 +13,4 @@ This module contains articles about the Java Persistence API (JPA) in Java. - [Returning an Auto-Generated Id with JPA](https://www.baeldung.com/jpa-get-auto-generated-id) - [How to Return Multiple Entities In JPA Query](https://www.baeldung.com/jpa-return-multiple-entities) - [Defining Unique Constraints in JPA](https://www.baeldung.com/jpa-unique-constraints) -- [How to Check Field Existence in MongoDB?](https://www.baeldung.com/mongodb-check-field-exists) - [Connecting to a Specific Schema in JDBC](https://www.baeldung.com/jdbc-connect-to-schema) diff --git a/persistence-modules/java-mongodb/README.md b/persistence-modules/java-mongodb/README.md index f632e7c662..34acd60c57 100644 --- a/persistence-modules/java-mongodb/README.md +++ b/persistence-modules/java-mongodb/README.md @@ -11,3 +11,4 @@ This module contains articles about MongoDB in Java. - [Introduction to Morphia – Java ODM for MongoDB](https://www.baeldung.com/mongodb-morphia) - [MongoDB Aggregations Using Java](https://www.baeldung.com/java-mongodb-aggregations) - [BSON to JSON Document Conversion in Java](https://www.baeldung.com/java-convert-bson-to-json) +- [How to Check Field Existence in MongoDB?](https://www.baeldung.com/mongodb-check-field-exists) diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/existence.field/FieldExistenceLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/existence/field/FieldExistenceLiveTest.java similarity index 100% rename from persistence-modules/java-mongodb/src/test/java/com/baeldung/existence.field/FieldExistenceLiveTest.java rename to persistence-modules/java-mongodb/src/test/java/com/baeldung/existence/field/FieldExistenceLiveTest.java From 2eacd35589a7cddb0732f7b22555aae65e810ffb Mon Sep 17 00:00:00 2001 From: Muhammad Abdullah Azam Khan Date: Fri, 26 Nov 2021 20:54:37 +0400 Subject: [PATCH 42/65] Indentation and Formatting Changes --- .../baeldung/unsupportedmediatype/User.java | 10 ++--- .../ApplicationUnitTest.java | 38 +++++++++---------- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java index f9c3d9c191..765149dad5 100644 --- a/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java +++ b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java @@ -55,11 +55,11 @@ public class User implements Serializable { @Override public String toString() { return "User{" - + "id=" + id - + ", name='" + name + '\'' - + ", age=" + age - + ", address='" + address + '\'' - + '}'; + + "id=" + id + + ", name='" + name + '\'' + + ", age=" + age + + ", address='" + address + '\'' + + '}'; } diff --git a/spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java b/spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java index 95de780106..498ad9d537 100644 --- a/spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java +++ b/spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java @@ -20,39 +20,39 @@ public class ApplicationUnitTest { @Test public void JsonTestCase() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/user/") - .contentType(MediaType.APPLICATION_JSON_VALUE) - .content( "{\n" - + " \"name\": \"Andy\",\n" - + " \"age\": 1,\n" - + " \"address\": \"Hello world\"\n" - + "}")) - .andExpect(status().isOk()); + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content( "{\n" + + " \"name\": \"Andy\",\n" + + " \"age\": 1,\n" + + " \"address\": \"Hello world\"\n" + + "}")) + .andExpect(status().isOk()); } @Test public void JsonFailTestCase() throws Exception {// Because no content-type added mockMvc.perform(MockMvcRequestBuilders.post("/user/") - .content( "{\n" - + " \"name\": \"Andy\",\n" - + " \"age\": 1,\n" - + " \"address\": \"Hello world\"\n" - + "}")) - .andExpect(status().isUnsupportedMediaType()); + .content( "{\n" + + " \"name\": \"Andy\",\n" + + " \"age\": 1,\n" + + " \"address\": \"Hello world\"\n" + + "}")) + .andExpect(status().isUnsupportedMediaType()); } @Test public void XmlTestCase() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/user/") - .contentType(MediaType.APPLICATION_XML_VALUE) - .content("Andy1
Hello world
")) - .andExpect(status().isOk()); + .contentType(MediaType.APPLICATION_XML_VALUE) + .content("Andy1
Hello world
")) + .andExpect(status().isOk()); } @Test public void StringFailTestCase() throws Exception { // Because content-type is not supported mockMvc.perform(MockMvcRequestBuilders.post("/user/") - .contentType(MediaType.TEXT_PLAIN_VALUE) - .content("Andy1
Hello world
")) - .andExpect(status().isUnsupportedMediaType()); + .contentType(MediaType.TEXT_PLAIN_VALUE) + .content("Andy1
Hello world
")) + .andExpect(status().isUnsupportedMediaType()); } } From 7a9a69bda346d0ca92c6227b5a38ec709c602f6f Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Fri, 26 Nov 2021 18:06:20 +0100 Subject: [PATCH 43/65] BAEL-5076 Unix domain socket in Java 16 (#11493) * BAEL-5076 Unix domain socket in Java 16 * BAEL-5076 Unix domain socket in Java 16 * BAEL-5076 Unix domain socket in Java 16 * BAEL-5076 Unix domain socket in Java 16 Co-authored-by: krzysztof --- .../core-java-networking-3/pom.xml | 10 +++ .../socket/UnixDomainSocketClient.java | 49 +++++++++++ .../socket/UnixDomainSocketServer.java | 57 +++++++++++++ .../UnixDomainSocketClientUnitTest.java | 82 +++++++++++++++++++ .../UnixDomainSocketServerUnitTest.java | 50 +++++++++++ core-java-modules/pom.xml | 1 - pom.xml | 2 + 7 files changed, 250 insertions(+), 1 deletion(-) create mode 100644 core-java-modules/core-java-networking-3/src/main/java/com/baeldung/socket/UnixDomainSocketClient.java create mode 100644 core-java-modules/core-java-networking-3/src/main/java/com/baeldung/socket/UnixDomainSocketServer.java create mode 100644 core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/UnixDomainSocketClientUnitTest.java create mode 100644 core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/UnixDomainSocketServerUnitTest.java diff --git a/core-java-modules/core-java-networking-3/pom.xml b/core-java-modules/core-java-networking-3/pom.xml index ee822e57cb..297d665544 100644 --- a/core-java-modules/core-java-networking-3/pom.xml +++ b/core-java-modules/core-java-networking-3/pom.xml @@ -64,6 +64,16 @@ + + + org.apache.maven.plugins + maven-compiler-plugin + + 16 + 16 + + + diff --git a/core-java-modules/core-java-networking-3/src/main/java/com/baeldung/socket/UnixDomainSocketClient.java b/core-java-modules/core-java-networking-3/src/main/java/com/baeldung/socket/UnixDomainSocketClient.java new file mode 100644 index 0000000000..2a8ae05628 --- /dev/null +++ b/core-java-modules/core-java-networking-3/src/main/java/com/baeldung/socket/UnixDomainSocketClient.java @@ -0,0 +1,49 @@ +package com.baeldung.socket; + +import java.io.IOException; +import java.net.StandardProtocolFamily; +import java.net.UnixDomainSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; +import java.nio.file.Path; + +class UnixDomainSocketClient { + + public static void main(String[] args) throws Exception { + new UnixDomainSocketClient().runClient(); + } + + void runClient() throws IOException { + Path socketPath = Path.of(System.getProperty("user.home")) + .resolve("baeldung.socket"); + UnixDomainSocketAddress socketAddress = getAddress(socketPath); + + SocketChannel channel = openSocketChannel(socketAddress); + + String message = "Hello from Baeldung Unix domain socket article"; + writeMessage(channel, message); + } + + UnixDomainSocketAddress getAddress(Path socketPath) { + return UnixDomainSocketAddress.of(socketPath); + } + + SocketChannel openSocketChannel(UnixDomainSocketAddress socketAddress) throws IOException { + SocketChannel channel = SocketChannel + .open(StandardProtocolFamily.UNIX); + channel.connect(socketAddress); + return channel; + } + + void writeMessage(SocketChannel socketChannel, String message) throws IOException { + ByteBuffer buffer = ByteBuffer.allocate(1024); + buffer.clear(); + buffer.put(message.getBytes()); + buffer.flip(); + + while (buffer.hasRemaining()) { + socketChannel.write(buffer); + } + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-networking-3/src/main/java/com/baeldung/socket/UnixDomainSocketServer.java b/core-java-modules/core-java-networking-3/src/main/java/com/baeldung/socket/UnixDomainSocketServer.java new file mode 100644 index 0000000000..c3093ae00c --- /dev/null +++ b/core-java-modules/core-java-networking-3/src/main/java/com/baeldung/socket/UnixDomainSocketServer.java @@ -0,0 +1,57 @@ +package com.baeldung.socket; + +import java.io.IOException; +import java.net.StandardProtocolFamily; +import java.net.UnixDomainSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Optional; + +class UnixDomainSocketServer { + + public static void main(String[] args) throws IOException, InterruptedException { + new UnixDomainSocketServer().runServer(); + } + + void runServer() throws IOException, InterruptedException { + Path socketPath = Path.of(System.getProperty("user.home")) + .resolve("baeldung.socket"); + Files.deleteIfExists(socketPath); + UnixDomainSocketAddress socketAddress = getAddress(socketPath); + + ServerSocketChannel serverChannel = createServerSocketChannel(socketAddress); + + SocketChannel channel = serverChannel.accept(); + + while (true) { + readSocketMessage(channel) + .ifPresent(message -> System.out.printf("[Client message] %s%n", message)); + Thread.sleep(100); + } + } + + UnixDomainSocketAddress getAddress(Path socketPath) { + return UnixDomainSocketAddress.of(socketPath); + } + + ServerSocketChannel createServerSocketChannel(UnixDomainSocketAddress socketAddress) throws IOException { + ServerSocketChannel serverChannel = ServerSocketChannel.open(StandardProtocolFamily.UNIX); + serverChannel.bind(socketAddress); + return serverChannel; + } + + Optional readSocketMessage(SocketChannel channel) throws IOException { + ByteBuffer buffer = ByteBuffer.allocate(1024); + int bytesRead = channel.read(buffer); + if (bytesRead < 0) return Optional.empty(); + byte[] bytes = new byte[bytesRead]; + buffer.flip(); + buffer.get(bytes); + String message = new String(bytes); + return Optional.of(message); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/UnixDomainSocketClientUnitTest.java b/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/UnixDomainSocketClientUnitTest.java new file mode 100644 index 0000000000..8cd2ee94d4 --- /dev/null +++ b/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/UnixDomainSocketClientUnitTest.java @@ -0,0 +1,82 @@ +package com.baeldung.socket; + +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.stubbing.Answer; + +import java.io.File; +import java.io.IOException; +import java.net.StandardProtocolFamily; +import java.net.UnixDomainSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.nio.file.Path; +import java.util.UUID; + +import static java.nio.file.Files.deleteIfExists; +import static org.assertj.core.util.Files.newTemporaryFile; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class UnixDomainSocketClientUnitTest { + + @Test + public void givenSocketPath_shouldCreateUnixDomainSocketAddress() { + // given + File tempFile = newTemporaryFile(); + Path socketPath = tempFile.toPath(); + + // when + UnixDomainSocketAddress address = new UnixDomainSocketClient().getAddress(socketPath); + + // then + assertEquals(address.getPath(), socketPath); + + // cleanup + tempFile.delete(); + } + + @Test + public void givenUnixDomainSocketAddress_shouldOpenSocketChannel() throws IOException { + // given + File tempFile = newTemporaryFile(); + Path socketPath = tempFile.toPath(); + deleteIfExists(socketPath); + UnixDomainSocketAddress address = UnixDomainSocketAddress.of(socketPath); + + // bind address as a unix domain socket + ServerSocketChannel serverChannel = ServerSocketChannel.open(StandardProtocolFamily.UNIX); + serverChannel.bind(address); + + // when + SocketChannel socketChannel = new UnixDomainSocketClient().openSocketChannel(address); + + // then + assertTrue(socketChannel.isOpen()); + assertEquals(socketChannel.getRemoteAddress(), address); + + // cleanup + tempFile.delete(); + } + + @Test + public void givenSocketChannelAndMessage_shouldWriteMessage() throws IOException { + // given + SocketChannel socketChannel = Mockito.mock(SocketChannel.class); + String message = UUID.randomUUID().toString(); + Mockito.when(socketChannel.write(Mockito.any(ByteBuffer.class))) + .thenAnswer( + (Answer) invocationOnMock -> { + ((ByteBuffer) invocationOnMock.getArguments()[0]).position(message.getBytes().length); + return -1; + } + ); + + // when + new UnixDomainSocketClient().writeMessage(socketChannel, message); + + // then + Mockito.verify(socketChannel, Mockito.times(1)).write(Mockito.any(ByteBuffer.class)); + } +} diff --git a/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/UnixDomainSocketServerUnitTest.java b/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/UnixDomainSocketServerUnitTest.java new file mode 100644 index 0000000000..1d0a68ac2f --- /dev/null +++ b/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/UnixDomainSocketServerUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.socket; + +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import java.net.UnixDomainSocketAddress; +import java.nio.channels.ServerSocketChannel; +import java.nio.file.Path; + +import static java.nio.file.Files.deleteIfExists; +import static org.assertj.core.util.Files.newTemporaryFile; +import static org.junit.Assert.assertEquals; + +public class UnixDomainSocketServerUnitTest { + + @Test + public void givenSocketPath_shouldCreateUnixDomainSocketAddress() { + // given + File tempFile = newTemporaryFile(); + Path socketPath = tempFile.toPath(); + + // when + UnixDomainSocketAddress address = new UnixDomainSocketServer().getAddress(socketPath); + + // then + assertEquals(address.getPath(), socketPath); + + // cleanup + tempFile.delete(); + } + + @Test + public void givenUnixDomainSocketAddress_shouldCreateServerSocketChannel() throws IOException { + // given + File tempFile = newTemporaryFile(); + Path socketPath = tempFile.toPath(); + deleteIfExists(socketPath); + UnixDomainSocketAddress address = UnixDomainSocketAddress.of(socketPath); + + // when + ServerSocketChannel serverSocketChannel = new UnixDomainSocketServer().createServerSocketChannel(address); + + // then + assertEquals(serverSocketChannel.getLocalAddress(), address); + + // cleanup + tempFile.delete(); + } +} diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index a57cd54191..d9da5a845b 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -90,7 +90,6 @@ core-java-lang-syntax-2 core-java-networking core-java-networking-2 - core-java-networking-3 core-java-nio core-java-nio-2 core-java-optional diff --git a/pom.xml b/pom.xml index 845b32615a..a2bd38bc06 100644 --- a/pom.xml +++ b/pom.xml @@ -1322,6 +1322,7 @@ core-java-modules/core-java-string-operations-3 core-java-modules/core-java-string-operations-4 core-java-modules/core-java-time-measurements + core-java-modules/core-java-networking-3 core-java-modules/multimodulemavenproject persistence-modules/sirix quarkus-vs-springboot @@ -1375,6 +1376,7 @@ core-java-modules/core-java-os core-java-modules/core-java-string-operations-3 core-java-modules/core-java-time-measurements + core-java-modules/core-java-networking-3 core-java-modules/multimodulemavenproject core-java-modules/core-java-strings persistence-modules/sirix From 4ea08dc79eeddbfce06c1a1dd2315439a9b5b8fc Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Fri, 26 Nov 2021 18:07:02 +0100 Subject: [PATCH 44/65] JAVA-8710: Update to lombok 1.8.22 --- core-java-modules/core-java-os/pom.xml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/core-java-modules/core-java-os/pom.xml b/core-java-modules/core-java-os/pom.xml index 970c8a562a..d2bf842897 100644 --- a/core-java-modules/core-java-os/pom.xml +++ b/core-java-modules/core-java-os/pom.xml @@ -45,6 +45,12 @@ grep4j ${grep4j.version}
+ + org.projectlombok + lombok + ${lombok.version} + provided + @@ -77,6 +83,7 @@ 25.1-jre 0.4 1.8.7 + 1.18.22 From 56acdb274fd0c897447d8554a291d86ecf6c51eb Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Fri, 26 Nov 2021 22:15:04 +0000 Subject: [PATCH 45/65] [JAVA-8353] Wait longer for the threads to finish --- .../IllegalMonitorStateExceptionUnitTest.java | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java b/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java index bef90e671f..857ab02c13 100644 --- a/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java +++ b/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java @@ -1,11 +1,12 @@ package com.baeldung.exceptions.illegalmonitorstate; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.junit.jupiter.api.Test; -import java.time.Duration; - -import static org.junit.jupiter.api.Assertions.*; - public class IllegalMonitorStateExceptionUnitTest { @Test @@ -20,11 +21,11 @@ public class IllegalMonitorStateExceptionUnitTest { Thread senderThread = new Thread(sender, "sender-thread"); senderThread.start(); - senderThread.join(1000); - receiverThread.join(1000); + // we need to wait for the sender and receiver threads to finish + senderThread.join(10_000); + receiverThread.join(10_000); - // we need to wait for enough time so that sender has had a chance to send the data - assertTimeout(Duration.ofSeconds(10), () -> assertEquals("test", receiver.getMessage())); + assertEquals("test", receiver.getMessage()); assertFalse(sender.hasIllegalMonitorStateExceptionOccurred()); assertFalse(receiver.hasIllegalMonitorStateExceptionOccurred()); } From f76a43a1ab23bff1e872de24508d8202b718d3e6 Mon Sep 17 00:00:00 2001 From: Mladen Savic Date: Sat, 27 Nov 2021 11:10:33 +0100 Subject: [PATCH 46/65] Spring Webflux and @Cacheable Annotation - moved to new package --- pom.xml | 3 + spring-5-webflux-2/README.md | 7 ++ spring-5-webflux-2/pom.xml | 102 ++++++++++++++++++ .../src/main/java}/caching/Item.java | 2 +- .../main/java}/caching/ItemRepository.java | 2 +- .../src/main/java}/caching/ItemService.java | 2 +- .../SpringWebfluxCachingApplication.java | 2 +- .../resources/application-cache.properties | 0 .../src/main/resources/logback.xml | 31 ++++++ .../MonoFluxResultCachingLiveTest.java | 2 +- .../src/test/resources/logback-test.xml | 13 +++ spring-5-webflux/README.md | 1 - spring-5-webflux/pom.xml | 20 ---- 13 files changed, 161 insertions(+), 26 deletions(-) create mode 100644 spring-5-webflux-2/README.md create mode 100644 spring-5-webflux-2/pom.xml rename {spring-5-webflux/src/main/java/com/baeldung/spring => spring-5-webflux-2/src/main/java}/caching/Item.java (96%) rename {spring-5-webflux/src/main/java/com/baeldung/spring => spring-5-webflux-2/src/main/java}/caching/ItemRepository.java (85%) rename {spring-5-webflux/src/main/java/com/baeldung/spring => spring-5-webflux-2/src/main/java}/caching/ItemService.java (96%) rename {spring-5-webflux/src/main/java/com/baeldung/spring => spring-5-webflux-2/src/main/java}/caching/SpringWebfluxCachingApplication.java (93%) rename {spring-5-webflux => spring-5-webflux-2}/src/main/resources/application-cache.properties (100%) create mode 100644 spring-5-webflux-2/src/main/resources/logback.xml rename {spring-5-webflux/src/test/java/com/baeldung/spring => spring-5-webflux-2/src/test/java}/caching/MonoFluxResultCachingLiveTest.java (98%) create mode 100644 spring-5-webflux-2/src/test/resources/logback-test.xml diff --git a/pom.xml b/pom.xml index a2bd38bc06..9581cfb004 100644 --- a/pom.xml +++ b/pom.xml @@ -7,6 +7,9 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + + spring-5-webflux-2 + parent-modules pom diff --git a/spring-5-webflux-2/README.md b/spring-5-webflux-2/README.md new file mode 100644 index 0000000000..0222ddbaa4 --- /dev/null +++ b/spring-5-webflux-2/README.md @@ -0,0 +1,7 @@ +## Spring 5 WebFlux 2 + +This module contains articles about Spring 5 WebFlux + +## Relevant articles: + +- [Spring Webflux and @Cacheable Annotation](https://www.baeldung.com/spring-webflux-cacheable) \ No newline at end of file diff --git a/spring-5-webflux-2/pom.xml b/spring-5-webflux-2/pom.xml new file mode 100644 index 0000000000..c90fcbe3d9 --- /dev/null +++ b/spring-5-webflux-2/pom.xml @@ -0,0 +1,102 @@ + + + 4.0.0 + spring-5-webflux-2 + spring-5-webflux-2 + http://www.baeldung.com + 1.0-SNAPSHOT + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + + + org.junit + junit-bom + ${junit-jupiter.version} + pom + import + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.jupiter + junit-jupiter + + + org.junit.jupiter + junit-jupiter-api + + + org.junit.platform + junit-plaform-commons + + + + + io.projectreactor.addons + reactor-extra + 3.4.5 + + + com.github.ben-manes.caffeine + caffeine + 2.9.2 + + + org.springframework.boot + spring-boot-starter-data-mongodb-reactive + + + io.projectreactor + reactor-test + test + + + org.testcontainers + mongodb + 1.16.2 + test + + + com.squareup.okhttp3 + mockwebserver + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/Item.java b/spring-5-webflux-2/src/main/java/caching/Item.java similarity index 96% rename from spring-5-webflux/src/main/java/com/baeldung/spring/caching/Item.java rename to spring-5-webflux-2/src/main/java/caching/Item.java index 7b79ff7503..627eeef740 100644 --- a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/Item.java +++ b/spring-5-webflux-2/src/main/java/caching/Item.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.caching; +package caching; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemRepository.java b/spring-5-webflux-2/src/main/java/caching/ItemRepository.java similarity index 85% rename from spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemRepository.java rename to spring-5-webflux-2/src/main/java/caching/ItemRepository.java index 27c97de36a..d69edaf5df 100644 --- a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemRepository.java +++ b/spring-5-webflux-2/src/main/java/caching/ItemRepository.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.caching; +package caching; import org.springframework.data.mongodb.repository.ReactiveMongoRepository; import org.springframework.stereotype.Repository; diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemService.java b/spring-5-webflux-2/src/main/java/caching/ItemService.java similarity index 96% rename from spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemService.java rename to spring-5-webflux-2/src/main/java/caching/ItemService.java index b24b54521e..85d7005831 100644 --- a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemService.java +++ b/spring-5-webflux-2/src/main/java/caching/ItemService.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.caching; +package caching; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.LoadingCache; diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/SpringWebfluxCachingApplication.java b/spring-5-webflux-2/src/main/java/caching/SpringWebfluxCachingApplication.java similarity index 93% rename from spring-5-webflux/src/main/java/com/baeldung/spring/caching/SpringWebfluxCachingApplication.java rename to spring-5-webflux-2/src/main/java/caching/SpringWebfluxCachingApplication.java index 5266e33775..df648fe6a3 100644 --- a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/SpringWebfluxCachingApplication.java +++ b/spring-5-webflux-2/src/main/java/caching/SpringWebfluxCachingApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.caching; +package caching; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-5-webflux/src/main/resources/application-cache.properties b/spring-5-webflux-2/src/main/resources/application-cache.properties similarity index 100% rename from spring-5-webflux/src/main/resources/application-cache.properties rename to spring-5-webflux-2/src/main/resources/application-cache.properties diff --git a/spring-5-webflux-2/src/main/resources/logback.xml b/spring-5-webflux-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..48b68c6bf1 --- /dev/null +++ b/spring-5-webflux-2/src/main/resources/logback.xml @@ -0,0 +1,31 @@ + + + + + + %black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable + + + + + + netty-access.log + + %msg%n + + + + + + + + + + + + + + + + diff --git a/spring-5-webflux/src/test/java/com/baeldung/spring/caching/MonoFluxResultCachingLiveTest.java b/spring-5-webflux-2/src/test/java/caching/MonoFluxResultCachingLiveTest.java similarity index 98% rename from spring-5-webflux/src/test/java/com/baeldung/spring/caching/MonoFluxResultCachingLiveTest.java rename to spring-5-webflux-2/src/test/java/caching/MonoFluxResultCachingLiveTest.java index 322b3c5aa5..daf8367209 100644 --- a/spring-5-webflux/src/test/java/com/baeldung/spring/caching/MonoFluxResultCachingLiveTest.java +++ b/spring-5-webflux-2/src/test/java/caching/MonoFluxResultCachingLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.caching; +package caching; import org.junit.jupiter.api.Test; diff --git a/spring-5-webflux-2/src/test/resources/logback-test.xml b/spring-5-webflux-2/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..12cedf5952 --- /dev/null +++ b/spring-5-webflux-2/src/test/resources/logback-test.xml @@ -0,0 +1,13 @@ + + + + + + %black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable + + + + + + + diff --git a/spring-5-webflux/README.md b/spring-5-webflux/README.md index 889f211fc6..bd667468fb 100644 --- a/spring-5-webflux/README.md +++ b/spring-5-webflux/README.md @@ -11,4 +11,3 @@ This module contains articles about Spring 5 WebFlux - [Spring MVC Async vs Spring WebFlux](https://www.baeldung.com/spring-mvc-async-vs-webflux) - [Set a Timeout in Spring 5 Webflux WebClient](https://www.baeldung.com/spring-webflux-timeout) - [Guide to Retry in Spring WebFlux](https://www.baeldung.com/spring-webflux-retry) -- [Spring Webflux and @Cacheable Annotation](https://www.baeldung.com/spring-webflux-cacheable) diff --git a/spring-5-webflux/pom.xml b/spring-5-webflux/pom.xml index d6afb686fc..69de83c227 100644 --- a/spring-5-webflux/pom.xml +++ b/spring-5-webflux/pom.xml @@ -66,31 +66,11 @@ - - io.projectreactor.addons - reactor-extra - 3.4.5 - - - com.github.ben-manes.caffeine - caffeine - 2.9.2 - - - org.springframework.boot - spring-boot-starter-data-mongodb-reactive - io.projectreactor reactor-test test - - org.testcontainers - mongodb - 1.16.2 - test - com.squareup.okhttp3 mockwebserver From 3a3aa56ad11a4c7331736d7ad9f56f55e0c937e2 Mon Sep 17 00:00:00 2001 From: Mladen Savic Date: Sat, 27 Nov 2021 11:10:33 +0100 Subject: [PATCH 47/65] Spring Webflux and @Cacheable Annotation - moved to new package --- pom.xml | 1 + spring-5-webflux-2/README.md | 7 ++ spring-5-webflux-2/pom.xml | 102 ++++++++++++++++++ .../src/main/java}/caching/Item.java | 2 +- .../main/java}/caching/ItemRepository.java | 2 +- .../src/main/java}/caching/ItemService.java | 2 +- .../SpringWebfluxCachingApplication.java | 2 +- .../resources/application-cache.properties | 0 .../src/main/resources/logback.xml | 31 ++++++ .../MonoFluxResultCachingLiveTest.java | 2 +- .../src/test/resources/logback-test.xml | 13 +++ spring-5-webflux/README.md | 1 - spring-5-webflux/pom.xml | 20 ---- 13 files changed, 159 insertions(+), 26 deletions(-) create mode 100644 spring-5-webflux-2/README.md create mode 100644 spring-5-webflux-2/pom.xml rename {spring-5-webflux/src/main/java/com/baeldung/spring => spring-5-webflux-2/src/main/java}/caching/Item.java (96%) rename {spring-5-webflux/src/main/java/com/baeldung/spring => spring-5-webflux-2/src/main/java}/caching/ItemRepository.java (85%) rename {spring-5-webflux/src/main/java/com/baeldung/spring => spring-5-webflux-2/src/main/java}/caching/ItemService.java (96%) rename {spring-5-webflux/src/main/java/com/baeldung/spring => spring-5-webflux-2/src/main/java}/caching/SpringWebfluxCachingApplication.java (93%) rename {spring-5-webflux => spring-5-webflux-2}/src/main/resources/application-cache.properties (100%) create mode 100644 spring-5-webflux-2/src/main/resources/logback.xml rename {spring-5-webflux/src/test/java/com/baeldung/spring => spring-5-webflux-2/src/test/java}/caching/MonoFluxResultCachingLiveTest.java (98%) create mode 100644 spring-5-webflux-2/src/test/resources/logback-test.xml diff --git a/pom.xml b/pom.xml index a2bd38bc06..bd431ef5cd 100644 --- a/pom.xml +++ b/pom.xml @@ -615,6 +615,7 @@ spring-5-reactive-oauth spring-5-reactive-security spring-5-webflux + spring-5-webflux-2 spring-activiti spring-akka diff --git a/spring-5-webflux-2/README.md b/spring-5-webflux-2/README.md new file mode 100644 index 0000000000..0222ddbaa4 --- /dev/null +++ b/spring-5-webflux-2/README.md @@ -0,0 +1,7 @@ +## Spring 5 WebFlux 2 + +This module contains articles about Spring 5 WebFlux + +## Relevant articles: + +- [Spring Webflux and @Cacheable Annotation](https://www.baeldung.com/spring-webflux-cacheable) \ No newline at end of file diff --git a/spring-5-webflux-2/pom.xml b/spring-5-webflux-2/pom.xml new file mode 100644 index 0000000000..c90fcbe3d9 --- /dev/null +++ b/spring-5-webflux-2/pom.xml @@ -0,0 +1,102 @@ + + + 4.0.0 + spring-5-webflux-2 + spring-5-webflux-2 + http://www.baeldung.com + 1.0-SNAPSHOT + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + + + org.junit + junit-bom + ${junit-jupiter.version} + pom + import + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.jupiter + junit-jupiter + + + org.junit.jupiter + junit-jupiter-api + + + org.junit.platform + junit-plaform-commons + + + + + io.projectreactor.addons + reactor-extra + 3.4.5 + + + com.github.ben-manes.caffeine + caffeine + 2.9.2 + + + org.springframework.boot + spring-boot-starter-data-mongodb-reactive + + + io.projectreactor + reactor-test + test + + + org.testcontainers + mongodb + 1.16.2 + test + + + com.squareup.okhttp3 + mockwebserver + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/Item.java b/spring-5-webflux-2/src/main/java/caching/Item.java similarity index 96% rename from spring-5-webflux/src/main/java/com/baeldung/spring/caching/Item.java rename to spring-5-webflux-2/src/main/java/caching/Item.java index 7b79ff7503..627eeef740 100644 --- a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/Item.java +++ b/spring-5-webflux-2/src/main/java/caching/Item.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.caching; +package caching; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemRepository.java b/spring-5-webflux-2/src/main/java/caching/ItemRepository.java similarity index 85% rename from spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemRepository.java rename to spring-5-webflux-2/src/main/java/caching/ItemRepository.java index 27c97de36a..d69edaf5df 100644 --- a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemRepository.java +++ b/spring-5-webflux-2/src/main/java/caching/ItemRepository.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.caching; +package caching; import org.springframework.data.mongodb.repository.ReactiveMongoRepository; import org.springframework.stereotype.Repository; diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemService.java b/spring-5-webflux-2/src/main/java/caching/ItemService.java similarity index 96% rename from spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemService.java rename to spring-5-webflux-2/src/main/java/caching/ItemService.java index b24b54521e..85d7005831 100644 --- a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemService.java +++ b/spring-5-webflux-2/src/main/java/caching/ItemService.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.caching; +package caching; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.LoadingCache; diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/SpringWebfluxCachingApplication.java b/spring-5-webflux-2/src/main/java/caching/SpringWebfluxCachingApplication.java similarity index 93% rename from spring-5-webflux/src/main/java/com/baeldung/spring/caching/SpringWebfluxCachingApplication.java rename to spring-5-webflux-2/src/main/java/caching/SpringWebfluxCachingApplication.java index 5266e33775..df648fe6a3 100644 --- a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/SpringWebfluxCachingApplication.java +++ b/spring-5-webflux-2/src/main/java/caching/SpringWebfluxCachingApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.caching; +package caching; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-5-webflux/src/main/resources/application-cache.properties b/spring-5-webflux-2/src/main/resources/application-cache.properties similarity index 100% rename from spring-5-webflux/src/main/resources/application-cache.properties rename to spring-5-webflux-2/src/main/resources/application-cache.properties diff --git a/spring-5-webflux-2/src/main/resources/logback.xml b/spring-5-webflux-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..48b68c6bf1 --- /dev/null +++ b/spring-5-webflux-2/src/main/resources/logback.xml @@ -0,0 +1,31 @@ + + + + + + %black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable + + + + + + netty-access.log + + %msg%n + + + + + + + + + + + + + + + + diff --git a/spring-5-webflux/src/test/java/com/baeldung/spring/caching/MonoFluxResultCachingLiveTest.java b/spring-5-webflux-2/src/test/java/caching/MonoFluxResultCachingLiveTest.java similarity index 98% rename from spring-5-webflux/src/test/java/com/baeldung/spring/caching/MonoFluxResultCachingLiveTest.java rename to spring-5-webflux-2/src/test/java/caching/MonoFluxResultCachingLiveTest.java index 322b3c5aa5..daf8367209 100644 --- a/spring-5-webflux/src/test/java/com/baeldung/spring/caching/MonoFluxResultCachingLiveTest.java +++ b/spring-5-webflux-2/src/test/java/caching/MonoFluxResultCachingLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.caching; +package caching; import org.junit.jupiter.api.Test; diff --git a/spring-5-webflux-2/src/test/resources/logback-test.xml b/spring-5-webflux-2/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..12cedf5952 --- /dev/null +++ b/spring-5-webflux-2/src/test/resources/logback-test.xml @@ -0,0 +1,13 @@ + + + + + + %black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable + + + + + + + diff --git a/spring-5-webflux/README.md b/spring-5-webflux/README.md index 889f211fc6..bd667468fb 100644 --- a/spring-5-webflux/README.md +++ b/spring-5-webflux/README.md @@ -11,4 +11,3 @@ This module contains articles about Spring 5 WebFlux - [Spring MVC Async vs Spring WebFlux](https://www.baeldung.com/spring-mvc-async-vs-webflux) - [Set a Timeout in Spring 5 Webflux WebClient](https://www.baeldung.com/spring-webflux-timeout) - [Guide to Retry in Spring WebFlux](https://www.baeldung.com/spring-webflux-retry) -- [Spring Webflux and @Cacheable Annotation](https://www.baeldung.com/spring-webflux-cacheable) diff --git a/spring-5-webflux/pom.xml b/spring-5-webflux/pom.xml index d6afb686fc..69de83c227 100644 --- a/spring-5-webflux/pom.xml +++ b/spring-5-webflux/pom.xml @@ -66,31 +66,11 @@ - - io.projectreactor.addons - reactor-extra - 3.4.5 - - - com.github.ben-manes.caffeine - caffeine - 2.9.2 - - - org.springframework.boot - spring-boot-starter-data-mongodb-reactive - io.projectreactor reactor-test test - - org.testcontainers - mongodb - 1.16.2 - test - com.squareup.okhttp3 mockwebserver From 0af4cde56c10a3dd1ab3e12f6777f4dffff34636 Mon Sep 17 00:00:00 2001 From: ACHRAF TAITAI <43656331+achraftt@users.noreply.github.com> Date: Sat, 27 Nov 2021 17:59:29 +0100 Subject: [PATCH 48/65] BAEL-5147 : convert ByteBuffer to String (#11504) * BAEL-5147: convert ByteBuffer to String * Update README.md --- .../core-java-string-conversions-2/README.md | 1 + .../ByteArrayToStringUnitTest.java | 44 +++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 core-java-modules/core-java-string-conversions-2/src/test/java/com/baeldung/bytebuffertostring/ByteArrayToStringUnitTest.java diff --git a/core-java-modules/core-java-string-conversions-2/README.md b/core-java-modules/core-java-string-conversions-2/README.md index 46eb783a27..22f4cd89a1 100644 --- a/core-java-modules/core-java-string-conversions-2/README.md +++ b/core-java-modules/core-java-string-conversions-2/README.md @@ -9,4 +9,5 @@ This module contains articles about string conversions from/to another type. - [Converting String to BigDecimal in Java](https://www.baeldung.com/java-string-to-bigdecimal) - [Converting String to BigInteger in Java](https://www.baeldung.com/java-string-to-biginteger) - [Convert a String to Camel Case](https://www.baeldung.com/java-string-to-camel-case) +- [Convert a ByteBuffer to String] - More articles: [[<-- prev]](/core-java-string-conversions) diff --git a/core-java-modules/core-java-string-conversions-2/src/test/java/com/baeldung/bytebuffertostring/ByteArrayToStringUnitTest.java b/core-java-modules/core-java-string-conversions-2/src/test/java/com/baeldung/bytebuffertostring/ByteArrayToStringUnitTest.java new file mode 100644 index 0000000000..c498921d9a --- /dev/null +++ b/core-java-modules/core-java-string-conversions-2/src/test/java/com/baeldung/bytebuffertostring/ByteArrayToStringUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.bytebuffertostring; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +import org.junit.Test; + +public class ByteArrayToStringUnitTest { + private static Charset charset = StandardCharsets.UTF_8; + private static final String content = "baeldung"; + + @Test + public void convertUsingNewStringFromBufferArray_thenOK() { + // Allocate a ByteBuffer + ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes()); + if (byteBuffer.hasArray()) { + String newContent = new String(byteBuffer.array(), charset); + assertEquals(content, newContent); + } + } + + @Test + public void convertUsingNewStringFromByteBufferGetBytes_thenOK() { + // Allocate a ByteBuffer + ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes()); + byte[] bytes = new byte[byteBuffer.remaining()]; + byteBuffer.get(bytes); + String newContent = new String(bytes, charset); + assertEquals(content, newContent); + } + + @Test + public void convertUsingCharsetDecode_thenOK() { + // Allocate a ByteBuffer + ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes()); + String newContent = charset.decode(byteBuffer) + .toString(); + assertEquals(content, newContent); + } + +} From 84418692834f483829c3b0b8894550e0fc17fecb Mon Sep 17 00:00:00 2001 From: Azhwani <13301425+azhwani@users.noreply.github.com> Date: Sun, 28 Nov 2021 16:47:49 +0100 Subject: [PATCH 49/65] init commit (#11496) --- .../baeldung/regex/matcher/MatcherUnitTest.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/matcher/MatcherUnitTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/matcher/MatcherUnitTest.java index 304b9f2f1d..7ec4a1ae58 100644 --- a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/matcher/MatcherUnitTest.java +++ b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/matcher/MatcherUnitTest.java @@ -11,6 +11,9 @@ import org.junit.jupiter.api.Test; public class MatcherUnitTest { + private static final String STRING_INPUT = "test+"; + private static final String REGEX = "\\+"; + @Test public void whenFindFourDigitWorks_thenCorrect() { Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); @@ -60,4 +63,16 @@ public class MatcherUnitTest { assertTrue(m.matches());// matches will always return the same return } + @Test + public void whenUsingMatcher_thenReturnTrue() { + Pattern pattern = Pattern.compile(REGEX); + Matcher matcher = pattern.matcher(STRING_INPUT); + assertTrue(matcher.find()); + } + + @Test + public void whenUsingMatches_thenReturnFalse() { + assertFalse(Pattern.matches(REGEX, STRING_INPUT)); + } + } From 15493016122187bf98c3fc6f55fa575e1f62d590 Mon Sep 17 00:00:00 2001 From: wugangca Date: Sun, 28 Nov 2021 08:51:13 -0700 Subject: [PATCH 50/65] BAEL-5205 Adding a column to an Excel file using Apache POI (#11491) * BAEL-5205 Adding a column to an Excel file using Apache POI * BAEL-5205 move the test xls file into the test folder Co-authored-by: Gang Wu --- apache-poi-2/.gitignore | 3 ++ apache-poi-2/pom.xml | 24 +++++++++++ .../poi/excel/newcolumn/ExcelColumn.java | 16 +++++++ .../excel/newcolumn/ExcelColumnUnitTest.java | 40 ++++++++++++++++++ .../src/test/resources/newColumnTest.xlsx | Bin 0 -> 3375 bytes 5 files changed, 83 insertions(+) create mode 100644 apache-poi-2/.gitignore create mode 100644 apache-poi-2/pom.xml create mode 100644 apache-poi-2/src/main/java/com/baeldung/poi/excel/newcolumn/ExcelColumn.java create mode 100644 apache-poi-2/src/test/java/com/baeldung/poi/excel/newcolumn/ExcelColumnUnitTest.java create mode 100644 apache-poi-2/src/test/resources/newColumnTest.xlsx diff --git a/apache-poi-2/.gitignore b/apache-poi-2/.gitignore new file mode 100644 index 0000000000..9552c1e63d --- /dev/null +++ b/apache-poi-2/.gitignore @@ -0,0 +1,3 @@ +*.docx +temp.xls +temp.xlsx diff --git a/apache-poi-2/pom.xml b/apache-poi-2/pom.xml new file mode 100644 index 0000000000..1cb6509457 --- /dev/null +++ b/apache-poi-2/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + apache-poi + 0.0.1-SNAPSHOT + apache-poi + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.apache.poi + poi-ooxml + 5.0.0 + + + + \ No newline at end of file diff --git a/apache-poi-2/src/main/java/com/baeldung/poi/excel/newcolumn/ExcelColumn.java b/apache-poi-2/src/main/java/com/baeldung/poi/excel/newcolumn/ExcelColumn.java new file mode 100644 index 0000000000..00ca24f6e8 --- /dev/null +++ b/apache-poi-2/src/main/java/com/baeldung/poi/excel/newcolumn/ExcelColumn.java @@ -0,0 +1,16 @@ +package com.baeldung.poi.excel.newcolumn; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + + +public class ExcelColumn { + + public void addColumn(Sheet sheet, CellType cellType) { + for (Row currentRow : sheet) { + currentRow.createCell(currentRow.getLastCellNum(), cellType); + } + } +} diff --git a/apache-poi-2/src/test/java/com/baeldung/poi/excel/newcolumn/ExcelColumnUnitTest.java b/apache-poi-2/src/test/java/com/baeldung/poi/excel/newcolumn/ExcelColumnUnitTest.java new file mode 100644 index 0000000000..9b991719b1 --- /dev/null +++ b/apache-poi-2/src/test/java/com/baeldung/poi/excel/newcolumn/ExcelColumnUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.poi.excel.newcolumn; + +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Paths; + +import static org.junit.Assert.assertEquals; + +public class ExcelColumnUnitTest { + private static final String FILE_NAME = "newColumnTest.xlsx"; + private String fileLocation; + + @Before + public void setup() throws URISyntaxException { + fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString(); + } + + @Test + public void givenExistingRows_whenAddNewColumn_thenRowColumnNumberIncreased() throws IOException { + Workbook workbook = new XSSFWorkbook(fileLocation); + Sheet sheet = workbook.getSheetAt(0); + Row row = sheet.getRow(0); + assertEquals(5, row.getLastCellNum()); + + ExcelColumn excelColumn = new ExcelColumn(); + excelColumn.addColumn(sheet, CellType.STRING); + assertEquals(6, row.getLastCellNum()); + + workbook.close(); + } + +} \ No newline at end of file diff --git a/apache-poi-2/src/test/resources/newColumnTest.xlsx b/apache-poi-2/src/test/resources/newColumnTest.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..54e8734d58f7e14ba90c1bd65417142c460db369 GIT binary patch literal 3375 zcmaJ@2{@E%8y-f+P?4l59h3=8#W*8tc4`>QjHHm=ScWmiR*WUokbO_tvUEsMvNo~| z*&-o(nIj^Sts_gwKcoLY=J-!N-}TKmb6wx_&ig#?{oMDBMgiIQ02~|~fJ(q|G=M4g z)4!W(5L`X6uAY`gK5keKbBSwsm$D0OuJv%9^`w@5n9L&j;(;Iyp=SOEi@+Nc$Ja9FKfyu`i1R)Z=a;jzn{{ z-T6dwlxTHaxm4O&elBP)Zan{n2B!DkbV^vt(;)wjXS%Bw6?pkHGxmoE=dK>7g%;<> zj+|;xf8Mf?Zx#v8Z4wk#Y%9JEUL@%+rUZlzTwVxqYdqrPY@nOP28ngnzivF6yO8&; zR^2p!{N#B?AQ7?@ILIv=Zhc6|J?uTnpq2%V0&(~zz9cHL002kW008t)d(TDhy`?+W z#Y0kp@mUy8#WlcplPw!3X>v1Gk(i3xzfa;LXIZ4pv~_LT28NQWH`*o4P@Dpv#i9P2 zpl)xKQ0;1rL`F`K*PGyM$HCPBfosZ2k7iX5P$%6+k?hAB0xJBo!S`Jgsd?G3WBkAn zB&DA+5X72H-rqPhB?n40ov;uq6=ka!^h8B zFg3g|Dn_#wJYMuy@?IB9pq5EXO$wm;^V3ytqKgosUr%?c7VF3#9{mp1%l2~g!4(9> z1pYK_ilEaUlMMtb@U3TCa7>j54fwM%dXpFFTRldvT$}Y*z2Tw1VMnkUC_@a2h|EzF52g z*XtOSAGm$qW_PmilrRUoOP;(yqBct)ftHQUu zzmwi5oXo$fP5XE@?fLjpKKa9M>2py<$P7&UJ^ph`l)@I<5|k`-A;`HElv8|cC>C$d z*>;0id9^8(uRmc)|FXHay;WV%zZN|vXFrCU7(FL{c6eC1 zy)CagqeddOXI%T$4GlrGD5kDHG%CtZEVQ@Rt3}6Z3?A|GbHO^d??&k@Rr1cE{RX@N{=_ zb?{*HQ7KAoZ!nxkYgv?*b*Fka1>ThS6u!VZ%5oTz1x{CYfD8UfA+CPkTzy@hDVHjX z1>X{oGd=?uRo)ZS%$_m4;TF_4bJbW=FH@%Pch(Z(Wm(F`v$QAD@COo?G^fPEEec9` zZcik+FPg$*#8ILuEtnBHsCL6%^iMQx`+u zZow~6vFE=9dHT3uw<<}GS0XeB^N^QyHn_v8sS9YWq?z4GSG=a;jXvqL51t!GT^FgU zt+7gbkzU|EIy+7a4apgZF}#Pk+*}4*@J_I1E9i=RSoC79`I~j&sXM@ec}ZN@DE^^iMUcoko#zpEvw01B5eL@oR@-ypBTlsX@J;C7 zR%lHs$3UkNeTdW-H!Ef0#^}jew2+Hl$WC4%G2n4yQ?>ebuUaDnPQ~(6x^c7*7?fFx zwdR~&6MFz-D^-S^n)_Dii$}g&v}ogj>nj%KhqXl5f?3O1j_xIT3e9jY4P;A)T;k6Z zYMi#L@9g9i)zvu`sE7J|KxXqGf7DFUW<&aBYgE3JjjzB5u!~Y4m6xPgS2pv^)_tw9 zSC%obEQ(|4R&<PO9v#4mQeglJmkn163S8*VoU~zrP1BQen ztjmSfPLG*4 zyl1cfo#pnc=>sfEPLpAXFeAl>M`vb$VU5EFO-`?#f%ePJY<1;e?Z)Xrdd*jUIe~|N zbmfO^G56+&gvIGO(16c?e9 z^Ca$4T0lpFPxCR6gpeX9s_?F8kv)4YmJMW=tu&RiRHU+iHUqAGujPCSRiIHOx>~Vv z$bwa>DH!Y^xyK=wGWD$8V!C9v%$nOgaOmP&+Ms*K_2X|oXNNqE_${Sc5?BD#uCem# zGHlCzFhWtVUyn&%3)sEV@*aP#o6EcEdPwz=5`~Dau^au5SN`~ZzjmWH&`lnx-gCj{ zx8X8W09ziUs&Z+9i-8z2P%*BDUOD2Ih=FV)#={Yd_4J?<75yQ##q{xJ1|h0EH~-XI z=T7zShL|`O-eq?zz}pJlg*f|LT2gUs-tXP*-e;?+Y zv-r_-!cq31nbH+R&1Cm;fn-(K)#Cw^6MMo>ogebld?0c}su~KK@%kR}*W%pR=f|3V&LnumF(cPX@5m+_x@p0~Z-xA8gEPF)_vI^cI zAAN72d3a3;cZaHT_Ypc->oDe$C*q^i3zLE~!A`xgC24{mp*qOo>CyH@&?j8aSL^cX zxhWxzz%9XDBzV>!=_r-mIt><9KESrOWp-W+Z~M>q7pIFx{c{0kd%`ei+u=w5OD4Ov zGm+T_Fx<;_q|o=d)64A4X4XH3RoD(EAXE1LjKj`!X0>66y!oQz-p0XhyWcmMzZ literal 0 HcmV?d00001 From d7f3f90731f5c0dd3770a14e9fa19c6c53464955 Mon Sep 17 00:00:00 2001 From: Bhaskara Date: Mon, 29 Nov 2021 05:02:23 +0530 Subject: [PATCH 51/65] BAEL-4648: How to debug Websockets (#11469) * BAEL-4648: How to debug Websockets * Formatted the code * Incorporated comments from Kevin --- spring-websockets/pom.xml | 4 +- .../debugwebsockets/StockTicksController.java | 39 ++++++ .../StompClientSessionHandler.java | 31 +++++ .../debugwebsockets/StompWebSocketClient.java | 24 ++++ .../debugwebsockets/WebsocketApplication.java | 13 ++ .../WebsocketConfiguration.java | 25 ++++ .../WebSocketIntegrationTest.java | 114 ++++++++++++++++++ 7 files changed, 248 insertions(+), 2 deletions(-) create mode 100644 spring-websockets/src/main/java/com/baeldung/debugwebsockets/StockTicksController.java create mode 100644 spring-websockets/src/main/java/com/baeldung/debugwebsockets/StompClientSessionHandler.java create mode 100644 spring-websockets/src/main/java/com/baeldung/debugwebsockets/StompWebSocketClient.java create mode 100644 spring-websockets/src/main/java/com/baeldung/debugwebsockets/WebsocketApplication.java create mode 100644 spring-websockets/src/main/java/com/baeldung/debugwebsockets/WebsocketConfiguration.java create mode 100644 spring-websockets/src/test/java/com/baeldung/debugwebsockets/WebSocketIntegrationTest.java diff --git a/spring-websockets/pom.xml b/spring-websockets/pom.xml index a28ef8749a..28c875d50d 100644 --- a/spring-websockets/pom.xml +++ b/spring-websockets/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 spring-websockets spring-websockets diff --git a/spring-websockets/src/main/java/com/baeldung/debugwebsockets/StockTicksController.java b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/StockTicksController.java new file mode 100644 index 0000000000..0942657c33 --- /dev/null +++ b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/StockTicksController.java @@ -0,0 +1,39 @@ +package com.baeldung.debugwebsockets; + +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Controller; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; + +@Controller +public class StockTicksController { + private final SimpMessagingTemplate simpMessagingTemplate; + + public StockTicksController(SimpMessagingTemplate simpMessagingTemplate) { + this.simpMessagingTemplate = simpMessagingTemplate; + } + + @Scheduled(fixedRate = 3000) + public void sendTicks() { + simpMessagingTemplate.convertAndSend("/topic/ticks", getStockTicks()); + } + + private Map getStockTicks() { + Map ticks = new HashMap<>(); + ticks.put("AAPL", getRandomTick()); + ticks.put("GOOGL", getRandomTick()); + ticks.put("MSFT", getRandomTick()); + ticks.put("TSLA", getRandomTick()); + ticks.put("AMZN", getRandomTick()); + ticks.put("HPE", getRandomTick()); + + return ticks; + } + + private int getRandomTick() { + return ThreadLocalRandom.current().nextInt(-100, 100 + 1); + } +} \ No newline at end of file diff --git a/spring-websockets/src/main/java/com/baeldung/debugwebsockets/StompClientSessionHandler.java b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/StompClientSessionHandler.java new file mode 100644 index 0000000000..535be79cee --- /dev/null +++ b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/StompClientSessionHandler.java @@ -0,0 +1,31 @@ +package com.baeldung.debugwebsockets; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.messaging.simp.stomp.StompHeaders; +import org.springframework.messaging.simp.stomp.StompSession; +import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter; + +import java.lang.reflect.Type; +import java.util.Map; + +public class StompClientSessionHandler extends StompSessionHandlerAdapter { + private static final Logger logger = LoggerFactory.getLogger("StompClientSessionHandler"); + + @Override + public void afterConnected(StompSession session, StompHeaders connectedHeaders) { + logger.info("New session established. Session Id -> {}", session.getSessionId()); + session.subscribe("/topic/ticks", this); + logger.info("Subscribed to topic: /topic/ticks"); + } + + @Override + public void handleFrame(StompHeaders headers, Object payload) { + logger.info("Payload -> {}", payload); + } + + @Override + public Type getPayloadType(StompHeaders headers) { + return Map.class; + } +} diff --git a/spring-websockets/src/main/java/com/baeldung/debugwebsockets/StompWebSocketClient.java b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/StompWebSocketClient.java new file mode 100644 index 0000000000..0cbe32bf65 --- /dev/null +++ b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/StompWebSocketClient.java @@ -0,0 +1,24 @@ +package com.baeldung.debugwebsockets; + +import org.springframework.messaging.converter.MappingJackson2MessageConverter; +import org.springframework.messaging.simp.stomp.StompSessionHandler; +import org.springframework.web.socket.client.WebSocketClient; +import org.springframework.web.socket.client.standard.StandardWebSocketClient; +import org.springframework.web.socket.messaging.WebSocketStompClient; + +import java.util.Scanner; + +public class StompWebSocketClient { + + private static final String URL = "ws://localhost:8080/stock-ticks/websocket"; + + public static void main(String[] args) { + WebSocketClient client = new StandardWebSocketClient(); + WebSocketStompClient stompClient = new WebSocketStompClient(client); + stompClient.setMessageConverter(new MappingJackson2MessageConverter()); + StompSessionHandler sessionHandler = new StompClientSessionHandler(); + stompClient.connect(URL, sessionHandler); + + new Scanner(System.in).nextLine(); + } +} diff --git a/spring-websockets/src/main/java/com/baeldung/debugwebsockets/WebsocketApplication.java b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/WebsocketApplication.java new file mode 100644 index 0000000000..1d0d6950d3 --- /dev/null +++ b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/WebsocketApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.debugwebsockets; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class WebsocketApplication { + + public static void main(String[] args) { + SpringApplication.run(WebsocketApplication.class, args); + } + +} diff --git a/spring-websockets/src/main/java/com/baeldung/debugwebsockets/WebsocketConfiguration.java b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/WebsocketConfiguration.java new file mode 100644 index 0000000000..3735e7359b --- /dev/null +++ b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/WebsocketConfiguration.java @@ -0,0 +1,25 @@ +package com.baeldung.debugwebsockets; + +import org.springframework.context.annotation.Configuration; +import org.springframework.messaging.simp.config.MessageBrokerRegistry; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; +import org.springframework.web.socket.config.annotation.StompEndpointRegistry; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; + +@Configuration +@EnableWebSocketMessageBroker +@EnableScheduling +public class WebsocketConfiguration implements WebSocketMessageBrokerConfigurer { + @Override + public void configureMessageBroker(MessageBrokerRegistry config) { + config.enableSimpleBroker("/topic"); + config.setApplicationDestinationPrefixes("/app"); + } + + @Override + public void registerStompEndpoints(StompEndpointRegistry registry) { + registry.addEndpoint("/stock-ticks").setAllowedOriginPatterns("*").withSockJS(); + } + +} diff --git a/spring-websockets/src/test/java/com/baeldung/debugwebsockets/WebSocketIntegrationTest.java b/spring-websockets/src/test/java/com/baeldung/debugwebsockets/WebSocketIntegrationTest.java new file mode 100644 index 0000000000..bdc283b9e4 --- /dev/null +++ b/spring-websockets/src/test/java/com/baeldung/debugwebsockets/WebSocketIntegrationTest.java @@ -0,0 +1,114 @@ +package com.baeldung.debugwebsockets; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.messaging.converter.MappingJackson2MessageConverter; +import org.springframework.messaging.simp.stomp.StompCommand; +import org.springframework.messaging.simp.stomp.StompFrameHandler; +import org.springframework.messaging.simp.stomp.StompHeaders; +import org.springframework.messaging.simp.stomp.StompSession; +import org.springframework.messaging.simp.stomp.StompSessionHandler; +import org.springframework.web.socket.client.WebSocketClient; +import org.springframework.web.socket.client.standard.StandardWebSocketClient; +import org.springframework.web.socket.messaging.WebSocketStompClient; + +import java.lang.reflect.Type; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +/** + * This should be part of integration test suite. + * The test starts the server and then connects to the WebSocket. Then verifies if the messages are received from the + * WebSocket. + * This test is inspired from: https://github.com/spring-guides/gs-messaging-stomp-websocket/blob/main/complete/src/test/java/com/example/messagingstompwebsocket/GreetingIntegrationTests.java + */ +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +class WebSocketIntegrationTest{ + WebSocketClient client; + WebSocketStompClient stompClient; + @LocalServerPort + private int port; + private static final Logger logger= LoggerFactory.getLogger(WebSocketIntegrationTest.class); + + @BeforeEach + public void setup() { + logger.info("Setting up the tests ..."); + client = new StandardWebSocketClient(); + stompClient = new WebSocketStompClient(client); + stompClient.setMessageConverter(new MappingJackson2MessageConverter()); + } + + @Test + void givenWebSocket_whenMessage_thenVerifyMessage() throws Exception { + final CountDownLatch latch = new CountDownLatch(1); + final AtomicReference failure = new AtomicReference<>(); + StompSessionHandler sessionHandler = new StompSessionHandler() { + @Override + public Type getPayloadType(StompHeaders headers) { + return null; + } + + @Override + public void handleFrame(StompHeaders headers, Object payload) { + } + + @Override + public void afterConnected(StompSession session, StompHeaders connectedHeaders) { + logger.info("Connected to the WebSocket ..."); + session.subscribe("/topic/ticks", new StompFrameHandler() { + @Override + public Type getPayloadType(StompHeaders headers) { + return Map.class; + } + + @Override + public void handleFrame(StompHeaders headers, Object payload) { + try { + + assertThat(payload).isNotNull(); + assertThat(payload).isInstanceOf(Map.class); + + @SuppressWarnings("unchecked") + Map map = (Map) payload; + + assertThat(map).containsKey("HPE"); + assertThat(map.get("HPE")).isInstanceOf(Integer.class); + } catch (Throwable t) { + failure.set(t); + logger.error("There is an exception ", t); + } finally { + session.disconnect(); + latch.countDown(); + } + + } + }); + } + + @Override + public void handleException(StompSession session, StompCommand command, StompHeaders headers, byte[] payload, Throwable exception) { + } + + @Override + public void handleTransportError(StompSession session, Throwable exception) { + } + }; + stompClient.connect("ws://localhost:{port}/stock-ticks/websocket", sessionHandler, this.port); + if (latch.await(20, TimeUnit.SECONDS)) { + if (failure.get() != null) { + fail("Assertion Failed", failure.get()); + } + } else { + fail("Could not receive the message on time"); + } + } +} From 3041ad372469ab2407e6f47e859f2babb98cf6a9 Mon Sep 17 00:00:00 2001 From: Teica Date: Tue, 30 Nov 2021 01:26:16 +0100 Subject: [PATCH 52/65] Feature bael 5253 (#11526) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * BAEL-5032 Swagger to PDF * BAEL-5032 added lombok as dependency * BAEL-5253 moving the tests to other module * renaming the test class * Update pom.xml * Update pom.xml * Update pom.xml * Delete pom.xml * Create pom.xml Co-authored-by: Matea Pejčinović --- core-java-modules/core-java-string-algorithms-3/pom.xml | 9 +++++++-- .../StringFirstCharacterUppercaseUnitTest.java} | 4 ++-- spring-boot-modules/spring-boot-swagger/pom.xml | 2 +- 3 files changed, 10 insertions(+), 5 deletions(-) rename core-java-modules/{core-java-string-algorithms-2/src/test/java/com/baeldung/isuppercase/StringFirstCharacterUppercase.java => core-java-string-algorithms-3/src/test/java/com/baeldung/isuppercase/StringFirstCharacterUppercaseUnitTest.java} (94%) diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml index 6700e9ba95..180d75cc61 100644 --- a/core-java-modules/core-java-string-algorithms-3/pom.xml +++ b/core-java-modules/core-java-string-algorithms-3/pom.xml @@ -24,6 +24,11 @@ commons-validator ${validator.version} + + com.google.guava + guava + ${guava.version} + @@ -49,8 +54,8 @@ - 28.1-jre + 31.0.1-jre 1.7 - \ No newline at end of file + diff --git a/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/isuppercase/StringFirstCharacterUppercase.java b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/isuppercase/StringFirstCharacterUppercaseUnitTest.java similarity index 94% rename from core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/isuppercase/StringFirstCharacterUppercase.java rename to core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/isuppercase/StringFirstCharacterUppercaseUnitTest.java index 0d9d3b6431..6803285ca2 100644 --- a/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/isuppercase/StringFirstCharacterUppercase.java +++ b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/isuppercase/StringFirstCharacterUppercaseUnitTest.java @@ -1,15 +1,15 @@ package com.baeldung.isuppercase; -import com.google.common.base.Ascii; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; +import com.google.common.base.Ascii; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.matchesPattern; @TestInstance(TestInstance.Lifecycle.PER_CLASS) -public class StringFirstCharacterUppercase { +public class StringFirstCharacterUppercaseUnitTest { @Test public void givenString_whenCheckingWithCharacterIsUpperCase_thenStringCapitalized() { diff --git a/spring-boot-modules/spring-boot-swagger/pom.xml b/spring-boot-modules/spring-boot-swagger/pom.xml index 87ee5f04cb..d6b62bce3c 100644 --- a/spring-boot-modules/spring-boot-swagger/pom.xml +++ b/spring-boot-modules/spring-boot-swagger/pom.xml @@ -40,4 +40,4 @@ 3.0.0 - \ No newline at end of file + From 915cbfdafae55f9655c106b0b71ae16d7ed557db Mon Sep 17 00:00:00 2001 From: vaibhav007jain <72961247+vaibhav007jain@users.noreply.github.com> Date: Tue, 30 Nov 2021 08:51:17 +0530 Subject: [PATCH 53/65] BAEL-5228: Adding code for approaches to concatenating null string in java (#11464) * commited initial code for hexagonal architecture * Deleting to check in again * Deleing to check in again * Push first code for Hexagonal Architecture * final code with UT for JSON to Java conversion * removed hexagonal-architecture code from last commit * BEL-5071 updated README * BAEL-5071: Undo README changes and added a nested object in the JSON example. * BAEL-5071: fixed whitespace/indentation in JsonToJavaClassConversion.java * BAEL-5151: Added code for getting the first of a String * BAEL-5151: Renamed Unit Test * BAEL-5151: Moved the files from core-java-string-operations to core-java-string-operations-3 * BAEL-5151: Replaced tabs with white spaces. * BAEL-5228: Adding code for approaches to concatening null string in java * BAEL-5228: Moved file to correct folder and added a UT. * BAEL-5228: corrected import statements. * BAEL-5228: corrected last commit. * BAEL-5228: removed extra import. * BAEL-5228: renamed UT Co-authored-by: Vaibhav Jain --- .../concatenation/ConcatenatingNull.java | 86 +++++++++++++++++++ .../ConcatenatingNullUnitTest.java | 59 +++++++++++++ 2 files changed, 145 insertions(+) create mode 100644 core-java-modules/core-java-string-operations-4/src/main/java/com/baeldung/concatenation/ConcatenatingNull.java create mode 100644 core-java-modules/core-java-string-operations-4/src/test/java/com/baeldung/concatenation/ConcatenatingNullUnitTest.java diff --git a/core-java-modules/core-java-string-operations-4/src/main/java/com/baeldung/concatenation/ConcatenatingNull.java b/core-java-modules/core-java-string-operations-4/src/main/java/com/baeldung/concatenation/ConcatenatingNull.java new file mode 100644 index 0000000000..250a0d6b25 --- /dev/null +++ b/core-java-modules/core-java-string-operations-4/src/main/java/com/baeldung/concatenation/ConcatenatingNull.java @@ -0,0 +1,86 @@ +package com.baeldung.concatenation; + +import java.util.StringJoiner; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class ConcatenatingNull { + + public static void main(String[] args) { + String[] values = { "Java ", null, "", "is ", "great!" }; + + concatenateUsingPlusOperator(values); + concatenateUsingHelperMethod(values); + concatenateUsingStringBuilder(values); + concatenateUsingJoin(values); + concatenateUsingStringJoiner(values); + concatenateUsingCollectorsJoining(values); + concatenateUsingStringConcat(values); + } + + public static String concatenateUsingStringConcat(String[] values) { + String result = ""; + + for (String value : values) { + result = result.concat(getNonNullString(value)); + } + + return result; + } + + public static String concatenateUsingCollectorsJoining(String[] values) { + String result = Stream.of(values).filter(value -> null != value).collect(Collectors.joining("")); + + return result; + } + + public static String concatenateUsingStringJoiner(String[] values) { + StringJoiner result = new StringJoiner(""); + + for (String value : values) { + result = result.add(getNonNullString(value)); + } + + return result.toString(); + } + + public static String concatenateUsingJoin(String[] values) { + String result = String.join("", values); + + return result; + } + + public static String concatenateUsingStringBuilder(String[] values) { + StringBuilder result = new StringBuilder(); + + for (String value : values) { + result = result.append(getNonNullString(value)); + } + + return result.toString(); + } + + public static String concatenateUsingHelperMethod(String[] values) { + String result = ""; + + for (String value : values) { + result = result + getNonNullString(value); + } + + return result; + } + + public static String concatenateUsingPlusOperator(String[] values) { + String result = ""; + + for (String value : values) { + result = result + (value == null ? "" : value); + } + + return result; + } + + private static String getNonNullString(String value) { + return value == null ? "" : value; + } +} diff --git a/core-java-modules/core-java-string-operations-4/src/test/java/com/baeldung/concatenation/ConcatenatingNullUnitTest.java b/core-java-modules/core-java-string-operations-4/src/test/java/com/baeldung/concatenation/ConcatenatingNullUnitTest.java new file mode 100644 index 0000000000..20e5f6ad7d --- /dev/null +++ b/core-java-modules/core-java-string-operations-4/src/test/java/com/baeldung/concatenation/ConcatenatingNullUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.concatenation; + +import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingCollectorsJoining; +import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingHelperMethod; +import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingJoin; +import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingPlusOperator; +import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingStringBuilder; +import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingStringConcat; +import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingStringJoiner; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class ConcatenatingNullUnitTest { + + String[] values = { "Java ", null, "", "is ", "great!" }; + + @Test + public void givenStringElementsWithNull_whenConcatenatedUsingPlus_thenNullIsIgnored() { + String result = concatenateUsingPlusOperator(values); + assertEquals("Java is great!", result); + } + + @Test + public void givenStringElementsWithNull_whenConcatenatedUsingHelperMethod_thenNullIsIgnored() { + String result = concatenateUsingHelperMethod(values); + assertEquals("Java is great!", result); + } + + @Test + public void givenStringElementsWithNull_whenConcatenatedUsingStringBuilder_thenNullIsIgnored() { + String result = concatenateUsingStringBuilder(values); + assertEquals("Java is great!", result); + } + + @Test + public void givenStringElementsWithNull_whenConcatenatedUsingJoin_thenNullIsNotIgnored() { + String result = concatenateUsingJoin(values); + assertEquals("Java nullis great!", result); + } + + @Test + public void givenStringElementsWithNull_whenConcatenatedUsingStringJoiner_thenNullIsIgnored() { + String result = concatenateUsingStringJoiner(values); + assertEquals("Java is great!", result); + } + + @Test + public void givenStringElementsWithNull_whenConcatenatedUsingCollectorsJoining_thenNullIsIgnored() { + String result = concatenateUsingCollectorsJoining(values); + assertEquals("Java is great!", result); + } + + @Test + public void givenStringElementsWithNull_whenConcatenatedUsingStringConcat_thenNullIsIgnored() { + String result = concatenateUsingStringConcat(values); + assertEquals("Java is great!", result); + } +} From b417edc4212dba0db650187af73af73d1d1e1b8e Mon Sep 17 00:00:00 2001 From: chaos2418 <> Date: Tue, 30 Nov 2021 09:06:22 +0530 Subject: [PATCH 54/65] JAVA-8735: fix logging related integration tests --- logging-modules/logback/pom.xml | 36 ++++++++++++++++++++++++++++++ spring-5-reactive-2/pom.xml | 38 +++++++++++++++++++++++++++++++- spring-5-reactive-client/pom.xml | 38 +++++++++++++++++++++++++++++++- 3 files changed, 110 insertions(+), 2 deletions(-) diff --git a/logging-modules/logback/pom.xml b/logging-modules/logback/pom.xml index 48bb37b881..b4ee42367f 100644 --- a/logging-modules/logback/pom.xml +++ b/logging-modules/logback/pom.xml @@ -74,4 +74,40 @@ 1.1.1 + + + integration-lite-first + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + ${project.basedir}/src/test/resources/logback-test.xml + + + + + + + + integration-lite-second + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + ${project.basedir}/src/test/resources/logback-test.xml + + + + + + + \ No newline at end of file diff --git a/spring-5-reactive-2/pom.xml b/spring-5-reactive-2/pom.xml index 0758365932..e48d42a863 100644 --- a/spring-5-reactive-2/pom.xml +++ b/spring-5-reactive-2/pom.xml @@ -75,9 +75,45 @@ + + + integration-lite-first + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + ${project.basedir}/src/test/resources/logback-test.xml + + + + + + + + integration-lite-second + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + ${project.basedir}/src/test/resources/logback-test.xml + + + + + + + + 1.0.1.RELEASE 2.24.0 - \ No newline at end of file diff --git a/spring-5-reactive-client/pom.xml b/spring-5-reactive-client/pom.xml index 136f31b49e..4502059ed3 100644 --- a/spring-5-reactive-client/pom.xml +++ b/spring-5-reactive-client/pom.xml @@ -148,6 +148,43 @@ + + + integration-lite-first + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + ${project.basedir}/src/test/resources/logback-test.xml + + + + + + + + integration-lite-second + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + ${project.basedir}/src/test/resources/logback-test.xml + + + + + + + + 1.0.1.RELEASE 1.1.3 @@ -157,5 +194,4 @@ 1.1.6 4.0.1 - \ No newline at end of file From fdcc5324bae91feb78d03fca08be29f0d1ca8b44 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Mon, 29 Nov 2021 22:19:32 -0600 Subject: [PATCH 55/65] Add and update README files (#11530) --- apache-poi-2/README.md | 8 ++++++++ apache-poi/README.md | 1 + 2 files changed, 9 insertions(+) create mode 100644 apache-poi-2/README.md diff --git a/apache-poi-2/README.md b/apache-poi-2/README.md new file mode 100644 index 0000000000..69aabf4616 --- /dev/null +++ b/apache-poi-2/README.md @@ -0,0 +1,8 @@ +## Apache POI + +This module contains articles about Apache POI + +### Relevant Articles: + +- [Adding a Column to an Excel Sheet Using Apache POI](https://www.baeldung.com/java-excel-add-column) +- More articles: [[<-- prev]](/apache-poi) diff --git a/apache-poi/README.md b/apache-poi/README.md index d3d60358c5..6d5b80b03a 100644 --- a/apache-poi/README.md +++ b/apache-poi/README.md @@ -15,3 +15,4 @@ This module contains articles about Apache POI - [Multiline Text in Excel Cell Using Apache POI](https://www.baeldung.com/apache-poi-write-multiline-text) - [Set Background Color of a Cell with Apache POI](https://www.baeldung.com/apache-poi-background-color) - [Add Borders to Excel Cells With Apache POI](https://www.baeldung.com/apache-poi-add-borders) +- More articles: [[next -->]](/apache-poi-2) From 8f586a00077416387cf7c32fb47d66d880f237d6 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Wed, 1 Dec 2021 01:17:36 +0100 Subject: [PATCH 56/65] Java Hashmap with different value types (#11495) * Java Hashmap with different value types * some fixes according to review comments * convert liveTest -> unitTest * convert liveTest -> unitTest --- .../mulipletypesinmap/DynamicTypeValue.java | 5 ++ .../mulipletypesinmap/InstantTypeValue.java | 24 ++++++ .../mulipletypesinmap/IntArrayTypeValue.java | 20 +++++ .../mulipletypesinmap/IntegerTypeValue.java | 17 +++++ .../MultipleTypesInMapUnitTest.java | 75 +++++++++++++++++++ 5 files changed, 141 insertions(+) create mode 100644 core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/DynamicTypeValue.java create mode 100644 core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/InstantTypeValue.java create mode 100644 core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/IntArrayTypeValue.java create mode 100644 core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/IntegerTypeValue.java create mode 100644 core-java-modules/core-java-collections-4/src/test/java/com/baeldung/multipletypesinmap/MultipleTypesInMapUnitTest.java diff --git a/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/DynamicTypeValue.java b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/DynamicTypeValue.java new file mode 100644 index 0000000000..4c9ed89f63 --- /dev/null +++ b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/DynamicTypeValue.java @@ -0,0 +1,5 @@ +package com.baeldung.collections.mulipletypesinmap; + +public interface DynamicTypeValue { + String valueDescription(); +} diff --git a/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/InstantTypeValue.java b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/InstantTypeValue.java new file mode 100644 index 0000000000..448e66d872 --- /dev/null +++ b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/InstantTypeValue.java @@ -0,0 +1,24 @@ +package com.baeldung.collections.mulipletypesinmap; + +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; + +public class InstantTypeValue implements DynamicTypeValue { + private static DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") + .withZone(ZoneId.systemDefault()); + private Instant value; + + public InstantTypeValue(Instant value) { + this.value = value; + } + + @Override + public String valueDescription() { + if (value == null) { + return "The value is null."; + } + return String.format("The value is an instant: %s", FORMATTER.format(value)); + } + +} diff --git a/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/IntArrayTypeValue.java b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/IntArrayTypeValue.java new file mode 100644 index 0000000000..290982183f --- /dev/null +++ b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/IntArrayTypeValue.java @@ -0,0 +1,20 @@ +package com.baeldung.collections.mulipletypesinmap; + +import java.util.Arrays; + +public class IntArrayTypeValue implements DynamicTypeValue { + private int[] value; + + public IntArrayTypeValue(int[] value) { + this.value = value; + } + + @Override + public String valueDescription() { + if (value == null) { + return "The value is null."; + } + return String.format("The value is an array of %d integers: %s", value.length, Arrays.toString(value)); + } + +} diff --git a/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/IntegerTypeValue.java b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/IntegerTypeValue.java new file mode 100644 index 0000000000..463b06f768 --- /dev/null +++ b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/IntegerTypeValue.java @@ -0,0 +1,17 @@ +package com.baeldung.collections.mulipletypesinmap; + +public class IntegerTypeValue implements DynamicTypeValue { + private Integer value; + + public IntegerTypeValue(Integer value) { + this.value = value; + } + + @Override + public String valueDescription() { + if(value == null){ + return "The value is null."; + } + return String.format("The value is a %s integer: %d", value > 0 ? "positive" : "negative", value); + } +} diff --git a/core-java-modules/core-java-collections-4/src/test/java/com/baeldung/multipletypesinmap/MultipleTypesInMapUnitTest.java b/core-java-modules/core-java-collections-4/src/test/java/com/baeldung/multipletypesinmap/MultipleTypesInMapUnitTest.java new file mode 100644 index 0000000000..87ea310ab0 --- /dev/null +++ b/core-java-modules/core-java-collections-4/src/test/java/com/baeldung/multipletypesinmap/MultipleTypesInMapUnitTest.java @@ -0,0 +1,75 @@ +package com.baeldung.multipletypesinmap; + +import com.baeldung.collections.mulipletypesinmap.DynamicTypeValue; +import com.baeldung.collections.mulipletypesinmap.InstantTypeValue; +import com.baeldung.collections.mulipletypesinmap.IntArrayTypeValue; +import com.baeldung.collections.mulipletypesinmap.IntegerTypeValue; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +class MultipleTypesInMapUnitTest { + private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") + .withZone(ZoneId.systemDefault()); + + private static final Integer intValue = 777; + private static final int[] intArray = new int[]{2, 3, 5, 7, 11, 13}; + private static final Instant instant = Instant.now(); + + private static final String KEY_INT = "E1 (Integer)"; + private static final String KEY_INT_ARRAY = "E2 (IntArray)"; + private static final String KEY_INSTANT = "E3 (Instant)"; + + @Test + void givenThreeTypes_whenUsingRawMap_thenPrintDescription() { + Map rawMap = new HashMap<>(); + rawMap.put(KEY_INT, intValue); + rawMap.put(KEY_INT_ARRAY, intArray); + rawMap.put(KEY_INSTANT, instant); + + rawMap.forEach((k, v) -> { + if (v instanceof Integer) { + Integer theV = (Integer) v; + String desc = String.format("The value is a %s integer: %d", theV > 0 ? "positive" : "negative", theV); + System.out.println(k + " -> " + desc); + assertThat(k).isEqualTo(KEY_INT); + assertThat(desc).isEqualTo("The value is a positive integer: 777"); + } else if (v instanceof int[]) { + int[] theV = (int[]) v; + String desc = String.format("The value is an array of %d integers: %s", theV.length, Arrays.toString(theV)); + System.out.println(k + " -> " + desc); + assertThat(k).isEqualTo(KEY_INT_ARRAY); + assertThat(desc).isEqualTo("The value is an array of 6 integers: [2, 3, 5, 7, 11, 13]"); + } else if (v instanceof Instant) { + Instant theV = (Instant) v; + String desc = String.format("The value is an instant: %s", FORMATTER.format(theV)); + System.out.println(k + " -> " + desc); + assertThat(k).isEqualTo(KEY_INSTANT); + assertThat(desc).matches("^The value is an instant: \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}"); + } else { + throw new IllegalStateException("Unknown Type found."); + } + }); + } + + @Test + void givenThreeTypes_whenUsingAnInterface_thenPrintDescription() { + Map theMap = new HashMap<>(); + theMap.put(KEY_INT, new IntegerTypeValue(intValue)); + theMap.put(KEY_INT_ARRAY, new IntArrayTypeValue(intArray)); + theMap.put(KEY_INSTANT, new InstantTypeValue(instant)); + + theMap.forEach((k, v) -> System.out.println(k + " -> " + v.valueDescription())); + + assertThat(theMap.get(KEY_INT).valueDescription()).isEqualTo("The value is a positive integer: 777"); + assertThat(theMap.get(KEY_INT_ARRAY).valueDescription()).isEqualTo("The value is an array of 6 integers: [2, 3, 5, 7, 11, 13]"); + assertThat(theMap.get(KEY_INSTANT).valueDescription()).matches("^The value is an instant: \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}"); + } +} From 2e2bcbab191e8201b8ff2c687081a69c0830d6b9 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 1 Dec 2021 16:16:25 +0800 Subject: [PATCH 57/65] Create README.md --- quarkus-jandex/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 quarkus-jandex/README.md diff --git a/quarkus-jandex/README.md b/quarkus-jandex/README.md new file mode 100644 index 0000000000..cca5fa7714 --- /dev/null +++ b/quarkus-jandex/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Quarkus Bean Discovery With Jandex Indexing](https://www.baeldung.com/quarkus-bean-discovery-index) From e1edaf8f5c4f4d2d83ac0d560e786723cad68894 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 1 Dec 2021 16:18:13 +0800 Subject: [PATCH 58/65] Update README.md --- jackson-modules/jackson-conversions-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jackson-modules/jackson-conversions-2/README.md b/jackson-modules/jackson-conversions-2/README.md index bddbb60bd7..fa3568652a 100644 --- a/jackson-modules/jackson-conversions-2/README.md +++ b/jackson-modules/jackson-conversions-2/README.md @@ -11,4 +11,5 @@ This module contains articles about Jackson conversions. - [Jackson Streaming API](https://www.baeldung.com/jackson-streaming-api) - [Jackson: java.util.LinkedHashMap cannot be cast to X](https://www.baeldung.com/jackson-linkedhashmap-cannot-be-cast) - [Deserialize Snake Case to Camel Case With Jackson](https://www.baeldung.com/jackson-deserialize-snake-to-camel-case) +- [Serialize and Deserialize Booleans as Integers With Jackson](https://www.baeldung.com/jackson-booleans-as-integers) - More articles: [[<-- prev]](../jackson-conversions) From 4f569c0914bbc44311253d49108d35300dd3f304 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 1 Dec 2021 16:23:15 +0800 Subject: [PATCH 59/65] Update README.md --- spring-websockets/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-websockets/README.md b/spring-websockets/README.md index 7d69c21b78..88a97850b5 100644 --- a/spring-websockets/README.md +++ b/spring-websockets/README.md @@ -7,3 +7,4 @@ This module contains articles about Spring WebSockets. - [A Quick Example of Spring Websockets’ @SendToUser Annotation](https://www.baeldung.com/spring-websockets-sendtouser) - [Scheduled WebSocket Push with Spring Boot](https://www.baeldung.com/spring-boot-scheduled-websocket) - [Test WebSocket APIs With Postman](https://www.baeldung.com/postman-websocket-apis) +- [Debugging WebSockets](https://www.baeldung.com/debug-websockets) From c60b97f6c7374c69c188505876681b8d4ad0eed6 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 1 Dec 2021 16:25:31 +0800 Subject: [PATCH 60/65] Update README.md --- spring-boot-rest-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-rest-2/README.md b/spring-boot-rest-2/README.md index 41270d58ea..985aa97a86 100644 --- a/spring-boot-rest-2/README.md +++ b/spring-boot-rest-2/README.md @@ -2,3 +2,4 @@ - [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) From 1cd06bd0ff6c9f0833869a0b0e49fac8441efd0d Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 1 Dec 2021 16:31:04 +0800 Subject: [PATCH 61/65] Update README.md --- core-java-modules/core-java-networking-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-networking-3/README.md b/core-java-modules/core-java-networking-3/README.md index 0dc9ad9f70..82e75820ba 100644 --- a/core-java-modules/core-java-networking-3/README.md +++ b/core-java-modules/core-java-networking-3/README.md @@ -9,4 +9,5 @@ This module contains articles about networking in Java - [Connection Timeout vs. Read Timeout for Java Sockets](https://www.baeldung.com/java-socket-connection-read-timeout) - [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) - [[<-- Prev]](/core-java-modules/core-java-networking-2) From 8c337801ce3f08911ccb0c0467daba00022fac0b Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 1 Dec 2021 16:33:28 +0800 Subject: [PATCH 62/65] Update README.md --- core-java-modules/core-java-string-operations-4/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-string-operations-4/README.md b/core-java-modules/core-java-string-operations-4/README.md index be4c9ae05f..83bfeb4d05 100644 --- a/core-java-modules/core-java-string-operations-4/README.md +++ b/core-java-modules/core-java-string-operations-4/README.md @@ -2,4 +2,5 @@ - [Ignoring Commas in Quotes When Splitting a Comma-separated String](https://www.baeldung.com/java-split-string-commas) - [Compare Strings While Ignoring Whitespace in Java](https://www.baeldung.com/java-compare-string-whitespace) +- [Concatenating Null Strings in Java](https://www.baeldung.com/java-concat-null-string) From 8e4bdad572cc3aac53ead78033c3452daa6d8711 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 1 Dec 2021 11:39:46 +0200 Subject: [PATCH 63/65] JAVA-8748 temporarily disable test --- .../{FindFreePortUnitTest.java => FindFreePortManualTest.java} | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) rename core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/{FindFreePortUnitTest.java => FindFreePortManualTest.java} (98%) diff --git a/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/FindFreePortUnitTest.java b/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/FindFreePortManualTest.java similarity index 98% rename from core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/FindFreePortUnitTest.java rename to core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/FindFreePortManualTest.java index 95530ef292..3e533b3fc0 100644 --- a/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/FindFreePortUnitTest.java +++ b/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/FindFreePortManualTest.java @@ -14,7 +14,8 @@ import java.net.ServerSocket; import static org.assertj.core.api.Assertions.*; import static org.assertj.core.api.Assertions.assertThat; -public class FindFreePortUnitTest { +// fixing in JAVA-8748 +public class FindFreePortManualTest { private static int FREE_PORT_NUMBER; private static int[] FREE_PORT_RANGE; From a66d9b5fd2ee9e0bb53e48b9359092cbd41666bd Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Wed, 1 Dec 2021 10:48:53 +0100 Subject: [PATCH 64/65] JAVA-8358: Move Spring Boot Exit Codes code --- spring-boot-modules/spring-boot-basic-customization-2/README.md | 1 + .../baeldung/exitcode/event/ExitCodeEventDemoApplication.java | 0 .../exception/ExitCodeExceptionMapperDemoApplication.java | 0 .../exceptionexitgen/ExceptionExitCodeGeneratorApplication.java | 0 .../exitcode/exceptionexitgen/FailedToStartException.java | 0 .../exitcode/generator/ExitCodeGeneratorDemoApplication.java | 0 spring-boot-modules/spring-boot-basic-customization/README.md | 1 - 7 files changed, 1 insertion(+), 1 deletion(-) rename spring-boot-modules/{spring-boot-basic-customization => spring-boot-basic-customization-2}/src/main/java/com/baeldung/exitcode/event/ExitCodeEventDemoApplication.java (100%) rename spring-boot-modules/{spring-boot-basic-customization => spring-boot-basic-customization-2}/src/main/java/com/baeldung/exitcode/exception/ExitCodeExceptionMapperDemoApplication.java (100%) rename spring-boot-modules/{spring-boot-basic-customization => spring-boot-basic-customization-2}/src/main/java/com/baeldung/exitcode/exceptionexitgen/ExceptionExitCodeGeneratorApplication.java (100%) rename spring-boot-modules/{spring-boot-basic-customization => spring-boot-basic-customization-2}/src/main/java/com/baeldung/exitcode/exceptionexitgen/FailedToStartException.java (100%) rename spring-boot-modules/{spring-boot-basic-customization => spring-boot-basic-customization-2}/src/main/java/com/baeldung/exitcode/generator/ExitCodeGeneratorDemoApplication.java (100%) 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 0e688bda2a..9488618ca5 100644 --- a/spring-boot-modules/spring-boot-basic-customization-2/README.md +++ b/spring-boot-modules/spring-boot-basic-customization-2/README.md @@ -7,3 +7,4 @@ This module contains articles about Spring Boot customization 2 - [DispatcherServlet and web.xml in Spring Boot](https://www.baeldung.com/spring-boot-dispatcherservlet-web-xml) - [XML Defined Beans in Spring Boot](https://www.baeldung.com/spring-boot-xml-beans) - [What Is OncePerRequestFilter?](https://www.baeldung.com/spring-onceperrequestfilter) + - [Spring Boot Exit Codes](https://www.baeldung.com/spring-boot-exit-codes) diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/event/ExitCodeEventDemoApplication.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/event/ExitCodeEventDemoApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/event/ExitCodeEventDemoApplication.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/event/ExitCodeEventDemoApplication.java diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/exception/ExitCodeExceptionMapperDemoApplication.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/exception/ExitCodeExceptionMapperDemoApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/exception/ExitCodeExceptionMapperDemoApplication.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/exception/ExitCodeExceptionMapperDemoApplication.java diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/exceptionexitgen/ExceptionExitCodeGeneratorApplication.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/exceptionexitgen/ExceptionExitCodeGeneratorApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/exceptionexitgen/ExceptionExitCodeGeneratorApplication.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/exceptionexitgen/ExceptionExitCodeGeneratorApplication.java diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/exceptionexitgen/FailedToStartException.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/exceptionexitgen/FailedToStartException.java similarity index 100% rename from spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/exceptionexitgen/FailedToStartException.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/exceptionexitgen/FailedToStartException.java diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/generator/ExitCodeGeneratorDemoApplication.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/generator/ExitCodeGeneratorDemoApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/generator/ExitCodeGeneratorDemoApplication.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/generator/ExitCodeGeneratorDemoApplication.java diff --git a/spring-boot-modules/spring-boot-basic-customization/README.md b/spring-boot-modules/spring-boot-basic-customization/README.md index 6c067fc5a1..a3d9f1b1fc 100644 --- a/spring-boot-modules/spring-boot-basic-customization/README.md +++ b/spring-boot-modules/spring-boot-basic-customization/README.md @@ -11,4 +11,3 @@ This module contains articles about Spring Boot customization - [Spring Boot: Configuring a Main Class](https://www.baeldung.com/spring-boot-main-class) - [How to Define a Spring Boot Filter?](https://www.baeldung.com/spring-boot-add-filter) - [Guide to the Favicon in Spring Boot](https://www.baeldung.com/spring-boot-favicon) - - [Spring Boot Exit Codes](https://www.baeldung.com/spring-boot-exit-codes) From ba29be11fbfea6879f826e8fb1515ffdd28be680 Mon Sep 17 00:00:00 2001 From: Olsi Seferi <72546616+olsiseferi@users.noreply.github.com> Date: Wed, 1 Dec 2021 19:19:19 +0100 Subject: [PATCH 65/65] ExcelUtility Jira issue BAEL-5198 (#11503) * CODE REFACTOR AND ADDED UNIT TEST * SMALL CHANGE * FIXED TESTS TIMEZONE ISSUES Co-authored-by: Olsi Seferi --- .../com/baeldung/poi/excel/ExcelUtility.java | 66 ++++++++++++++++++ .../poi/excel/ExcelUtilityUnitTest.java | 54 ++++++++++++++ apache-poi/src/test/resources/baeldung.xlsx | Bin 0 -> 16777 bytes 3 files changed, 120 insertions(+) create mode 100644 apache-poi/src/main/java/com/baeldung/poi/excel/ExcelUtility.java create mode 100644 apache-poi/src/test/java/com/baeldung/poi/excel/ExcelUtilityUnitTest.java create mode 100644 apache-poi/src/test/resources/baeldung.xlsx diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelUtility.java b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelUtility.java new file mode 100644 index 0000000000..e4a5b791c9 --- /dev/null +++ b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelUtility.java @@ -0,0 +1,66 @@ +package com.baeldung.poi.excel; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; + +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.DateUtil; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +public class ExcelUtility { + private static final String ENDLINE = System.getProperty("line.separator"); + + public static String readExcel(String filePath) throws IOException { + File file = new File(filePath); + FileInputStream inputStream = null; + StringBuilder toReturn = new StringBuilder(); + try { + inputStream = new FileInputStream(file); + Workbook baeuldungWorkBook = new XSSFWorkbook(inputStream); + for (Sheet sheet : baeuldungWorkBook) { + toReturn.append("--------------------------------------------------------------------").append(ENDLINE); + toReturn.append("Worksheet :").append(sheet.getSheetName()).append(ENDLINE); + toReturn.append("--------------------------------------------------------------------").append(ENDLINE); + int firstRow = sheet.getFirstRowNum(); + int lastRow = sheet.getLastRowNum(); + for (int index = firstRow + 1; index <= lastRow; index++) { + Row row = sheet.getRow(index); + toReturn.append("|| "); + for (int cellIndex = row.getFirstCellNum(); cellIndex < row.getLastCellNum(); cellIndex++) { + Cell cell = row.getCell(cellIndex, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); + printCellValue(cell, toReturn); + } + toReturn.append(" ||").append(ENDLINE); + } + } + inputStream.close(); + + } catch (IOException e) { + throw e; + } + return toReturn.toString(); + } + + public static void printCellValue(Cell cell, StringBuilder toReturn) { + CellType cellType = cell.getCellType().equals(CellType.FORMULA) ? cell.getCachedFormulaResultType() + : cell.getCellType(); + if (cellType.equals(CellType.STRING)) { + toReturn.append(cell.getStringCellValue()).append(" | "); + } + if (cellType.equals(CellType.NUMERIC)) { + if (DateUtil.isCellDateFormatted(cell)) { + toReturn.append(cell.getDateCellValue()).append(" | "); + } else { + toReturn.append(cell.getNumericCellValue()).append(" | "); + } + } + if (cellType.equals(CellType.BOOLEAN)) { + toReturn.append(cell.getBooleanCellValue()).append(" | "); + } + } +} \ No newline at end of file diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelUtilityUnitTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelUtilityUnitTest.java new file mode 100644 index 0000000000..6638d77066 --- /dev/null +++ b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelUtilityUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.poi.excel; + +import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Paths; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +import org.junit.Before; +import org.junit.Test; + +public class ExcelUtilityUnitTest { + private static final String FILE_NAME = "baeldung.xlsx"; + private String fileLocation; + private static final String ENDLINE = System.getProperty("line.separator"); + private StringBuilder output; + + @Before + public void setupUnitTest() throws IOException, URISyntaxException, ParseException { + output = new StringBuilder(); + output.append("--------------------------------------------------------------------").append(ENDLINE); + output.append("Worksheet :Sheet1").append(ENDLINE); + output.append("--------------------------------------------------------------------").append(ENDLINE); + output.append("|| Name1 | Surname1 | 3.55696564113E11 | ").append(new SimpleDateFormat("dd/MM/yyyy").parse("4/11/2021").toString()).append(" | ‡ | ||") + .append(ENDLINE); + output.append("|| Name2 | Surname2 | 5.646513512E9 | ").append(new SimpleDateFormat("dd/MM/yyyy").parse("4/12/2021").toString()).append(" | false | ||") + .append(ENDLINE); + output.append("|| Name3 | Surname3 | 3.55696564113E11 | ").append(new SimpleDateFormat("dd/MM/yyyy").parse("4/11/2021").toString()).append(" | 7.17039641738E11 | ||") + .append(ENDLINE); + output.append("--------------------------------------------------------------------").append(ENDLINE); + output.append("Worksheet :Sheet2").append(ENDLINE); + output.append("--------------------------------------------------------------------").append(ENDLINE); + output.append("|| Name4 | Surname4 | 3.55675623232E11 | 13/04/2021 | ||").append(ENDLINE); + + fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString(); + } + + @Test + public void givenStringPath_whenReadExcel_thenReturnStringValue() throws IOException { + assertEquals(output.toString(), ExcelUtility.readExcel(fileLocation)); + + } + + @Test + public void givenStringPath_whenReadExcel_thenThrowException() { + assertThrows(IOException.class, () -> { + ExcelUtility.readExcel("baeldung"); + }); + } + +} diff --git a/apache-poi/src/test/resources/baeldung.xlsx b/apache-poi/src/test/resources/baeldung.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..a6ed6c4e6ac8b0d3bd39dd4bb114bf5e0ab56479 GIT binary patch literal 16777 zcmeHuWmFvLwl)N};O_1cB)CI@1q~2f8`nmIySoO5Ai>?;-90!24ek!NCv(opOlI!4 z?)USqJJqYJyH~yYSyj9Dez(g@LqKAHL4(19fq{{NW$-R%hJk~D1w(^@p@YG`&=9q@ zvIkh%>%9MH1F+L#a<;S}`3(7jCKK!hX#GFO|6vYvD-Xzav7oe&pCU(><=d`%p_nZ| z453ER5U(vv^%fdvq|;V=j&*DK$(v%bh+V)UWRClOuG#-S$Xnxsy zr$#BzJJ!OhKtgLBhd@ME@d6`zeXB>eIm8P})wNjc9ma94n3iaEIU*`wq>QK;#;I}g zK>mg1h|tQ#eVrnV+*-j~#sHj`M0$l-5g}hFpS9_eJ}`#_UN$EbqS3uEt|7ys6KuH^ zpG24{n9=poW=GW0m&rt&1)HvCr5Xy`BMh3yfp17;^X{_B!B?eJHPZXA7^G_Ph#cU! zX|0;lsHz=dh=gHHHxX(!-=xWNi#h3r*4fO5I9bEdAP&ebUi~i6o3_Hz{(B_9lt;*ZOe4YtQ>8qBWLKG^GSuM%AiC2!3SX!u%8e zCaVrbmo-TKo}VGW2rr*y0DDVGajs3%;7stGl zhIoY%aP0F;I^4p$NJlnl!7RS}&hQcZRnns_XHry7H{k~oo!(>?h5JR9Y~gfUS@V|yA;lY?{g^19 zy>J}fs`U8qH)xu2eTWC*s9#7S7gB1*ZxIHp;>nM&_l!!w^4dXs7Px7?ZGO%9uFQ1E z#d;u@oIWZ~Y&1&kChDum_j8WVDp|P{9pxT_dqIQuWCjpK)as8JyT|4eii&S2{gWZm zwr>x(psJg5#O=^Mmy+JN?XWbnB7gZ{#XRu&`c(zL!KmsOC)(&r<=x+^%n&C(PdEe^ zm?OvxB7;^qTQECW1I_iVt<8V4dBw^K*4bPr9)f#M5F5)qR6=Oe_E4m|bPjULb&IVe z$}d0ZVzL;gP$}0uKlW1O9B$ixcVL#Xu#gk*WIG?Rc>>H$&!WeMggWZQvRP;pkBE0H zj&weGq|YK#2XV-IT`qkY9vG(1&y|W`_aw<7&Ceu`oqZ0rXwrMjGBk z@&maIQhcO)AaKGStYVvEZVV#dlH;RugQgs~z4fF{)4zyDBk5|xuwmMekte-Lrj7SA5|6~Puy^?YUmO_lxDfl zw{NXV-EFncl9vy2%_mClV_#D#)mYBF-&5}3pvStxNYEczvFvXRb=B@F*uOoRc4UeG zwkD`_NG;6WVfpcOiUJ@zmM+67VaW?QVi{*FXw{K;_--zXlJUzEk-#UWK}F?xtOX$ISJSGQ>i z>w-eQ;xt@3ZIUsb4@7{}1*IAc?kX#?_c$-%HKd_52lcMn>mW znNkwp)m`*W^!G{xgO6xvZ>W$hnMBV{(C%aVLnpb<5{?i*POu6qe9tq9k##$`6OJ0) zAYKbY?9?3BR)s0R+4Vp4W|EC)om_Snv6(;Li0?%ZaEnUv#Otjh?$w*ZIObX`R8>gI zt!dh^B&|ijZ>VZOu;M4?3{tZS{N}2?3vbWew_X+9#K#($ zhbr|5Np9UJrNAC(Y_gpzEf`!LY2dlG*-Xm8u1mr>tip>i!Z{TOXYay>tXIp3o6Nfj z5DrtNo*jRVm_2c;b_~pkOx&y<&B_^OZy$wo-0Af>yojIdLNwc6Lp-%%@3BK(pXq)} z)D8RasorFd@@O!lG$!8G$b$4)bc!&9j$qXw03e>*8qemXm0{eck^G~qH}9x%X0vdox{hqC zmaGXX?@Cp=Qo6ezPmVp=WR3+)oNF50>*WI7p2-W`$A`Ic7H~z~PdWcqbDvDVtHOhf z-7rXd@xWlgL7Mx!z5Ap7{@eC}gB(}T+W*@}bF7?nHw#M7vCk^$@N!;BV~|B7jQD&} zDKSaTRGvjj-0;np)fM>)2fc#C4cnEdYY#rw#bx8U5GTZG=PxAEiYU8b%=oJG&is5@ z%ibijrPC!&`MN?rTDBi6+I$T*TG;=r|av`!QP+Yb?faKoUN|37J{~#m1c+C8yUaNe*X#iKs>b$E{{+( zG-2U%UQO#MQr6ydX~M z9jhA4$a5{IZPXhkA+c|44}bO8ea>$AiDV(3f4^Nxnli{+wdT~m45z>%%A{rdT1gIN zWj&fjA(F*V%Wg0s<_L0s7*?T}68dZo>G(2dT6X=iTpyOvE-Rl2E{d`xN;eR`ZtbKd z4qC9n3G%~x>cuLyL_mC>^ZX%Pp}mP_IB)J!t)v>_Q8_DQ#&9m#8u;vg`p!V;wWBwH zT3?YcQAPloc)%S>FM7z8oVR?T3af*xWko5z}hK~P5x3*svBP{JZlv(HT zP<&!A)XFb2@|E95R8MEz(7r4}NzFi7$KCD<>U@E%v0lt73{($!x}Dj#d(o}Ld?~!H z)Ej&aU2IkP<+@P$ohuFyO7`jcopDyURWFnd$v z&}xVHjke&<=sv-<{ZPLj{CXcg0pH1jDDIgnb~3>&CU$tWCWJ!=y8&Zgz38*3SQ*rI ztU{h#O}g$Y%$ZMg=4_Rmk(3s|42%lXD$yFEYGWO80Nq?3IAS_0$r?t z$j(|eT^lufzZ+ID(Tf`EHBDC_;Q}OA-7CcXjC_NB2@bXU8oQ}GcP#dFf9NFBa$P^6 z#mp~&{QXCpQ8vQIQHKj+f|ej+_ruhjzYnpDwdZ*bK;hLm)PK8Iu>RO9rlcc5dj;5< zYwi=wkduuw#n;RzWo!%wYvr25qpKgs5N*L-&e_*iYV!|Np^&(fNs1?%4N z37gR5$Y9a8BYu`=1Y)I;@w^3MC5+j$XL7)>mpw5++pm*ff4(;Ug&F-7o=iQ-OAO=> zZO4YkWyx5PHpxxPt&x5+{Al4M5?abKp`2hSTLux^V(@|0ubc4pivB`Q7bYb+>^PR229#}h6z6sKtcMO$2g zZIlF$fu9h+)mJ!jGBoQa!@(0_1nIHB_6>p4$rt7@&nG>zCF79wTW$2+6qfaYKdnnZ zFs>GzOcAyDE;)ifC-99{ROqpWY-{>rbH#k(8I5`bx%dB4*088|FFQ#v{K`bQyyDuD z*@g6n#9?FV3-h81>#p_QArvFx>k6z4XKpb18EOIFFkVxuv*+RT1g4N5KzmPw!tVs` zF9z&(rLrH%65wyKxqxF?k)^6m(N^M#Kgi)rhtDp=@w0FDn5&>Wl7A3BNh67}k3{HS zwH>mpwk4oHWx2;ntCW738VaPnuR6dDoXJ@!uWT?;jQ!Rn_;W}3->M-U*eI>CFkoQ4 zB)?@6e^^s{6M!Xv`N#Q(Aw5tV3B~8cXv4k}M6`2y;P@6vxw1B95xY!bm=;G+Q+uGG z!p0iYjF0|;lKWDTCMP#h#F{^DQV0U6bf_h}0ykv_a#X?Hm5h?WTQ_Ghx z*XbTE=k}+QEuUQ8enRMsNziGPKjTjgoBu>HmEdX4MZ@kUClMEh3V^e^MPPW4Ud-?S zqFN5X_RT}widkeO5KD3|(qZ+$21M7l8*zEBQib(NbdqOa^$`&Iu6)9x&s8kJA&&#QOfUTvFVTkU zL-^9W&O13YFLvw3?_@<}+)9jIP^<3A?ks4zo!TSYLJ5Tpfsf&A!Y1 zNA^|{%wevjt@m5iKNb+|xSxu_P%0pNy<2qVZ4TOb}{&Sh{J<9`#5gXUU z5z2&V1vI+?(~Q0t@6Tmo=xB7!Ngry<*Ik&)i%A0O1DO14%$yn)Fbz9*BhXh6eT7?M zXvY+ykctizm1I7Uac-%H9kB|4dA(4iklYyPL6jSZt*j5F;a=-rq@039vkpL`(yf0_ zizKCdQzqd3lt&&?%fgxyucaIO0blXTS-*QgruKn8bB2?IIi272>16Lbu#MmIV)wR7 zr?R1jPTC5FQc3A(CQ|45@ezAPr|s$F`zhz%H1%m`ciY45P-5HjDbHp3#u6rTtNYp6 zUM%*i`{j;YB;mp$0pX_;(%_1d(shGls!%=em-naOf@$3>BHb}UsJo8&M??KDv^7Y+ zcRG|Gb}kZp=!I(LYcv1aNPOBr5s_5(rUGioAj}cRiD#`adFbTCCS7JZ_PimuDR?~E z{D?`a80>n7EmL(v@oRWFU>hj}EjW*>V^XQDLNtu9s7W+vYmT3FL#90V;s~Y8H)x7d z6sSw7$W$$=A2ienAn{u`8(Fa|>&iEu;de76*8|-Li$_qwR_~Arlfr=_x7aHV!q!m3 zO;(_1$6KmWW(qNv5Zd!Q0|r0oZJxkOJmEHY#BVR}iL|<3$4CQrCmTX>*rNFz=fmas z>=tBV`nx@-UXqGOJNZgtyG4HG72_8rkgt5TR0mhv`DjE|54CBQ97i2=2N)%+Xbwwi zA;z}%DGvoK@YT-Oj0Cgs@|+jMFErsO*@yMwxYh~SeHhnc8`^1@P$koiCp?fUrtcqB zzD(5x2gDSb&(Z=DVd(+ar*W3$#@4nz&R8_TsH-`*cw);^T3lPH?_JU&UcOu7c(Fyi z89GHf2er!*)6^!p9}cT#oalmenEVf7l9%>t=>aa#eRVf}&vV!>1Pj z3y+As>=T6fq$!qGq;7E(molI78W{rPjY}Gh+Sa2ovgVP|96Sy5TRHVk~eH>2; z4PZyiy9(}_n8Dn|Bz>vfCZ^bK_M@_$_RP)meWB5mwm=zR)I8~2z4!9!QrIl1+0A>9 z>iBFoU9P!ei;XnyXb7sONyNz=vUws5h9!Sdp^>`541ARACYj?C!%`eM<2PF>L2A~8 z$ZP3x1gMx>XIjm0(L|}d zU3LEBm6GXwkKOl9YKhP^U#D>NWQ_0?9B>qLUW#C78~bU0P5Lll|6xM@dt#RQ8`~{- z7E4S_=dG(X@s_PX;RWFUBZ9ac1I#bgNzGxU@S{m@Tw>V@lECHlnb}Ap?UlYZ+I}>1 zFfD8m&tW7Fv#$zgnPl<7UT5GPNw`<*ZA=QBW|eEuZ@>q#eGf-QH5VtNuJ@**QX22( zwYse_gRP?@XE(n^-^J;gbB1mppVq+stW@uaE17O}i(MHg7RRF*D?14ND*BUa zTsNZ*qh~x4`vk#fOL|o=6an>b$wKtRDYhu~y#3Cs9pt6~%Qy<@vc%r&N~JbWg*~f; z#S~u&I$MatBU>PNb~sUUK73%NhlvRG3iSnkA9>}SQjQtDb?daDJ7_Z395Trr7eUSw zD)0FDlVN%%M{w!zgd9CFj@;Mej;wtqzE6b^S1oeOoWwJOcF?BV#(6z-->2f-#>tz{#m1BCi{h@lh;<@4&D|t^f81-` z(4|Jl=r@hS*W!|{*E{*LyzT}-yP_X*L0&5G+$2b z-+^oDjf*>)mi5gs9evwk9PvjD4VBRu#;#ev+i2DN>SlY4N|JV8GnlDn>1gI}RKrgL z*&>@gelW}9uU(>XjO4OhK0&~D(n5~(a$&|wexDP*23V&7Yeot1$X3gTiI?Kdufu=L zd?cYa(A}bSH*5vFHfySV{@Y+yKKrB4ILJYj1DRl?-_5U`{YMLc-EUrLj$k=&LjBn+ryIGbt?0z zGCkLVk`@~!`hku!jzUtA&w!;*8^6&gLG}WQ8cHd}yA$u(8@k6E($W#{sX)S9XmGz` z^k%j^^+v0-<9w1!|H6Df=G;ji9Io#r8mh@LpKB8#ogl_i8hluSUHx+Vbs)%sJk02* zRX>vjSmGFOkL&4CoNXPd(7k(2kYDQ|0i3>LBg|AG_O+iiwuKz3DO5IP0-I9?3;^#^ zk2S4~a8AmBK~rK)LaD8!SmX&fy!zVa>ErgmbuF^xdo7tV_`Tv$M~W_Zmj;PG3Q&j}h&N#Ndt_Q{GF@Wj^y*m3wG@AS>y3!eM; zk=eB2+>A&lGZsx%MGBY?R&lQ~J@Bx@EaEAa@+N)5@Fl3fqzcX-J!_}y)ltTT_xm+4 zq9GplW3AWwiv?Il&Ji;_VU+Zxw+F}Y47>51&OYPKYPbnNj5%Chq+SrqeEj-;=-rceYLvrQvg;`JiMdMY5WgkI&e8842_ zH%vM7;y^8AW>T8ge*SXG8UJ09&(U(78d!B4@P zb7NCU=?vW6b3(>2k!xV~NxJ4f3Sf#rT)#o9F=n zhD!E8Q!C>i8ekt?Aq&cZiMdidbpXe>2gG4X`&3C3v?1KQB(Inf4jfKOQ6KmtB)ntf z?+y=!i;LxSIzr_nHpv_-1>P%yUD?_=A8s!0pD+7jbYsEnlZ#Ndd2bFZt(cHu0k8{V z$rbQ}1llqcfaU$VcjIVmhCbj2(drM>$UEo~(^uq(jI$Cw%a zCYCLEq=#~&3Mms4zr^T<_rx(n&cM`Vbe(Y01yGKNpK+I8SQ}^dy~a&|)U~PCE-BnG zU?lylK7g5fJ-w@wlL}$=W;pmzaNDzBWvmx*%8vof+2nl@g(Z(8awNcD5}IsRy;l z9n(G(|Hgs=${1bl&l3Fo%7;UKAQrs6`s8#+02j7Dylm$L%4YtR1qS-p&UK(VR}Kdl z81?T$U;|PNdjL=gU~m7MhA{u~`xTSEsnvn{yD);cm>x~99ns`5KGU$0im3RZgy>f{ zsrgtkoID(k7H>!H5m|`j$^nT>DL25H5 zeCP`gE=H7)DZ(nLA<{w=50ZLz*~CYlz+{dk)nGwsYPr-q{72iCi>t{qG{y-*VjwY# ztzd(_!$;ifq9N)Ntwc-zN-fi?=+*>%^H%0>F7W=(8&zskvoirhHAdI8JY0|KzQ=sa z1rJY6p*$_^6$A=vwYMPxh4$)p>cHywNFwW%&c3epw6LWPQ?imQ>k8w@@u4rC5<0m= zNz-49ZMB4M35-G|>2G-7?%%8kKXOYj^*3}WLY#5z;+Jc6xWiETYKw((^x+4J4`o@A zEVORN_V3uf>Da}>5q1qH2T_I}7_u$T}uq*|TU~Jc7;bp-}An5VKN?maY z;nTmTH(&JEFDlyi-*BuN&nKAp@Q$Ol=HW5o z*xJIkaUh{o=$JrVAJOKUCN5N7`jo$K&!veyV^}W@!AHU)bMv*Q^to*;Ff)mc!7? z-?otmH&J5*KE5xV@hX2{D_~t0=UXzY$*ja+-BKFT;@Lt_;l9FZIYjhJd^44Tua_aE z*6@OvDs7R)D8d^?xVX4TN-%q8I@hNlGxwmBl@W zWTZ%a>~40Gwz)ezr4$wmS>K-`tdj_R*;3xOFUb`1ric%)Q9>WwPqN zo_|E`E#)-L+}17hmr(#)cpq2qZ|~q(lZB!OD5K^ZO;)B0Y26Q%6gO;Z*SDy6s$149>HwuMvzME>B!s8!x;w=6Tob@DMAWXJ_gO4F)8~g|pFoDbE;IdS=>+;4{8`H@ccR?^XGeGOtxg*@Y(m&MY6f ztddKmf(O16y|AwZ<_vvoYWkk-H{R84ZRM>##Nvyb-sq1nPc-14Xisusly2W8^nJQ_ z&DcT~2lg7T59P{zdDJp`NW$RuuBU-y4~86-hpe?WOjtpb1zz?)k)f>Mbh%>~(6abg$9w3jc(B5{dDE zY2yI#X;H`90`?(>%oFqG#7@e!ozq+G8M-vE;}CRDFHUl)L3Og~&NG~r|-#s<1ISDF<@18R~YjvQ4?{i-;O-{Q7B!xi`>t&5cfz_g{6O3%YsW&h|i!+xA6q0Bw&Tvw8vYlY^PL&f%la!6m&ocjvl z>n*9|1My~LM0slxRe4l@OpMQLxe|(>Re4qcdzR&pR zHGeuN-!lYyqx_!tG0?Lx5H-;=wfe0pAQmAE>cv43zxHv0t*SFE3X+&&5|hh>f!&*j zjFB9GoLIyc-rw%>BqnOZPwxnYp>mAIU{^+ZG0;6Rk+bI5V)2rM%N(yJ(hpv{pXFj- z*|?gMx`;4XpF~C1E(kKMKptpqW5;Y@4Fvr5 zFrYz)f0{i(f3jbUf^-)PhW{$mv*>_pN}ipP$fEaPIstqNO{@Q=6~b#%iO9Nc^nlWS7g(0mSJZk$dqAA2tO|%gT>Y!Y-m^XMaxW}q>l}oaOU~EjZwRN_Z z^DeGyXs&qcKS?aJYahmIgs>9o>w3JY zYmrQ4N~IMRm9cicHC0%IC%t?W0zqfjL0i}EW;uju(LT7_0A%gU{@BzN!rg|rzaoKh z9cZ_oOOUS>OoT)RUtyxNk<afCgPP$W@nZlbSW*5cetI@G|41K*W&b)- zV}z|2SrGk?A+CrKm+`s3$|HIgf0p39DAxmzsWn#4Gsvo?2r7=gn2W4cm{UWBav{GZ zN*9b(RPC!B;E~w%VeSS-haxs3<(>zMEFF4kJ)q#moaUPP1d61B^~68jiCZcKMfHOl z5v*6Ba42X>2iFG7uK57Qq%alDgBI{q3b+r^3}y!F8>rKzz}Y#=Y~bg&8X0fxaZBS4h*0%-kIA{dupS zz_yBZTE^Q#?@v$nx3c8@9hYge5A)LTw99n%ZRHnfYtlt zidoB%Q;v=7tIdS=cC~>(*5x_dJPjSuAX_=0nb(IvK0YCQ!FboFy{poG7J6?)*UF5;@_YH+@AKZQ zOq3M%Mc+*91Mi)Tmc;MgJ{(M^nHmOoUAMW z)pb`8zx`w*vKzAgqXGa^dOTB)}gxBC2tY+u^zLkvdl}{tQZn6mdyjQH1~CE4oEN zB1-bj<|4zi1>GgvC*M}BLn9N}cL=UgRhiIA3T^WzOBPP&jc)2YRYC!=O5->mR*%>! z6>10a>Pv-ndm#d(2So@Jw{5Y&ARYKagG~y90|)1^?sdDqy^34tLcLH%2lANABTc zx%>ne!2bd8v+3nm(qG#Iev)<*{Z9I8)4;C?zgE+KBCHbs%7eeHt^W%6YjOG~;5y0w z1Mp|5`d7eT)15y7H%Wg0{!-}u+rsbv9CVHDe**d=qxvi8uffUBJ6&S?0s5y<