This commit is contained in:
Jonathan Cook 2020-06-14 10:20:41 +02:00
commit 754e7f3d49
52 changed files with 1015 additions and 107 deletions

View File

@ -17,6 +17,15 @@ public class StringToIntOrIntegerUnitTest {
assertThat(result).isEqualTo(42);
}
@Test
public void givenBinaryString_whenParsingInt_shouldConvertToInt() {
String givenString = "101010";
int result = Integer.parseInt(givenString, 2);
assertThat(result).isEqualTo(42);
}
@Test
public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() {
String givenString = "42";
@ -27,6 +36,15 @@ public class StringToIntOrIntegerUnitTest {
}
@Test
public void givenBinaryString_whenCallingIntegerValueOf_shouldConvertToInt() {
String givenString = "101010";
Integer result = Integer.valueOf(givenString, 2);
assertThat(result).isEqualTo(new Integer(42));
}
@Test
public void givenString_whenCallingValueOf_shouldCacheSomeValues() {
for (int i = -128; i <= 127; i++) {
String value = i + "";

View File

@ -16,12 +16,39 @@
<build>
<finalName>guava-collections-map</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties>
</project>

View File

@ -13,8 +13,32 @@
<relativePath>../parent-java</relativePath>
</parent>
<build>
<finalName>guava-collections-set</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<dependencies>
<!-- test scoped -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
@ -23,13 +47,10 @@
</dependency>
</dependencies>
<build>
<finalName>guava-collections-set</finalName>
</build>
<properties>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties>
</project>

View File

@ -15,6 +15,25 @@
<relativePath>../parent-java</relativePath>
</parent>
<build>
<finalName>guava-collections</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<dependencies>
<!-- utils -->
<dependency>
@ -27,7 +46,20 @@
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
@ -44,16 +76,6 @@
</dependency>
</dependencies>
<build>
<finalName>guava-collections</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<!-- util -->
<commons-collections4.version>4.1</commons-collections4.version>
@ -61,6 +83,7 @@
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<java-hamcrest.version>2.0.0.0</java-hamcrest.version>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties>
</project>

View File

@ -4,6 +4,9 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>guava-io</artifactId>
<version>0.1.0-SNAPSHOT</version>
<properties>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties>
<name>guava-io</name>
<parent>
@ -15,12 +18,35 @@
<build>
<finalName>guava-io</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -11,8 +11,11 @@ import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import org.junit.After;
import org.junit.Test;
import com.google.common.base.Charsets;
@ -31,6 +34,21 @@ import com.google.common.io.Resources;
public class GuavaIOUnitTest {
@After
public void afterEach() throws Exception {
deleteProducedFiles();
}
private void deleteProducedFiles() throws IOException {
deleteIfExists("test.out");
deleteIfExists("test_copy.in");
deleteIfExists("test_le.txt");
}
private void deleteIfExists(String fileName) throws IOException {
java.nio.file.Files.deleteIfExists(Paths.get("src", "test", "resources", fileName));
}
@Test
public void whenWriteUsingFiles_thenWritten() throws IOException {
final String expectedValue = "Hello world";
@ -206,5 +224,4 @@ public class GuavaIOUnitTest {
assertEquals(value, result);
}
}

View File

@ -0,0 +1 @@
Hello world

View File

@ -0,0 +1 @@
Test

View File

@ -0,0 +1,4 @@
John
Jane
Adam
Tom

View File

@ -8,9 +8,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<artifactId>guava-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<properties>

View File

@ -8,9 +8,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<artifactId>guava-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<properties>

View File

@ -8,9 +8,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<artifactId>guava-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -4,13 +4,16 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>guava-modules</artifactId>
<name>guava-modules</name>
<properties>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<modules>
@ -19,4 +22,28 @@
<module>guava-21</module>
</modules>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -15,13 +15,45 @@
<relativePath>../parent-java</relativePath>
</parent>
<build>
<finalName>guava</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
@ -30,18 +62,9 @@
</dependency>
</dependencies>
<build>
<finalName>guava</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<!-- testing -->
<junit-jupiter.version>5.6.2</junit-jupiter.version>
<assertj.version>3.6.1</assertj.version>
</properties>

View File

@ -60,6 +60,7 @@
</dependencies>
<properties>
<h2.version>1.4.200</h2.version>
<postgresql.version>42.2.5.jre7</postgresql.version>
<assertj-core.version>3.10.0</assertj-core.version>
<commons-dbcp2.version>2.4.0</commons-dbcp2.version>

View File

@ -0,0 +1,93 @@
package com.baeldung.genkeys;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import static org.assertj.core.api.Assertions.assertThat;
public class JdbcInsertIdIntegrationTest {
private static final String QUERY = "insert into persons (name) values (?)";
private static Connection connection;
@BeforeClass
public static void setUp() throws Exception {
connection = DriverManager.getConnection("jdbc:h2:mem:generated-keys", "sa", "");
connection
.createStatement()
.execute("create table persons(id bigint auto_increment, name varchar(255))");
}
@AfterClass
public static void tearDown() throws SQLException {
connection
.createStatement()
.execute("drop table persons");
connection.close();
}
@Test
public void givenInsert_whenUsingAutoGenFlag_thenBeAbleToFetchTheIdAfterward() throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(QUERY, Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, "Foo");
int affectedRows = statement.executeUpdate();
assertThat(affectedRows).isPositive();
try (ResultSet keys = statement.getGeneratedKeys()) {
assertThat(keys.next()).isTrue();
assertThat(keys.getLong(1)).isGreaterThanOrEqualTo(1);
}
}
}
@Test
public void givenInsert_whenUsingAutoGenFlagViaExecute_thenBeAbleToFetchTheIdAfterward() throws SQLException {
try (Statement statement = connection.createStatement()) {
String query = "insert into persons (name) values ('Foo')";
int affectedRows = statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
assertThat(affectedRows).isPositive();
try (ResultSet keys = statement.getGeneratedKeys()) {
assertThat(keys.next()).isTrue();
assertThat(keys.getLong(1)).isGreaterThanOrEqualTo(1);
}
}
}
@Test
public void givenInsert_whenUsingReturningCols_thenBeAbleToFetchTheIdAfterward() throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(QUERY, new String[] { "id" })) {
statement.setString(1, "Foo");
int affectedRows = statement.executeUpdate();
assertThat(affectedRows).isPositive();
try (ResultSet keys = statement.getGeneratedKeys()) {
assertThat(keys.next()).isTrue();
assertThat(keys.getLong(1)).isGreaterThanOrEqualTo(1);
}
}
}
@Test
public void givenInsert_whenUsingReturningColsViaExecute_thenBeAbleToFetchTheIdAfterward() throws SQLException {
try (Statement statement = connection.createStatement()) {
String query = "insert into persons (name) values ('Foo')";
int affectedRows = statement.executeUpdate(query, new String[] { "id" });
assertThat(affectedRows).isPositive();
try (ResultSet keys = statement.getGeneratedKeys()) {
assertThat(keys.next()).isTrue();
assertThat(keys.getLong(1)).isGreaterThanOrEqualTo(1);
}
}
}
}

