Merge branch 'eugenp:master' into master
This commit is contained in:
commit
b51b9fdced
|
@ -14,6 +14,15 @@
|
|||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.24</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.java14.recordvslombok;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class ColorData {
|
||||
|
||||
private int red;
|
||||
private int green;
|
||||
private int blue;
|
||||
|
||||
public String getHexString() {
|
||||
return String.format("#%02X%02X%02X", red, green, blue);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.java14.recordvslombok;
|
||||
|
||||
public record ColorRecord(int red, int green, int blue) {
|
||||
|
||||
public String getHexString() {
|
||||
return String.format("#%02X%02X%02X", red, green, blue);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.java14.recordvslombok;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.Value;
|
||||
|
||||
@Value
|
||||
@Getter(AccessLevel.NONE)
|
||||
public class ColorValueObject {
|
||||
int red;
|
||||
int green;
|
||||
int blue;
|
||||
|
||||
public String getHexString() {
|
||||
return String.format("#%02X%02X%02X", red, green, blue);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.java14.recordvslombok;
|
||||
|
||||
import lombok.Value;
|
||||
|
||||
@Value
|
||||
public class MonochromeColor extends ColorData {
|
||||
|
||||
public MonochromeColor(int grayScale) {
|
||||
super(grayScale, grayScale, grayScale);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.java14.recordvslombok;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@Builder
|
||||
public class StudentBuilder {
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private Long studentId;
|
||||
private String email;
|
||||
private String phoneNumber;
|
||||
private String address;
|
||||
private String country;
|
||||
private int age;
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package com.baeldung.java14.recordvslombok;
|
||||
|
||||
public record StudentRecord(String firstName, String lastName, Long studentId, String email, String phoneNumber, String address, String country, int age) {
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.java14.recordvslombok;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RecordVsLombokUntTest {
|
||||
|
||||
@Test
|
||||
public void givenAColorRecord_hexStringIsCorrect() {
|
||||
var red = new ColorRecord(255, 0, 0);
|
||||
|
||||
assertThat(red.getHexString()).isEqualTo("#FF0000");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAColorValueObject_hexStringIsCorrect() {
|
||||
var red = new ColorValueObject(255, 0, 0);
|
||||
|
||||
assertThat(red.getHexString()).isEqualTo("#FF0000");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRecordWithManyAttributes_firstNameShouldBeJohn() {
|
||||
StudentRecord john = new StudentRecord("John", "Doe", null, "john@doe.com", null, null, "England", 20);
|
||||
|
||||
assertThat(john.firstName()).isEqualTo("John");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBuilderWithManyAttributes_firstNameShouldBeJohn() {
|
||||
StudentBuilder john = StudentBuilder.builder()
|
||||
.firstName("John")
|
||||
.lastName("Doe")
|
||||
.email("john@doe.com")
|
||||
.country("England")
|
||||
.age(20)
|
||||
.build();
|
||||
|
||||
assertThat(john.getFirstName()).isEqualTo("John");
|
||||
}
|
||||
|
||||
}
|
|
@ -5,4 +5,3 @@ This module contains articles about Java 15.
|
|||
### Relevant articles
|
||||
|
||||
- [Hidden Classes in Java 15](https://www.baeldung.com/java-hidden-classes)
|
||||
- [Sealed Classes and Interfaces in Java 15](https://www.baeldung.com/java-sealed-classes-interfaces)
|
||||
|
|
|
@ -5,3 +5,4 @@
|
|||
- [Introduction to HexFormat in Java 17](https://www.baeldung.com/java-hexformat)
|
||||
- [New Features in Java 17](https://www.baeldung.com/java-17-new-features)
|
||||
- [Random Number Generators in Java 17](https://www.baeldung.com/java-17-random-number-generators)
|
||||
- [Sealed Classes and Interfaces in Java 17](https://www.baeldung.com/java-sealed-classes-interfaces)
|
||||
|
|
|
@ -21,7 +21,7 @@ public class VehicleUnitTest {
|
|||
public void givenCar_whenUsingReflectionAPI_thenSuperClassIsSealed() {
|
||||
Assertions.assertThat(car.getClass().isSealed()).isEqualTo(false);
|
||||
Assertions.assertThat(car.getClass().getSuperclass().isSealed()).isEqualTo(true);
|
||||
Assertions.assertThat(car.getClass().getSuperclass().permittedSubclasses())
|
||||
Assertions.assertThat(car.getClass().getSuperclass().getPermittedSubclasses())
|
||||
.contains(ClassDesc.of(car.getClass().getCanonicalName()));
|
||||
}
|
||||
|
||||
|
@ -29,7 +29,7 @@ public class VehicleUnitTest {
|
|||
public void givenTruck_whenUsingReflectionAPI_thenSuperClassIsSealed() {
|
||||
Assertions.assertThat(truck.getClass().isSealed()).isEqualTo(false);
|
||||
Assertions.assertThat(truck.getClass().getSuperclass().isSealed()).isEqualTo(true);
|
||||
Assertions.assertThat(truck.getClass().getSuperclass().permittedSubclasses())
|
||||
Assertions.assertThat(truck.getClass().getSuperclass().getPermittedSubclasses())
|
||||
.contains(ClassDesc.of(truck.getClass().getCanonicalName()));
|
||||
}
|
||||
|
|
@ -4,3 +4,4 @@
|
|||
|
||||
### Relevant Articles:
|
||||
- [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain)
|
||||
- [Use Cases for Static Methods in Java](https://www.baeldung.com/java-static-methods-use-cases)
|
||||
|
|
|
@ -9,4 +9,5 @@ This module contains articles about core Java input/output(IO) conversions.
|
|||
- [Converting a BufferedReader to a JSONObject](https://www.baeldung.com/java-bufferedreader-to-jsonobject)
|
||||
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
|
||||
- [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv)
|
||||
- [How to Convert InputStream to Base64 String](https://www.baeldung.com/java-inputstream-to-base64-string)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-io-conversions)
|
||||
|
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.jar;
|
||||
|
||||
import java.awt.event.*;
|
||||
import java.awt.*;
|
||||
|
||||
import javax.swing.*;
|
||||
|
||||
public class MySampleGUIAppn extends JFrame {
|
||||
public MySampleGUIAppn() {
|
||||
if (!GraphicsEnvironment.isHeadless()) {
|
||||
setSize(300,300);
|
||||
setTitle("MySampleGUIAppn");
|
||||
Button b = new Button("Click Me!");
|
||||
b.setBounds(30,100,80,30);
|
||||
add(b);
|
||||
setVisible(true);
|
||||
addWindowListener(new WindowAdapter() {
|
||||
public void windowClosing(WindowEvent e) {
|
||||
dispose();
|
||||
System.exit(0);
|
||||
}
|
||||
});
|
||||
}
|
||||
else {
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
MySampleGUIAppn app=new MySampleGUIAppn();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.jar;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class MySampleGUIAppnUnitTest {
|
||||
@Test
|
||||
void testMain() throws IOException {
|
||||
System.setProperty("java.awt.headless", "true");
|
||||
String [] args = null;
|
||||
System.exit(0);
|
||||
MySampleGUIAppn.main(args);
|
||||
}
|
||||
}
|
|
@ -6,3 +6,4 @@ This module contains articles about types in Java
|
|||
|
||||
- [Convert an Array of Primitives to an Array of Objects](https://www.baeldung.com/java-primitive-array-to-object-array)
|
||||
- [Check if an Enum Value Exists in Java](https://www.baeldung.com/java-search-enum-values)
|
||||
- [Generate a Random Value From an Enum](https://www.baeldung.com/java-enum-random-value)
|
||||
|
|
|
@ -7,7 +7,6 @@
|
|||
- [Automorphic Numbers in Java](https://www.baeldung.com/java-automorphic-numbers)
|
||||
- [Convert Byte Size Into a Human-Readable Format in Java](https://www.baeldung.com/java-human-readable-byte-size)
|
||||
- [Convert boolean to int in Java](https://www.baeldung.com/java-boolean-to-int)
|
||||
- [Generate a Random Value From an Enum](https://www.baeldung.com/java-enum-random-value)
|
||||
- [Reverse a Number in Java](https://www.baeldung.com/java-reverse-number)
|
||||
- [Check if BigDecimal Value Is Zero](https://www.baeldung.com/java-bigdecimal-zero)
|
||||
- More articles: [[<-- prev]](../core-java-numbers-3) [[next -->]](../core-java-numbers-5)
|
|
@ -1,3 +1,4 @@
|
|||
## Relevant Articles:
|
||||
|
||||
- [Count Occurrences Using Java groupingBy Collector](https://www.baeldung.com/java-groupingby-count)
|
||||
- [How to Split a Stream into Multiple Streams](https://www.baeldung.com/java-split-stream)
|
||||
|
|
|
@ -0,0 +1,105 @@
|
|||
package com.baeldung.truncate;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.regex.MatchResult;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.google.common.base.Splitter;
|
||||
|
||||
public class TruncateString {
|
||||
|
||||
private static final String EMPTY = "";
|
||||
|
||||
public static String usingSubstringMethod(String text, int length) {
|
||||
if (length < 0) {
|
||||
throw new IllegalArgumentException("length cannot be negative");
|
||||
}
|
||||
|
||||
if (text == null) {
|
||||
return EMPTY;
|
||||
}
|
||||
|
||||
if (text.length() <= length) {
|
||||
return text;
|
||||
} else {
|
||||
return text.substring(0, length);
|
||||
}
|
||||
}
|
||||
|
||||
public static String usingSplitMethod(String text, int length) {
|
||||
if (length < 0) {
|
||||
throw new IllegalArgumentException("length cannot be negative");
|
||||
}
|
||||
|
||||
if (text == null) {
|
||||
return EMPTY;
|
||||
}
|
||||
|
||||
String[] results = text.split("(?<=\\G.{" + length + "})");
|
||||
|
||||
return results[0];
|
||||
}
|
||||
|
||||
public static String usingPattern(String text, int length) {
|
||||
if (length < 0) {
|
||||
throw new IllegalArgumentException("length cannot be negative");
|
||||
}
|
||||
|
||||
if (text == null) {
|
||||
return EMPTY;
|
||||
}
|
||||
|
||||
Optional<String> result = Pattern.compile(".{1," + length + "}")
|
||||
.matcher(text)
|
||||
.results()
|
||||
.map(MatchResult::group)
|
||||
.findFirst();
|
||||
|
||||
return result.isPresent() ? result.get() : EMPTY;
|
||||
|
||||
}
|
||||
|
||||
public static String usingCodePointsMethod(String text, int length) {
|
||||
if (length < 0) {
|
||||
throw new IllegalArgumentException("length cannot be negative");
|
||||
}
|
||||
|
||||
if (text == null) {
|
||||
return EMPTY;
|
||||
}
|
||||
|
||||
return text.codePoints()
|
||||
.limit(length)
|
||||
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
|
||||
.toString();
|
||||
}
|
||||
|
||||
public static String usingLeftMethod(String text, int length) {
|
||||
|
||||
return StringUtils.left(text, length);
|
||||
}
|
||||
|
||||
public static String usingTruncateMethod(String text, int length) {
|
||||
|
||||
return StringUtils.truncate(text, length);
|
||||
}
|
||||
|
||||
public static String usingSplitter(String text, int length) {
|
||||
if (length < 0) {
|
||||
throw new IllegalArgumentException("length cannot be negative");
|
||||
}
|
||||
|
||||
if (text == null) {
|
||||
return EMPTY;
|
||||
}
|
||||
|
||||
Iterable<String> parts = Splitter.fixedLength(length)
|
||||
.split(text);
|
||||
|
||||
return parts.iterator()
|
||||
.next();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
package com.baeldung.truncate;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class TruncateStringUnitTest {
|
||||
|
||||
private static final String TEXT = "Welcome to baeldung.com";
|
||||
|
||||
@Test
|
||||
public void givenStringAndLength_whenUsingSubstringMethod_thenTruncate() {
|
||||
|
||||
assertEquals(TruncateString.usingSubstringMethod(TEXT, 10), "Welcome to");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringAndLength_whenUsingSplitMethod_thenTruncate() {
|
||||
|
||||
assertEquals(TruncateString.usingSplitMethod(TEXT, 13), "Welcome to ba");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringAndLength_whenUsingPattern_thenTruncate() {
|
||||
|
||||
assertEquals(TruncateString.usingPattern(TEXT, 19), "Welcome to baeldung");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringAndLength_whenUsingCodePointsMethod_thenTruncate() {
|
||||
|
||||
assertEquals(TruncateString.usingCodePointsMethod(TEXT, 6), "Welcom");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringAndLength_whenUsingLeftMethod_thenTruncate() {
|
||||
|
||||
assertEquals(TruncateString.usingLeftMethod(TEXT, 15), "Welcome to bael");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringAndLength_whenUsingTruncateMethod_thenTruncate() {
|
||||
|
||||
assertEquals(TruncateString.usingTruncateMethod(TEXT, 20), "Welcome to baeldung.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringAndLength_whenUsingSplitter_thenTruncate() {
|
||||
|
||||
assertEquals(TruncateString.usingSplitter(TEXT, 3), "Wel");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
|
||||
## Relevant Articles:
|
||||
- [How to Pass Environment Variable Value into Dockerfile](https://www.baeldung.com/ops/dockerfile-env-variable)
|
|
@ -0,0 +1,4 @@
|
|||
FROM openjdk:11
|
||||
MAINTAINER baeldung.com
|
||||
COPY target/docker-java-jar-0.0.1-SNAPSHOT.jar app.jar
|
||||
ENTRYPOINT ["java","-jar","/app.jar"]
|
|
@ -0,0 +1,37 @@
|
|||
<?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">
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>docker-java-jar</artifactId>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>${maven-jar-plugin.version}</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>com.baeldung.HelloWorld</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung;
|
||||
|
||||
public class HelloWorld {
|
||||
|
||||
public static void main(String[] args){
|
||||
System.out.println("Welcome to our application");
|
||||
}
|
||||
}
|
|
@ -23,6 +23,7 @@
|
|||
<module>docker-images</module>
|
||||
<module>docker-spring-boot</module>
|
||||
<module>docker-spring-boot-postgres</module>
|
||||
<module>docker-java-jar</module>
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
package com.baeldung.libraries.opencsv;
|
||||
|
||||
import com.baeldung.libraries.opencsv.beans.CsvBean;
|
||||
import com.baeldung.libraries.opencsv.beans.NamedColumnBean;
|
||||
import com.baeldung.libraries.opencsv.beans.SimplePositionBean;
|
||||
import com.baeldung.libraries.opencsv.examples.sync.BeanExamples;
|
||||
|
@ -7,102 +8,60 @@ import com.baeldung.libraries.opencsv.examples.sync.CsvReaderExamples;
|
|||
import com.baeldung.libraries.opencsv.examples.sync.CsvWriterExamples;
|
||||
import com.baeldung.libraries.opencsv.helpers.Helpers;
|
||||
|
||||
import java.io.Reader;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
public class Application {
|
||||
|
||||
/*
|
||||
* Bean Examples.
|
||||
*/
|
||||
|
||||
public static String simpleSyncPositionBeanExample() {
|
||||
Path path = null;
|
||||
try {
|
||||
path = Helpers.twoColumnCsvPath();
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
}
|
||||
return BeanExamples.beanBuilderExample(path, SimplePositionBean.class).toString();
|
||||
// CSV Reader Examples
|
||||
public static List<String[]> readLineByLineSyncExample() throws Exception {
|
||||
Path path = Helpers.twoColumnCsvPath();
|
||||
return CsvReaderExamples.readLineByLine(path);
|
||||
}
|
||||
|
||||
public static String namedSyncColumnBeanExample() {
|
||||
Path path = null;
|
||||
try {
|
||||
path = Helpers.namedColumnCsvPath();
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
}
|
||||
return BeanExamples.beanBuilderExample(path, NamedColumnBean.class).toString();
|
||||
public static List<String[]> readAllLinesSyncExample() throws Exception {
|
||||
Path path = Helpers.twoColumnCsvPath();
|
||||
return CsvReaderExamples.readAllLines(path);
|
||||
}
|
||||
|
||||
public static String writeSyncCsvFromBeanExample() {
|
||||
Path path = null;
|
||||
try {
|
||||
path = Helpers.fileOutBeanPath();
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
// CSV Writer Examples
|
||||
public static String writeLineByLineSyncExample() throws Exception {
|
||||
Path path = Helpers.fileOutOnePath();
|
||||
return CsvWriterExamples.writeLineByLine(Helpers.fourColumnCsvString(), path);
|
||||
}
|
||||
|
||||
public static String writeAllLinesSyncExample() throws Exception {
|
||||
Path path = Helpers.fileOutAllPath();
|
||||
return CsvWriterExamples.writeAllLines(Helpers.fourColumnCsvString(), path);
|
||||
}
|
||||
|
||||
// Bean Examples
|
||||
public static List<CsvBean> simpleSyncPositionBeanExample() throws Exception {
|
||||
Path path = Helpers.twoColumnCsvPath();
|
||||
return BeanExamples.beanBuilderExample(path, SimplePositionBean.class);
|
||||
}
|
||||
|
||||
public static List<CsvBean> namedSyncColumnBeanExample() throws Exception {
|
||||
Path path = Helpers.namedColumnCsvPath();
|
||||
return BeanExamples.beanBuilderExample(path, NamedColumnBean.class);
|
||||
}
|
||||
|
||||
public static String writeSyncCsvFromBeanExample() throws Exception {
|
||||
Path path = Helpers.fileOutBeanPath();
|
||||
return BeanExamples.writeCsvFromBean(path);
|
||||
}
|
||||
|
||||
/*
|
||||
* CSV Reader Examples.
|
||||
*/
|
||||
|
||||
public static String oneByOneSyncExample() {
|
||||
Reader reader = null;
|
||||
try {
|
||||
reader = Files.newBufferedReader(Helpers.twoColumnCsvPath());
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
}
|
||||
return CsvReaderExamples.oneByOne(reader).toString();
|
||||
}
|
||||
|
||||
public static String readAllSyncExample() {
|
||||
Reader reader = null;
|
||||
try {
|
||||
reader = Files.newBufferedReader(Helpers.twoColumnCsvPath());
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
}
|
||||
return CsvReaderExamples.readAll(reader).toString();
|
||||
}
|
||||
|
||||
/*
|
||||
* CSV Writer Examples.
|
||||
*/
|
||||
|
||||
|
||||
public static String csvWriterSyncOneByOne() {
|
||||
Path path = null;
|
||||
try {
|
||||
path = Helpers.fileOutOnePath();
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
}
|
||||
return CsvWriterExamples.csvWriterOneByOne(Helpers.fourColumnCsvString(), path);
|
||||
}
|
||||
|
||||
public static String csvWriterSyncAll() {
|
||||
Path path = null;
|
||||
try {
|
||||
path = Helpers.fileOutAllPath();
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
}
|
||||
return CsvWriterExamples.csvWriterAll(Helpers.fourColumnCsvString(), path);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
simpleSyncPositionBeanExample();
|
||||
namedSyncColumnBeanExample();
|
||||
writeSyncCsvFromBeanExample();
|
||||
oneByOneSyncExample();
|
||||
readAllSyncExample();
|
||||
csvWriterSyncOneByOne();
|
||||
csvWriterSyncAll();
|
||||
readLineByLineSyncExample();
|
||||
readAllLinesSyncExample();
|
||||
writeLineByLineSyncExample();
|
||||
writeAllLinesSyncExample();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Error during csv processing", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -27,5 +27,10 @@ public class NamedColumnBean extends CsvBean {
|
|||
this.age = age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return name + ',' + age;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -26,4 +26,8 @@ public class SimplePositionBean extends CsvBean {
|
|||
this.exampleColTwo = exampleColTwo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return exampleColOne + ',' + exampleColTwo;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -37,4 +37,9 @@ public class WriteExampleBean extends CsvBean {
|
|||
public void setColC(String colC) {
|
||||
this.colC = colC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return colA + ',' + colB + "," + colC;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,60 +4,49 @@ import com.baeldung.libraries.opencsv.beans.CsvBean;
|
|||
import com.baeldung.libraries.opencsv.beans.WriteExampleBean;
|
||||
import com.baeldung.libraries.opencsv.helpers.Helpers;
|
||||
import com.baeldung.libraries.opencsv.pojos.CsvTransfer;
|
||||
import com.opencsv.CSVWriter;
|
||||
import com.opencsv.bean.*;
|
||||
import com.opencsv.bean.CsvToBean;
|
||||
import com.opencsv.bean.CsvToBeanBuilder;
|
||||
import com.opencsv.bean.StatefulBeanToCsv;
|
||||
import com.opencsv.bean.StatefulBeanToCsvBuilder;
|
||||
|
||||
import java.io.FileWriter;
|
||||
import java.io.Reader;
|
||||
import java.io.Writer;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class BeanExamples {
|
||||
|
||||
public static List<CsvBean> beanBuilderExample(Path path, Class clazz) {
|
||||
ColumnPositionMappingStrategy ms = new ColumnPositionMappingStrategy();
|
||||
return beanBuilderExample(path, clazz, ms);
|
||||
}
|
||||
|
||||
public static List<CsvBean> beanBuilderExample(Path path, Class clazz, MappingStrategy ms) {
|
||||
public static List<CsvBean> beanBuilderExample(Path path, Class<? extends CsvBean> clazz) throws Exception {
|
||||
CsvTransfer csvTransfer = new CsvTransfer();
|
||||
try {
|
||||
ms.setType(clazz);
|
||||
|
||||
Reader reader = Files.newBufferedReader(path);
|
||||
CsvToBean cb = new CsvToBeanBuilder(reader).withType(clazz)
|
||||
.withMappingStrategy(ms)
|
||||
try (Reader reader = Files.newBufferedReader(path)) {
|
||||
CsvToBean<CsvBean> cb = new CsvToBeanBuilder<CsvBean>(reader)
|
||||
.withType(clazz)
|
||||
.build();
|
||||
|
||||
csvTransfer.setCsvList(cb.parse());
|
||||
reader.close();
|
||||
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
}
|
||||
|
||||
return csvTransfer.getCsvList();
|
||||
}
|
||||
|
||||
public static String writeCsvFromBean(Path path) {
|
||||
try {
|
||||
Writer writer = new FileWriter(path.toString());
|
||||
public static String writeCsvFromBean(Path path) throws Exception {
|
||||
|
||||
StatefulBeanToCsv sbc = new StatefulBeanToCsvBuilder(writer).withSeparator(CSVWriter.DEFAULT_SEPARATOR)
|
||||
List<CsvBean> sampleData = Arrays.asList(
|
||||
new WriteExampleBean("Test1", "sample", "data"),
|
||||
new WriteExampleBean("Test2", "ipso", "facto")
|
||||
);
|
||||
|
||||
try (Writer writer = new FileWriter(path.toString())) {
|
||||
StatefulBeanToCsv<CsvBean> sbc = new StatefulBeanToCsvBuilder<CsvBean>(writer)
|
||||
.withQuotechar('\'')
|
||||
.build();
|
||||
|
||||
List<CsvBean> list = new ArrayList<>();
|
||||
list.add(new WriteExampleBean("Test1", "sfdsf", "fdfd"));
|
||||
list.add(new WriteExampleBean("Test2", "ipso", "facto"));
|
||||
|
||||
sbc.write(list);
|
||||
writer.close();
|
||||
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
sbc.write(sampleData);
|
||||
}
|
||||
|
||||
return Helpers.readFile(path);
|
||||
}
|
||||
}
|
|
@ -1,61 +1,58 @@
|
|||
package com.baeldung.libraries.opencsv.examples.sync;
|
||||
|
||||
import com.baeldung.libraries.opencsv.helpers.Helpers;
|
||||
import com.opencsv.CSVParser;
|
||||
import com.opencsv.CSVParserBuilder;
|
||||
import com.opencsv.CSVReader;
|
||||
import com.opencsv.CSVReaderBuilder;
|
||||
|
||||
import java.io.Reader;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class CsvReaderExamples {
|
||||
|
||||
public static List<String[]> readAll(Reader reader) {
|
||||
public static List<String[]> readAllLines(Path filePath) throws Exception {
|
||||
|
||||
CSVParser parser = new CSVParserBuilder()
|
||||
.withSeparator(',')
|
||||
.withIgnoreQuotations(true)
|
||||
.build();
|
||||
|
||||
CSVReader csvReader = new CSVReaderBuilder(reader)
|
||||
try (Reader reader = Files.newBufferedReader(filePath)) {
|
||||
CSVReaderBuilder csvReaderBuilder = new CSVReaderBuilder(reader)
|
||||
.withSkipLines(0)
|
||||
.withCSVParser(parser)
|
||||
.build();
|
||||
.withCSVParser(parser);
|
||||
|
||||
List<String[]> list = new ArrayList<>();
|
||||
try {
|
||||
list = csvReader.readAll();
|
||||
reader.close();
|
||||
csvReader.close();
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
try (CSVReader csvReader = csvReaderBuilder.build()) {
|
||||
return csvReader.readAll();
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<String[]> oneByOne(Reader reader) {
|
||||
}
|
||||
|
||||
public static List<String[]> readLineByLine(Path filePath) throws Exception {
|
||||
List<String[]> list = new ArrayList<>();
|
||||
try {
|
||||
|
||||
CSVParser parser = new CSVParserBuilder()
|
||||
.withSeparator(',')
|
||||
.withIgnoreQuotations(true)
|
||||
.build();
|
||||
|
||||
CSVReader csvReader = new CSVReaderBuilder(reader)
|
||||
.withSkipLines(0)
|
||||
.withCSVParser(parser)
|
||||
.build();
|
||||
try (Reader reader = Files.newBufferedReader(filePath)) {
|
||||
|
||||
CSVReaderBuilder csvReaderBuilder = new CSVReaderBuilder(reader)
|
||||
.withSkipLines(0)
|
||||
.withCSVParser(parser);
|
||||
|
||||
try (CSVReader csvReader = csvReaderBuilder.build()) {
|
||||
String[] line;
|
||||
while ((line = csvReader.readNext()) != null) {
|
||||
list.add(line);
|
||||
}
|
||||
reader.close();
|
||||
csvReader.close();
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
}
|
||||
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
|
|
@ -9,26 +9,21 @@ import java.util.List;
|
|||
|
||||
public class CsvWriterExamples {
|
||||
|
||||
public static String csvWriterOneByOne(List<String[]> stringArray, Path path) {
|
||||
try {
|
||||
CSVWriter writer = new CSVWriter(new FileWriter(path.toString()));
|
||||
for (String[] array : stringArray) {
|
||||
writer.writeNext(array);
|
||||
public static String writeLineByLine(List<String[]> lines, Path path) throws Exception {
|
||||
|
||||
try (CSVWriter writer = new CSVWriter(new FileWriter(path.toString()))) {
|
||||
for (String[] line : lines) {
|
||||
writer.writeNext(line);
|
||||
}
|
||||
writer.close();
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
}
|
||||
|
||||
return Helpers.readFile(path);
|
||||
}
|
||||
|
||||
public static String csvWriterAll(List<String[]> stringArray, Path path) {
|
||||
try {
|
||||
CSVWriter writer = new CSVWriter(new FileWriter(path.toString()));
|
||||
writer.writeAll(stringArray);
|
||||
writer.close();
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
public static String writeAllLines(List<String[]> lines, Path path) throws Exception {
|
||||
|
||||
try (CSVWriter writer = new CSVWriter(new FileWriter(path.toString()))) {
|
||||
writer.writeAll(lines);
|
||||
}
|
||||
return Helpers.readFile(path);
|
||||
}
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
package com.baeldung.libraries.opencsv.helpers;
|
||||
|
||||
import com.baeldung.libraries.opencsv.Constants;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Path;
|
||||
|
@ -13,9 +13,7 @@ import java.util.List;
|
|||
|
||||
public class Helpers {
|
||||
|
||||
/**
|
||||
* Write Files
|
||||
*/
|
||||
// Write Files
|
||||
|
||||
public static Path fileOutAllPath() throws URISyntaxException {
|
||||
URI uri = ClassLoader.getSystemResource(Constants.CSV_All).toURI();
|
||||
|
@ -32,9 +30,7 @@ public class Helpers {
|
|||
return Paths.get(uri);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read Files
|
||||
*/
|
||||
// Read Files
|
||||
|
||||
public static Path twoColumnCsvPath() throws URISyntaxException {
|
||||
URI uri = ClassLoader.getSystemResource(Constants.TWO_COLUMN_CSV).toURI();
|
||||
|
@ -51,33 +47,12 @@ public class Helpers {
|
|||
return Paths.get(uri);
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple File Reader
|
||||
*/
|
||||
|
||||
public static String readFile(Path path) {
|
||||
String response = "";
|
||||
try {
|
||||
FileReader fr = new FileReader(path.toString());
|
||||
BufferedReader br = new BufferedReader(fr);
|
||||
String strLine;
|
||||
StringBuffer sb = new StringBuffer();
|
||||
while ((strLine = br.readLine()) != null) {
|
||||
sb.append(strLine);
|
||||
}
|
||||
response = sb.toString();
|
||||
System.out.println(response);
|
||||
fr.close();
|
||||
br.close();
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
}
|
||||
return response;
|
||||
public static String readFile(Path path) throws IOException {
|
||||
return IOUtils.toString(path.toUri());
|
||||
}
|
||||
|
||||
/**
|
||||
* Dummy Data for Writing.
|
||||
*/
|
||||
|
||||
// Dummy Data for Writing
|
||||
|
||||
public static List<String[]> twoColumnCsvString() {
|
||||
List<String[]> list = new ArrayList<>();
|
||||
|
@ -94,15 +69,4 @@ public class Helpers {
|
|||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Message Helpers
|
||||
*/
|
||||
|
||||
public static void print(String msg) {
|
||||
System.out.println(msg);
|
||||
}
|
||||
|
||||
public static void err(Exception ex) {
|
||||
System.out.println(Constants.GENERIC_EXCEPTION + " " + ex);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
colA, ColB
|
||||
colA,colB
|
||||
A,B
|
||||
C,D
|
||||
G,G
|
||||
|
|
|
|
@ -1,66 +1,107 @@
|
|||
package com.baeldung.libraries.opencsv;
|
||||
|
||||
import com.baeldung.libraries.opencsv.helpers.Helpers;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import com.baeldung.libraries.opencsv.beans.CsvBean;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class OpenCsvIntegrationTest {
|
||||
|
||||
private Object testReadCsv(Object result) {
|
||||
assert (result != null);
|
||||
assert (result instanceof String);
|
||||
assert (!((String) result).isEmpty());
|
||||
System.out.println(result);
|
||||
return result;
|
||||
}
|
||||
private static final String NEW_LINE = System.lineSeparator();
|
||||
|
||||
private Object testWriteCsv(Object result) {
|
||||
assert (result instanceof String);
|
||||
assert (!((String) result).isEmpty());
|
||||
return result;
|
||||
}
|
||||
@Test
|
||||
public void givenSampleData_whenReadUsingPosition_thenContentsRead() throws Exception {
|
||||
List<CsvBean> values = Application.simpleSyncPositionBeanExample();
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
assertThat(values)
|
||||
.extracting(Object::toString)
|
||||
.containsExactly(
|
||||
"colA,colB",
|
||||
"A,B",
|
||||
"C,D",
|
||||
"G,G",
|
||||
"G,F"
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void positionExampleTest() {
|
||||
testReadCsv(Application.simpleSyncPositionBeanExample());
|
||||
public void givenSampleData_whenReadUsingNamedColumn_thenContentsRead() throws Exception {
|
||||
List<CsvBean> values = Application.namedSyncColumnBeanExample();
|
||||
|
||||
assertThat(values)
|
||||
.extracting(Object::toString)
|
||||
.containsExactly(
|
||||
"Joe,27",
|
||||
"Jane,32",
|
||||
"Bob,53"
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void namedColumnExampleTest() {
|
||||
testReadCsv(Application.namedSyncColumnBeanExample());
|
||||
public void givenSampleData_whenReadLineByLine_thenContentsRead() throws Exception {
|
||||
List<String[]> lineByLineContents = Application.readLineByLineSyncExample();
|
||||
|
||||
assertThat(lineByLineContents)
|
||||
.containsExactly(
|
||||
new String[] {"colA", "colB"},
|
||||
new String[] {"A", "B"},
|
||||
new String[] {"C", "D"},
|
||||
new String[] {"G", "G"},
|
||||
new String[] {"G", "F"}
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeCsvUsingBeanBuilderTest() {
|
||||
testWriteCsv(Application.writeSyncCsvFromBeanExample());
|
||||
public void givenSampleData_whenReadAllLines_thenContentsRead() throws Exception {
|
||||
|
||||
List<String[]> contents = Application.readAllLinesSyncExample();
|
||||
|
||||
assertThat(contents)
|
||||
.containsExactly(
|
||||
new String[] {"colA", "colB"},
|
||||
new String[] {"A", "B"},
|
||||
new String[] {"C", "D"},
|
||||
new String[] {"G", "G"},
|
||||
new String[] {"G", "F"}
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oneByOneExampleTest() {
|
||||
testReadCsv(Application.oneByOneSyncExample());
|
||||
public void givenSampleData_whenWriteCsvUsingBean_thenContentsWritten() throws Exception {
|
||||
String contents = Application.writeSyncCsvFromBeanExample();
|
||||
|
||||
assertThat(contents.split(NEW_LINE))
|
||||
.containsExactly(
|
||||
"'colA','colB','colC'",
|
||||
"'Test1','sample','data'",
|
||||
"'Test2','ipso','facto'"
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void readAllExampleTest() {
|
||||
testReadCsv(Application.readAllSyncExample());
|
||||
public void givenSampleData_whenWriteCsvLineByLine_thenContentsWritten() throws Exception {
|
||||
String contents = Application.writeLineByLineSyncExample();
|
||||
|
||||
assertThat(contents.split(NEW_LINE))
|
||||
.containsExactly(
|
||||
"\"ColA\",\"ColB\",\"ColC\",\"ColD\"",
|
||||
"\"A\",\"B\",\"A\",\"B\"",
|
||||
"\"BB\",\"AB\",\"AA\",\"B\""
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void csvWriterOneByOneTest() {
|
||||
testWriteCsv(Application.csvWriterSyncOneByOne());
|
||||
public void givenSampleData_whenWriteCsvAllLines_thenContentsWritten() throws Exception {
|
||||
String contents = Application.writeAllLinesSyncExample();
|
||||
|
||||
assertThat(contents.split(NEW_LINE))
|
||||
.containsExactly(
|
||||
"\"ColA\",\"ColB\",\"ColC\",\"ColD\"",
|
||||
"\"A\",\"B\",\"A\",\"B\"",
|
||||
"\"BB\",\"AB\",\"AA\",\"B\""
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void csvWriterAllTest() {
|
||||
testWriteCsv(Application.csvWriterSyncAll());
|
||||
}
|
||||
|
||||
@After
|
||||
public void close() {
|
||||
}
|
||||
}
|
|
@ -0,0 +1,80 @@
|
|||
package com.baeldung.mongo.find;
|
||||
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.FindIterable;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoCursor;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
import org.bson.Document;
|
||||
import org.bson.types.ObjectId;
|
||||
|
||||
import static com.mongodb.client.model.Filters.eq;
|
||||
|
||||
public class FindWithObjectId {
|
||||
|
||||
private static final String OBJECT_ID_FIELD = "_id";
|
||||
|
||||
private static MongoClient mongoClient;
|
||||
private static MongoDatabase database;
|
||||
private static MongoCollection<Document> collection;
|
||||
private static String collectionName;
|
||||
private static String databaseName;
|
||||
|
||||
public static void setUp() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient("localhost", 27017);
|
||||
|
||||
databaseName = "baeldung";
|
||||
collectionName = "employee";
|
||||
|
||||
database = mongoClient.getDatabase(databaseName);
|
||||
collection = database.getCollection(collectionName);
|
||||
}
|
||||
}
|
||||
|
||||
public static void retrieveAllDocumentsUsingFindWithObjectId() {
|
||||
Document document = collection.find()
|
||||
.first();
|
||||
System.out.println(document);
|
||||
|
||||
FindIterable<Document> documents = collection.find(eq(OBJECT_ID_FIELD, document.get(OBJECT_ID_FIELD)));
|
||||
|
||||
MongoCursor<Document> cursor = documents.iterator();
|
||||
while (cursor.hasNext()) {
|
||||
System.out.println(cursor.next());
|
||||
}
|
||||
}
|
||||
|
||||
public static void retrieveFirstDocumentWithObjectId() {
|
||||
Document document = collection.find()
|
||||
.first();
|
||||
System.out.println(document);
|
||||
|
||||
FindIterable<Document> documents = collection.find(eq(OBJECT_ID_FIELD, document.get(OBJECT_ID_FIELD)));
|
||||
Document queriedDocument = documents.first();
|
||||
|
||||
System.out.println(queriedDocument);
|
||||
}
|
||||
|
||||
public static void retrieveDocumentWithRandomObjectId() {
|
||||
FindIterable<Document> documents = collection.find(eq(OBJECT_ID_FIELD, new ObjectId()));
|
||||
Document queriedDocument = documents.first();
|
||||
|
||||
if (queriedDocument != null) {
|
||||
System.out.println(queriedDocument);
|
||||
} else {
|
||||
System.out.println("No documents found");
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String args[]) {
|
||||
|
||||
setUp();
|
||||
|
||||
retrieveAllDocumentsUsingFindWithObjectId();
|
||||
|
||||
retrieveFirstDocumentWithObjectId();
|
||||
|
||||
retrieveDocumentWithRandomObjectId();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,87 @@
|
|||
package com.baeldung.mongo.find;
|
||||
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.FindIterable;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoCursor;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
import org.bson.Document;
|
||||
import org.bson.types.ObjectId;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
import static com.mongodb.client.model.Filters.eq;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class FindWithObjectIdLiveTest {
|
||||
|
||||
private static final String OBJECT_ID_FIELD = "_id";
|
||||
|
||||
private static MongoClient mongoClient;
|
||||
private static MongoDatabase database;
|
||||
private static MongoCollection<Document> collection;
|
||||
private static final String DATASET_JSON = "/employee.json";
|
||||
|
||||
@BeforeClass
|
||||
public static void setUp() throws IOException {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient("localhost", 27017);
|
||||
|
||||
database = mongoClient.getDatabase("baeldung");
|
||||
collection = database.getCollection("employee");
|
||||
|
||||
collection.drop();
|
||||
|
||||
InputStream is = FindOperationLiveTest.class.getResourceAsStream(DATASET_JSON);
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
|
||||
reader.lines()
|
||||
.forEach(line -> collection.insertOne(Document.parse(line)));
|
||||
reader.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeCollection_whenFetchingDocumentsUsingObjectId_thenCheckingForDocuments() {
|
||||
Document employee = collection.find()
|
||||
.first();
|
||||
ObjectId objectId = (ObjectId) employee.get(OBJECT_ID_FIELD);
|
||||
|
||||
FindIterable<Document> documents = collection.find(eq(OBJECT_ID_FIELD, objectId));
|
||||
MongoCursor<Document> cursor = documents.iterator();
|
||||
|
||||
assertNotNull(cursor);
|
||||
assertTrue(cursor.hasNext());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeCollection_whenFetchingFirstDocumentUsingObjectId_thenCheckingForDocument() {
|
||||
Document employee = collection.find()
|
||||
.first();
|
||||
ObjectId objectId = (ObjectId) employee.get(OBJECT_ID_FIELD);
|
||||
|
||||
Document queriedEmployee = collection.find(eq(OBJECT_ID_FIELD, objectId))
|
||||
.first();
|
||||
|
||||
assertNotNull(queriedEmployee);
|
||||
assertEquals(employee.get(OBJECT_ID_FIELD), queriedEmployee.get(OBJECT_ID_FIELD));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeCollection_whenFetchingUsingRandomObjectId_thenCheckingForDocument() {
|
||||
Document employee = collection.find(eq(OBJECT_ID_FIELD, new ObjectId()))
|
||||
.first();
|
||||
|
||||
assertNull(employee);
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void cleanUp() {
|
||||
mongoClient.close();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
<?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">
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>persistence-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>java-mongodb-queries</artifactId>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.mongodb</groupId>
|
||||
<artifactId>mongodb-driver-sync</artifactId>
|
||||
<version>4.6.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>5.8.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>8</maven.compiler.source>
|
||||
<maven.compiler.target>8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,183 @@
|
|||
package com.baeldung.mongo.crud;
|
||||
|
||||
import com.baeldung.mongo.crud.model.Event;
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.BasicDBObjectBuilder;
|
||||
import com.mongodb.MongoException;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
import com.mongodb.client.model.UpdateOptions;
|
||||
import com.mongodb.client.model.Updates;
|
||||
import com.mongodb.client.result.InsertOneResult;
|
||||
import com.mongodb.client.result.DeleteResult;
|
||||
import com.mongodb.client.result.UpdateResult;
|
||||
import org.bson.BsonValue;
|
||||
import org.bson.Document;
|
||||
import org.bson.codecs.configuration.CodecProvider;
|
||||
import org.bson.codecs.configuration.CodecRegistry;
|
||||
import org.bson.codecs.pojo.PojoCodecProvider;
|
||||
import org.bson.conversions.Bson;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static com.mongodb.client.model.Filters.and;
|
||||
import static com.mongodb.client.model.Filters.eq;
|
||||
import static com.mongodb.MongoClientSettings.getDefaultCodecRegistry;
|
||||
import static com.mongodb.client.model.Filters.gte;
|
||||
import static com.mongodb.client.model.Filters.lt;
|
||||
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
|
||||
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
|
||||
|
||||
public class CrudClient {
|
||||
|
||||
private static String uri = "mongodb://localhost:27017";
|
||||
private static MongoClient mongoClient = MongoClients.create(uri);
|
||||
private static MongoDatabase db;
|
||||
private static MongoCollection<Event> collection;
|
||||
|
||||
public static OffsetDateTime offsetDateTime = OffsetDateTime.of(LocalDateTime.of(2022, 6, 4, 11, 0, 0),
|
||||
ZoneOffset.ofHours(2));
|
||||
|
||||
public static Event pianoLessons = new Event(
|
||||
"Piano lessons",
|
||||
"Foo Bvld",
|
||||
LocalDateTime.of(2022, 6, 4, 11, 0, 0));
|
||||
|
||||
public static Event soccerGame = new Event(
|
||||
"Soccer game",
|
||||
"Bar Avenue",
|
||||
LocalDateTime.of(2022, 6, 10, 17, 0, 0));
|
||||
|
||||
public static Event pianoLessonsTZ = new Event(
|
||||
"Piano lessons",
|
||||
"Baz Bvld",
|
||||
LocalDateTime.of(2022, 12, 31, 12, 0, 0),
|
||||
ZoneOffset.ofHours(2).toString());
|
||||
|
||||
public static LocalDateTime dateQuery = LocalDateTime.of(2022, 6, 10, 17, 0, 0);
|
||||
public static LocalDateTime dateQueryEventWithTZ = LocalDateTime.of(2022, 12, 31, 12, 0, 0);
|
||||
|
||||
public static LocalDateTime from = LocalDateTime.of(2022, 06, 04, 12, 0, 0);
|
||||
public static LocalDateTime to = LocalDateTime.of(2022, 06, 10, 17, 0, 0);
|
||||
|
||||
public static LocalDate updateManyFrom = LocalDate.of(2022, 1, 1);
|
||||
public static LocalDate updateManyTo = LocalDate.of(2023, 1, 1);
|
||||
|
||||
public static LocalDate deleteFrom = LocalDate.of(2022, 1, 1);
|
||||
public static LocalDate deleteTo = LocalDate.of(2023, 01, 01);
|
||||
|
||||
public static void setup() {
|
||||
CodecProvider codecProvider = PojoCodecProvider.builder().automatic(true).build();
|
||||
CodecRegistry codecRegistry = fromRegistries(getDefaultCodecRegistry(), fromProviders(codecProvider));
|
||||
|
||||
db = mongoClient.getDatabase("calendar").withCodecRegistry(codecRegistry);
|
||||
collection = db.getCollection("my_events", Event.class);
|
||||
}
|
||||
|
||||
public static void close() {
|
||||
mongoClient.close();
|
||||
}
|
||||
|
||||
public static BsonValue insertEventsWithDate(Event e) {
|
||||
try {
|
||||
InsertOneResult insertResult = collection.insertOne(e);
|
||||
return insertResult.getInsertedId();
|
||||
} catch (MongoException me) {
|
||||
System.err.println("Failed to insert with error: " + me);
|
||||
throw me;
|
||||
}
|
||||
}
|
||||
|
||||
public static Event readEventsByDate(LocalDateTime localDateTime) {
|
||||
try {
|
||||
Event event = collection
|
||||
.find(eq("dateTime", localDateTime))
|
||||
.first();
|
||||
return event;
|
||||
} catch (MongoException me) {
|
||||
System.err.println("Failed to read with error: " + me);
|
||||
throw me;
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Event> readEventsByDateRange(LocalDateTime from, LocalDateTime to) {
|
||||
BasicDBObject object = new BasicDBObject();
|
||||
object.put("dateTime", BasicDBObjectBuilder
|
||||
.start("$gte", from)
|
||||
.add("$lte", to)
|
||||
.get());
|
||||
try {
|
||||
List<Event> list = new ArrayList<Event>(collection.find(object).into(new ArrayList<Event>()));
|
||||
return list;
|
||||
} catch (MongoException me) {
|
||||
System.err.println("Failed to read with error: " + me);
|
||||
throw me;
|
||||
}
|
||||
}
|
||||
|
||||
public static LocalDateTime readEventsByDateWithTZ(LocalDateTime localDateTime) {
|
||||
try {
|
||||
Event event = collection
|
||||
.find(eq("dateTime", localDateTime))
|
||||
.first();
|
||||
OffsetDateTime offsetDateTime = OffsetDateTime.of(event.dateTime, ZoneOffset.of(pianoLessonsTZ.timeZoneOffset));
|
||||
ZonedDateTime zoned = offsetDateTime.atZoneSameInstant(ZoneId.of("America/Toronto"));
|
||||
return zoned.toLocalDateTime();
|
||||
} catch (MongoException me) {
|
||||
System.err.println("Failed to read with error: " + me);
|
||||
throw me;
|
||||
}
|
||||
}
|
||||
|
||||
public static long updateDateField() {
|
||||
Document document = new Document().append("title", "Piano lessons");
|
||||
Bson update = Updates.currentDate("updatedAt");
|
||||
UpdateOptions options = new UpdateOptions().upsert(false);
|
||||
try {
|
||||
UpdateResult result = collection.updateOne(document, update, options);
|
||||
return result.getModifiedCount();
|
||||
} catch (MongoException me) {
|
||||
System.err.println("Failed to update with error: " + me);
|
||||
throw me;
|
||||
}
|
||||
}
|
||||
|
||||
public static long updateManyEventsWithDateCriteria(LocalDate updateManyFrom, LocalDate updateManyTo) {
|
||||
Bson query = and(gte("dateTime", updateManyFrom), lt("dateTime", updateManyTo));
|
||||
Bson updates = Updates.currentDate("dateTime");
|
||||
try {
|
||||
UpdateResult result = collection.updateMany(query, updates);
|
||||
return result.getModifiedCount();
|
||||
} catch(MongoException me) {
|
||||
System.err.println("Failed to replace/update with error: " + me);
|
||||
throw me;
|
||||
}
|
||||
}
|
||||
|
||||
public static long deleteEventsByDate(LocalDate from, LocalDate to) {
|
||||
Bson query = and(gte("dateTime", from), lt("dateTime", to));
|
||||
try {
|
||||
DeleteResult result = collection.deleteMany(query);
|
||||
return result.getDeletedCount();
|
||||
} catch (MongoException me) {
|
||||
System.err.println("Failed to delete with error: " + me);
|
||||
throw me;
|
||||
}
|
||||
}
|
||||
|
||||
public static void dropDb() {
|
||||
db.drop();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.mongo.crud.model;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class Event {
|
||||
public String title;
|
||||
public String location;
|
||||
public LocalDateTime dateTime;
|
||||
public String timeZoneOffset;
|
||||
|
||||
public Event() {}
|
||||
public Event(String title, String location, LocalDateTime dateTime) {
|
||||
this.title = title;
|
||||
this.location = location;
|
||||
this.dateTime = dateTime;
|
||||
}
|
||||
|
||||
public Event(String title, String location, LocalDateTime dateTime, String timeZoneOffset) {
|
||||
this.title = title;
|
||||
this.location = location;
|
||||
this.dateTime = dateTime;
|
||||
this.timeZoneOffset = timeZoneOffset;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() { return "\nEvent: " + title + "\nWhere: " + location + "\nWhen: " + dateTime; }
|
||||
}
|
||||
|
|
@ -0,0 +1,95 @@
|
|||
package com.baeldung.mongo.crud;
|
||||
|
||||
import com.baeldung.mongo.crud.model.Event;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
public class CrudClientLiveTest {
|
||||
|
||||
@BeforeAll
|
||||
public static void setup() {
|
||||
CrudClient.setup();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
public void whenInsertingEventsWithDate_thenCheckForDocument() {
|
||||
Assertions.assertNotNull(CrudClient.insertEventsWithDate(CrudClient.pianoLessons));
|
||||
Assertions.assertNotNull(CrudClient.insertEventsWithDate(CrudClient.soccerGame));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
public void whenReadingEventsByDate_thenCheckForReturnedDocument() {
|
||||
Assertions.assertNotNull(CrudClient.readEventsByDate(CrudClient.dateQuery));
|
||||
Event event = CrudClient.readEventsByDate(CrudClient.dateQuery);
|
||||
Assertions.assertNotNull(event);
|
||||
Assertions.assertEquals("Soccer game", event.title);
|
||||
Assertions.assertEquals("Bar Avenue", event.location);
|
||||
Assertions.assertEquals(CrudClient.soccerGame.dateTime, event.dateTime);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
public void whenReadingEventsByDateRange_thenCheckForReturnedDocument() {
|
||||
List<Event> events = CrudClient.readEventsByDateRange(CrudClient.from, CrudClient.to);
|
||||
Assertions.assertNotNull(events);
|
||||
Assertions.assertEquals(1, events.size());
|
||||
Assertions.assertEquals("Soccer game", events.get(0).title);
|
||||
Assertions.assertEquals("Bar Avenue", events.get(0).location);
|
||||
Assertions.assertEquals(CrudClient.soccerGame.dateTime, events.get(0).dateTime);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
public void whenUpdatingEventsDateField_thenCheckUpdatedCount() {
|
||||
Assertions.assertEquals(1, CrudClient.updateDateField());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
public void whenUpdatingManyEvents_thenCheckUpdatedCount() {
|
||||
long updates = CrudClient.updateManyEventsWithDateCriteria(CrudClient.updateManyFrom, CrudClient.updateManyTo);
|
||||
Assertions.assertTrue(1 < updates);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
public void whenDeletingEventsWithDate_thenCheckDeletedCount() {
|
||||
Assertions.assertEquals(2, CrudClient.deleteEventsByDate(CrudClient.deleteFrom, CrudClient.deleteTo));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
public void whenInsertingEventWithDateAndTimeZone_thenCheckForDocument() {
|
||||
Assertions.assertNotNull(CrudClient.insertEventsWithDate(CrudClient.pianoLessonsTZ));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(9)
|
||||
public void whenReadingEventsWithDateAndTimeZone_thenCheckInsertedCount() {
|
||||
Assertions.assertNotEquals(CrudClient.pianoLessonsTZ.dateTime, CrudClient.readEventsByDateWithTZ(CrudClient.dateQueryEventWithTZ));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(10)
|
||||
public void whenDeletingEventsWithDateAndTimeZone_thenCheckDeletedCount() {
|
||||
Assertions.assertEquals(1, CrudClient.deleteEventsByDate(CrudClient.deleteFrom, CrudClient.deleteTo));
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
public static void close() throws IOException {
|
||||
CrudClient.dropDb();
|
||||
CrudClient.close();
|
||||
}
|
||||
|
||||
}
|
|
@ -45,6 +45,7 @@
|
|||
<module>java-mongodb</module> <!-- long running -->
|
||||
<module>java-mongodb-2</module> <!-- long running -->
|
||||
<module>java-mongodb-3</module> <!-- long running -->
|
||||
<module>java-mongodb-queries</module> <!-- long running -->
|
||||
<module>jnosql</module> <!-- long running -->
|
||||
<module>jooq</module>
|
||||
<module>jpa-hibernate-cascade-type</module>
|
||||
|
|
|
@ -11,6 +11,7 @@
|
|||
- [Spring Data MongoDB: Projections and Aggregations](http://www.baeldung.com/spring-data-mongodb-projections-aggregations)
|
||||
- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations)
|
||||
- [Spring Data MongoDB Transactions](https://www.baeldung.com/spring-data-mongodb-transactions)
|
||||
- [UUID as Entity ID in MongoDB](https://www.baeldung.com/java-mongodb-uuid)
|
||||
|
||||
## Spring Data MongoDB Live Testing
|
||||
|
||||
|
|
3
pom.xml
3
pom.xml
|
@ -1246,6 +1246,7 @@
|
|||
<module>core-java-modules/core-java-networking-3</module>
|
||||
<module>core-java-modules/core-java-strings</module>
|
||||
<module>core-java-modules/core-java-httpclient</module>
|
||||
<module>spring-core-6</module>
|
||||
<module>ddd-contexts</module>
|
||||
<module>docker-modules</module>
|
||||
<module>apache-httpclient-2</module>
|
||||
|
@ -1328,6 +1329,7 @@
|
|||
<module>testing-modules/testing-assertions</module>
|
||||
<module>persistence-modules/fauna</module>
|
||||
<module>lightrun</module>
|
||||
<module>spring-core-6</module>
|
||||
</modules>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
@ -1398,6 +1400,7 @@
|
|||
<lombok.version>1.18.20</lombok.version>
|
||||
<h2.version>1.4.200</h2.version>
|
||||
<guava.version>31.0.1-jre</guava.version>
|
||||
<maven-jar-plugin.version>3.2.2</maven-jar-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -44,6 +44,7 @@
|
|||
<module>spring-boot-groovy</module>
|
||||
<!-- <module>spring-boot-gradle</module> --> <!-- Not a maven project -->
|
||||
<module>spring-boot-jasypt</module>
|
||||
<module>spring-boot-jsp</module>
|
||||
<module>spring-boot-keycloak</module>
|
||||
<module>spring-boot-keycloak-2</module>
|
||||
<module>spring-boot-libraries</module>
|
||||
|
|
|
@ -9,9 +9,9 @@
|
|||
<packaging>war</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-web-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<groupId>com.baeldung.spring-boot-modules</groupId>
|
||||
<artifactId>spring-boot-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencyManagement>
|
|
@ -10,3 +10,4 @@ This module contains articles about Spring Cloud Gateway
|
|||
- [Spring Cloud Gateway WebFilter Factories](https://www.baeldung.com/spring-cloud-gateway-webfilter-factories)
|
||||
- [Using Spring Cloud Gateway with OAuth 2.0 Patterns](https://www.baeldung.com/spring-cloud-gateway-oauth2)
|
||||
- [URL Rewriting With Spring Cloud Gateway](https://www.baeldung.com/spring-cloud-gateway-url-rewriting)
|
||||
- [Processing the Response Body in Spring Cloud Gateway](https://www.baeldung.com/spring-cloud-gateway-response-body)
|
||||
|
|
|
@ -0,0 +1,76 @@
|
|||
<?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>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-core-6</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>spring-core-6</name>
|
||||
<url>http://www.baeldung.com</url>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.11</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<version>2.0.0.RELEASE</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-clean-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<version>3.0.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.0.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-install-plugin</artifactId>
|
||||
<version>2.5.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-deploy-plugin</artifactId>
|
||||
<version>2.8.2</version>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<artifactId>maven-site-plugin</artifactId>
|
||||
<version>3.7.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-project-info-reports-plugin</artifactId>
|
||||
<version>3.0.0</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.multibeaninstantiation.solution1;
|
||||
|
||||
public class Person {
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
public Person(String firstName, String secondName) {
|
||||
super();
|
||||
this.firstName = firstName;
|
||||
this.lastName = secondName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Person [firstName=" + firstName + ", secondName=" + lastName + "]";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.multibeaninstantiation.solution1;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class PersonConfig {
|
||||
@Bean
|
||||
public Person personOne() {
|
||||
return new Person("Harold", "Finch");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Person personTwo() {
|
||||
return new Person("John", "Reese");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.multibeaninstantiation.solution1;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class SpringApp1 {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringApp1.class, args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.multibeaninstantiation.solution2;
|
||||
|
||||
public class Person {
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
public Person(String firstName, String secondName) {
|
||||
super();
|
||||
this.firstName = firstName;
|
||||
this.lastName = secondName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Person [firstName=" + firstName + ", secondName=" + lastName + "]";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.multibeaninstantiation.solution2;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan("com.baeldung.multibeaninstantiation.solution2")
|
||||
public class PersonConfig {
|
||||
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.multibeaninstantiation.solution2;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.baeldung.multibeaninstantiation.solution2.Person;
|
||||
|
||||
@Component
|
||||
public class PersonOne extends Person {
|
||||
|
||||
public PersonOne() {
|
||||
super("Harold", "Finch");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.multibeaninstantiation.solution2;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.baeldung.multibeaninstantiation.solution2.Person;
|
||||
|
||||
@Component
|
||||
public class PersonTwo extends Person {
|
||||
|
||||
public PersonTwo() {
|
||||
super("John", "Reese");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.multibeaninstantiation.solution2;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class SpringApp2 {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringApp2.class, args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.multibeaninstantiation.solution3;
|
||||
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
public class Human implements InitializingBean {
|
||||
|
||||
private Person personOne;
|
||||
|
||||
private Person personTwo;
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
Assert.notNull(personOne, "Harold is alive!");
|
||||
Assert.notNull(personTwo, "John is alive!");
|
||||
}
|
||||
|
||||
/* Setter injection */
|
||||
@Autowired
|
||||
public void setPersonOne(Person personOne) {
|
||||
this.personOne = personOne;
|
||||
this.personOne.setFirstName("Harold");
|
||||
this.personOne.setSecondName("Finch");
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public void setPersonTwo(Person personTwo) {
|
||||
this.personTwo = personTwo;
|
||||
this.personTwo.setFirstName("John");
|
||||
this.personTwo.setSecondName("Reese");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.multibeaninstantiation.solution3;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface MultiBeanFactory<T> {
|
||||
List<T> getObject(String name) throws Exception;
|
||||
|
||||
Class<?> getObjectType();
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
package com.baeldung.multibeaninstantiation.solution3;
|
||||
|
||||
import org.springframework.beans.factory.FactoryBean;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
|
||||
@Qualifier(value = "personOne, personTwo")
|
||||
public class Person implements FactoryBean<Object> {
|
||||
private String firstName;
|
||||
private String secondName;
|
||||
|
||||
public Person() {
|
||||
// initialization code (optional)
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<Person> getObjectType() {
|
||||
return Person.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getObject() throws Exception {
|
||||
return new Person();
|
||||
}
|
||||
|
||||
public boolean isSingleton() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getSecondName() {
|
||||
return secondName;
|
||||
}
|
||||
|
||||
public void setSecondName(String secondName) {
|
||||
this.secondName = secondName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Person [firstName=" + firstName + ", secondName=" + secondName + "]";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.multibeaninstantiation.solution3;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class PersonConfig {
|
||||
@Bean
|
||||
public PersonFactoryPostProcessor PersonFactoryPostProcessor() {
|
||||
return new PersonFactoryPostProcessor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Person person() {
|
||||
return new Person();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Human human() {
|
||||
return new Human();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.multibeaninstantiation.solution3;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
|
||||
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
|
||||
|
||||
public class PersonFactoryPostProcessor implements BeanFactoryPostProcessor {
|
||||
|
||||
@Override
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
|
||||
Map<String, Object> map = beanFactory.getBeansWithAnnotation(Qualifier.class);
|
||||
for (Map.Entry<String, Object> entry : map.entrySet()) {
|
||||
createInstances(beanFactory, entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
private void createInstances(ConfigurableListableBeanFactory beanFactory, String beanName, Object bean) {
|
||||
Qualifier qualifier = bean.getClass()
|
||||
.getAnnotation(Qualifier.class);
|
||||
for (String name : extractNames(qualifier)) {
|
||||
Object newBean = beanFactory.getBean(beanName);
|
||||
beanFactory.registerSingleton(name.trim(), newBean);
|
||||
}
|
||||
}
|
||||
|
||||
private String[] extractNames(Qualifier qualifier) {
|
||||
return qualifier.value()
|
||||
.split(",");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.multibeaninstantiation.solution3;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class SpringApp3 {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringApp3.class, args);
|
||||
}
|
||||
}
|
|
@ -47,7 +47,6 @@
|
|||
<module>spring-thymeleaf-3</module>
|
||||
<module>spring-thymeleaf-4</module>
|
||||
<module>spring-thymeleaf-5</module>
|
||||
<module>spring-boot-jsp</module>
|
||||
<module>spring-web-url</module>
|
||||
</modules>
|
||||
|
||||
|
|
Loading…
Reference in New Issue