View File

@ -13,4 +13,5 @@ This module contains articles about the Java Persistence API (JPA) in Java.
- [JPA Annotation for the PostgreSQL TEXT Type](https://www.baeldung.com/jpa-annotation-postgresql-text-type)
- [Mapping a Single Entity to Multiple Tables in JPA](https://www.baeldung.com/jpa-mapping-single-entity-to-multiple-tables)
- [Constructing a JPA Query Between Unrelated Entities](https://www.baeldung.com/jpa-query-unrelated-entities)
- [When Does JPA Set the Primary Key](https://www.baeldung.com/jpa-strategies-when-set-primary-key)
- More articles: [[<-- prev]](/java-jpa)

View File

@ -0,0 +1,36 @@
package com.baeldung.jpa.generateidvalue;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "app_admin")
public class Admin {
@Id
@GeneratedValue
private Long id;
@Column(name = "admin_name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.jpa.generateidvalue;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "article")
public class Article {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "article_gen")
@SequenceGenerator(name = "article_gen", sequenceName = "article_seq")
private Long id;
@Column(name = "article_name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.jpa.generateidvalue;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name = "id_gen")
@Entity
public class IdGenerator {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "gen_name")
private String gen_name;
@Column(name = "gen_value")
private Long gen_value;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getGen_name() {
return gen_name;
}
public void setGen_name(String gen_name) {
this.gen_name = gen_name;
}
public Long getGen_value() {
return gen_value;
}
public void setGen_value(Long gen_value) {
this.gen_value = gen_value;
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.jpa.generateidvalue;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
@Entity
@Table(name = "task")
public class Task {
@Id
@TableGenerator(name = "id_generator", table = "id_gen", pkColumnName = "gen_name", valueColumnName = "gen_value", pkColumnValue = "task_gen", initialValue = 10000, allocationSize = 10)
@GeneratedValue(strategy = GenerationType.TABLE, generator = "id_generator")
private Long id;
@Column(name = "name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.jpa.generateidvalue;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "app_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "user_name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -184,4 +184,29 @@
value="false" />
</properties>
</persistence-unit>
<persistence-unit name="jpa-h2-primarykey">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.baeldung.jpa.generateidvalue.Admin</class>
<class>com.baeldung.jpa.generateidvalue.Article</class>
<class>com.baeldung.jpa.generateidvalue.IdGenerator</class>
<class>com.baeldung.jpa.generateidvalue.Task</class>
<class>com.baeldung.jpa.generateidvalue.User</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver"
value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:h2:mem:test" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="javax.persistence.sql-load-script-source"
value="primary_key_generator.sql" />
<property name="eclipselink.ddl-generation" value="create-or-extend-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
<property name="eclipselink.weaving" value="static" />
<property name="eclipselink.logging.level" value="FINE" />
<property name="eclipselink.jdbc.allow-native-sql-queries" value="true" />
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,4 @@
CREATE SEQUENCE article_seq MINVALUE 1 START WITH 50 INCREMENT BY 50;
INSERT INTO id_gen (gen_name, gen_val) VALUES ('id_generator', 0);
INSERT INTO id_gen (gen_name, gen_val) VALUES ('task_gen', 10000);

View File

@ -0,0 +1,81 @@
package com.baeldung.jpa.generateidvalue;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* PrimaryKeyGeneratorTest class
*
* @author shiwangzhihe@gmail.com
*/
public class PrimaryKeyUnitTest {
private static EntityManager entityManager;
@BeforeClass
public static void setup() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa-h2-primarykey");
entityManager = factory.createEntityManager();
}
@Test
public void givenIdentityStrategy_whenCommitTransction_thenReturnPrimaryKey() {
User user = new User();
user.setName("TestName");
entityManager.getTransaction()
.begin();
entityManager.persist(user);
Assert.assertNull(user.getId());
entityManager.getTransaction()
.commit();
Long expectPrimaryKey = 1L;
Assert.assertEquals(expectPrimaryKey, user.getId());
}
@Test
public void givenTableStrategy_whenPersist_thenReturnPrimaryKey() {
Task task = new Task();
task.setName("Test Task");
entityManager.getTransaction()
.begin();
entityManager.persist(task);
Long expectPrimaryKey = 10000L;
Assert.assertEquals(expectPrimaryKey, task.getId());
entityManager.getTransaction()
.commit();
}
@Test
public void givenSequenceStrategy_whenPersist_thenReturnPrimaryKey() {
Article article = new Article();
article.setName("Test Name");
entityManager.getTransaction()
.begin();
entityManager.persist(article);
Long expectPrimaryKey = 51L;
Assert.assertEquals(expectPrimaryKey, article.getId());
entityManager.getTransaction()
.commit();
}
@Test
public void givenAutoStrategy_whenPersist_thenReturnPrimaryKey() {
Admin admin = new Admin();
admin.setName("Test Name");
entityManager.persist(admin);
Long expectPrimaryKey = 1L;
Assert.assertEquals(expectPrimaryKey, admin.getId());
}
}

View File

@ -1,13 +0,0 @@
# Logs
logs
*.log
# Git
.git
.cache
# Classes
**/*.class
# Ignore md files
*.md

View File

@ -1,10 +0,0 @@
FROM maven:3.6.0-jdk-11
WORKDIR /code/spring-boot-modules/spring-boot-properties/
COPY ./spring-boot-modules/spring-boot-properties/pom.xml .
COPY ./spring-boot-modules/spring-boot-properties/src ./src
COPY ./parent-boot-2/pom.xml /code/parent-boot-2/pom.xml
COPY ./pom.xml /code/pom.xml
COPY ./custom-pmd-0.0.1.jar /code/custom-pmd-0.0.1.jar
COPY ./baeldung-pmd-rules.xml /code/baeldung-pmd-rules.xml
RUN mvn dependency:resolve
CMD ["mvn", "spring-boot:run"]

View File

@ -11,6 +11,9 @@ import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.baeldung.yaml.YAMLConfig.Idm;
import com.baeldung.yaml.YAMLConfig.Service;
@SpringBootApplication
public class MyApplication implements CommandLineRunner {
@ -26,6 +29,23 @@ public class MyApplication implements CommandLineRunner {
System.out.println("using environment:" + myConfig.getEnvironment());
System.out.println("name:" + myConfig.getName());
System.out.println("servers:" + myConfig.getServers());
if ("testing".equalsIgnoreCase(myConfig.getEnvironment())) {
System.out.println("external:" + myConfig.getExternal());
System.out.println("map:" + myConfig.getMap());
Idm idm = myConfig.getComponent().getIdm();
Service service = myConfig.getComponent().getService();
System.out.println("Idm:");
System.out.println(" Url: " + idm.getUrl());
System.out.println(" User: " + idm.getUser());
System.out.println(" Password: " + idm.getPassword());
System.out.println(" Description: " + idm.getDescription());
System.out.println("Service:");
System.out.println(" Url: " + service.getUrl());
System.out.println(" Token: " + service.getToken());
System.out.println(" Description: " + service.getDescription());
}
}
}

View File

@ -1,7 +1,10 @@
package com.baeldung.yaml;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@ -13,6 +16,9 @@ public class YAMLConfig {
private String name;
private String environment;
private List<String> servers = new ArrayList<String>();
private List<String> external = new ArrayList<String>();
private Map<String, String> map = new HashMap<String, String>();
private Component component = new Component();
public List<String> getServers() {
return servers;
@ -37,5 +43,111 @@ public class YAMLConfig {
public void setEnvironment(String environment) {
this.environment = environment;
}
public Component getComponent() {
return component;
}
public void setComponent(Component component) {
this.component = component;
}
public Map<String, String> getMap() {
return map;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
public List<String> getExternal() {
return external;
}
public void setExternal(List<String> external) {
this.external = external;
}
public class Component {
private Idm idm = new Idm();
private Service service = new Service();
public Idm getIdm() {
return idm;
}
public void setIdm(Idm idm) {
this.idm = idm;
}
public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}
}
public class Idm {
private String url;
private String user;
private String password;
private String description;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
public class Service {
private String url;
private String token;
private String description;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
}

View File

@ -6,22 +6,42 @@ spring:
---
spring:
profiles: test
profiles: test
name: test-YAML
environment: testing
servers:
- www.abc.test.com
- www.xyz.test.com
- www.abc.test.com
- www.xyz.test.com
external: [www.abc.test.com, www.xyz.test.com]
map:
firstkey: key1
secondkey: key2
component:
idm:
url: myurl
user: user
password: password
description: >
this should be a long
description
service:
url: myurlservice
token: token
description: >
this should be another long
description
---
spring:
profiles: prod
profiles: prod
name: prod-YAML
environment: production
servers:
- www.abc.com
- www.xyz.com
- www.abc.com
- www.xyz.com
---

View File

@ -11,6 +11,7 @@ import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApplication.class)
@TestPropertySource(properties = {"spring.profiles.active = test"})
class YAMLIntegrationTest {
@Autowired
@ -20,5 +21,6 @@ class YAMLIntegrationTest {
void whenProfileTest_thenNameTesting() {
assertTrue("testing".equalsIgnoreCase(config.getEnvironment()));
assertTrue("test-YAML".equalsIgnoreCase(config.getName()));
assertTrue("myurl".equalsIgnoreCase(config.getComponent().getIdm().getUrl()));
}
}

View File

@ -22,16 +22,6 @@
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_${scala.version}</artifactId>
<version>${spark.version}</version>
<exclusions>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

View File

@ -13,7 +13,7 @@ import java.util.stream.IntStream;
public class PiApproximation {
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("BaeldungPIApproximation");
SparkConf conf = new SparkConf().setAppName("BaeldungPIApproximation").setMaster("local[2]");
JavaSparkContext context = new JavaSparkContext(conf);
int slices = args.length >= 1 ? Integer.valueOf(args[0]) : 2;
int n = (100000L * slices) > Integer.MAX_VALUE ? Integer.MAX_VALUE : 100000 * slices;

View File

@ -11,9 +11,8 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-1</artifactId>
<artifactId>spring-cloud-data-flow</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-1</relativePath>
</parent>
<dependencyManagement>
@ -21,7 +20,7 @@
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.SR5</version>
<version>Hoxton.SR4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -31,8 +30,7 @@
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-task-starter</artifactId>
<version>${spring-cloud-task-starter.version}</version>
<artifactId>spring-cloud-starter-task</artifactId>
</dependency>
<dependency>
@ -48,7 +46,7 @@
</dependencies>
<properties>
<spring-cloud-task-starter.version>1.0.3.RELEASE</spring-cloud-task-starter.version>
<spring-cloud-task-starter.version>2.2.3.RELEASE</spring-cloud-task-starter.version>
</properties>
</project>

View File

@ -9,8 +9,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<modules>

View File

@ -9,9 +9,8 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>spring-cloud-data-flow-etl</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-2</relativePath>
</parent>
<dependencyManagement>
@ -63,7 +62,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
<spring-cloud.version>Hoxton.SR4</spring-cloud.version>
</properties>
</project>

View File

@ -9,9 +9,8 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>spring-cloud-data-flow-etl</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-2</relativePath>
</parent>
<dependencyManagement>
@ -55,7 +54,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
<spring-cloud.version>Hoxton.SR4</spring-cloud.version>
</properties>
</project>

View File

@ -10,9 +10,8 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-1</artifactId>
<artifactId>spring-cloud-data-flow-stream-processing</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-1</relativePath>
</parent>
<dependencyManagement>
@ -35,7 +34,7 @@
</dependencies>
<properties>
<spring-cloud-dependencies.version>Brixton.SR7</spring-cloud-dependencies.version>
<spring-cloud-dependencies.version>Hoxton.SR4</spring-cloud-dependencies.version>
</properties>
</project>

View File

@ -2,6 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-cloud-data-flow-stream-processing</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-cloud-data-flow-stream-processing</name>
@ -9,9 +10,8 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
<artifactId>spring-cloud-data-flow</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modules>
@ -21,5 +21,13 @@
<module>time-processor</module>
<module>log-sink</module>
</modules>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -10,9 +10,8 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-1</artifactId>
<artifactId>spring-cloud-data-flow-stream-processing</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-1</relativePath>
</parent>
<dependencyManagement>
@ -35,7 +34,7 @@
</dependencies>
<properties>
<spring-cloud-dependencies.version>Brixton.SR7</spring-cloud-dependencies.version>
<spring-cloud-dependencies.version>Hoxton.SR4</spring-cloud-dependencies.version>
</properties>
</project>

View File

@ -2,6 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>time-source</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>time-source</name>
@ -10,9 +11,8 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-1</artifactId>
<artifactId>spring-cloud-data-flow-stream-processing</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-1</relativePath>
</parent>
<dependencyManagement>
@ -35,7 +35,7 @@
</dependencies>
<properties>
<spring-cloud-dependencies.version>Brixton.SR7</spring-cloud-dependencies.version>
<spring-cloud-dependencies.version>Hoxton.SR4</spring-cloud-dependencies.version>
</properties>
</project>

View File

@ -9,10 +9,10 @@
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-1</relativePath>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.13.RELEASE</version>
<relativePath />
</parent>
<dependencies>
@ -32,6 +32,11 @@
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -45,7 +50,7 @@
</build>
<properties>
<spring-cloud-starter-stream.version>1.3.1.RELEASE</spring-cloud-starter-stream.version>
<spring-cloud-starter-stream.version>2.1.2.RELEASE</spring-cloud-starter-stream.version>
</properties>
</project>

View File

@ -8,7 +8,7 @@ import java.util.concurrent.Executors;
@SuppressWarnings("ALL")
public final class GlobalEventBus {
public static final String GLOBAL_EVENT_BUS_EXPRESSION = "T(com.baeldung.postprocessor.GlobalEventBus).getEventBus()";
public static final String GLOBAL_EVENT_BUS_EXPRESSION = "T(com.baeldung.beanpostprocessor.GlobalEventBus).getEventBus()";
private static final String IDENTIFIER = "global-event-bus";

View File

@ -0,0 +1,7 @@
## Spring RestTemplate
This module contains articles about Spring RestTemplate
### Relevant Articles:

View File

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-resttemplate</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-resttemplate-2</name>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>
<!-- Spring Boot Dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,14 @@
package com.baeldung.resttemplate.logging;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableAutoConfiguration
public class RestTemplateConfigurationApplication {
public static void main(String[] args) {
SpringApplication.run(RestTemplateConfigurationApplication.class, args);
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.resttemplate.logging.web.controller;
import java.util.Arrays;
import java.util.List;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PersonController {
@PostMapping("/persons")
public List<String> getPersons() {
return Arrays.asList(new String[] { "Lucie", "Jackie", "Danesh", "Tao" });
}
}

View File

@ -0,0 +1,2 @@
server.port=8080
server.servlet.context-path=/spring-rest

View File

@ -0,0 +1,29 @@
package com.baeldung.resttemplate.logging;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
public class LoggingInterceptor implements ClientHttpRequestInterceptor {
final static Logger log = LoggerFactory.getLogger(LoggingInterceptor.class);
@Override
public ClientHttpResponse intercept(HttpRequest req, byte[] reqBody, ClientHttpRequestExecution ex) throws IOException {
log.debug("Request body: {}", new String(reqBody, StandardCharsets.UTF_8));
ClientHttpResponse response = ex.execute(req, reqBody);
InputStreamReader isr = new InputStreamReader(response.getBody(), StandardCharsets.UTF_8);
String body = new BufferedReader(isr).lines()
.collect(Collectors.joining("\n"));
log.debug("Response body: {}", body);
return response;
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.resttemplate.logging;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RestTemplateLoggingLiveTest {
private static final String baseUrl = "http://localhost:8080/spring-rest";
@Test
public void givenHttpClientConfiguration_whenSendGetForRequestEntity_thenRequestResponseFullLog() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
final ResponseEntity<String> response = restTemplate.postForEntity(baseUrl + "/persons", "my request body", String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenLoggingInterceptorConfiguration_whenSendGetForRequestEntity_thenRequestResponseCustomLog() {
RestTemplate restTemplate = new RestTemplate();
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
if (CollectionUtils.isEmpty(interceptors)) {
interceptors = new ArrayList<>();
}
interceptors.add(new LoggingInterceptor());
restTemplate.setInterceptors(interceptors);
final ResponseEntity<String> response = restTemplate.postForEntity(baseUrl + "/persons", "my request body", String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
}

View File

@ -0,0 +1,5 @@
logging.level.org.springframework.web.client.RestTemplate=DEBUG
logging.level.com.baeldung.resttemplate.logging.LoggingInterceptor=DEBUG
logging.level.org.apache.http=DEBUG
logging.level.httpclient.wire=DEBUG
logging.pattern.console=%20logger{20} - %msg%n