Merge pull request #73 from eugenp/master

update
This commit is contained in:
Maiklins 2020-09-26 22:33:31 +02:00 committed by GitHub
commit ea391ff6dd
262 changed files with 5951 additions and 884 deletions

View File

@ -5,3 +5,4 @@ This module contains articles about AWS Lambda
### Relevant Articles:
- [Using AWS Lambda with API Gateway](https://www.baeldung.com/aws-lambda-api-gateway)
- [Introduction to AWS Serverless Application Model](https://www.baeldung.com/aws-serverless)
- [How to Implement Hibernate in an AWS Lambda Function in Java](https://www.baeldung.com/java-aws-lambda-hibernate)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [How to Remove a Prefix From Strings in Groovy](https://www.baeldung.com/groovy-remove-string-prefix)

122
core-groovy-strings/pom.xml Normal file
View File

@ -0,0 +1,122 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-groovy-strings</artifactId>
<version>1.0-SNAPSHOT</version>
<name>core-groovy-strings</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>${groovy.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>${groovy-all.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-dateutil</artifactId>
<version>${groovy.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-sql</artifactId>
<version>${groovy-sql.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>${spock-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>${gmavenplus-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>addSources</goal>
<goal>addTestSources</goal>
<goal>compile</goal>
<goal>compileTests</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven-failsafe-plugin.version}</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>junit5</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<includes>
<include>**/*Test5.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>central</id>
<url>https://jcenter.bintray.com</url>
</repository>
</repositories>
<properties>
<junit.platform.version>1.0.0</junit.platform.version>
<groovy.version>2.5.6</groovy.version>
<groovy-all.version>2.5.6</groovy-all.version>
<groovy-sql.version>2.5.6</groovy-sql.version>
<hsqldb.version>2.4.0</hsqldb.version>
<spock-core.version>1.1-groovy-2.4</spock-core.version>
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,70 @@
package com.baeldung.removeprefix
import org.junit.Assert
import org.junit.Test
class RemovePrefixTest {
@Test
public void whenCasePrefixIsRemoved_thenReturnTrue() {
def trimPrefix = {
it.startsWith('Groovy-') ? it.minus('Groovy-') : it
}
def actual = trimPrefix("Groovy-Tutorials at Baeldung")
def expected = "Tutorials at Baeldung"
Assert.assertEquals(expected, actual)
}
@Test
public void whenPrefixIsRemoved_thenReturnTrue() {
String prefix = "groovy-"
String trimPrefix = "Groovy-Tutorials at Baeldung"
def actual;
if(trimPrefix.startsWithIgnoreCase(prefix)) {
actual = trimPrefix.substring(prefix.length())
}
def expected = "Tutorials at Baeldung"
Assert.assertEquals(expected, actual)
}
@Test
public void whenPrefixIsRemovedUsingRegex_thenReturnTrue() {
def regex = ~"^([Gg])roovy-"
String trimPrefix = "Groovy-Tutorials at Baeldung"
String actual = trimPrefix - regex
def expected = "Tutorials at Baeldung"
Assert.assertEquals(expected, actual)
}
@Test
public void whenPrefixIsRemovedUsingReplaceFirst_thenReturnTrue() {
def regex = ~"^groovy"
String trimPrefix = "groovyTutorials at Baeldung's groovy page"
String actual = trimPrefix.replaceFirst(regex, "")
def expected = "Tutorials at Baeldung's groovy page"
Assert.assertEquals(expected, actual)
}
@Test
public void whenPrefixIsRemovedUsingReplaceAll_thenReturnTrue() {
String trimPrefix = "groovyTutorials at Baeldung groovy"
String actual = trimPrefix.replaceAll(/^groovy/, "")
def expected = "Tutorials at Baeldung groovy"
Assert.assertEquals(expected, actual)
}
}

View File

@ -7,7 +7,7 @@ import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
public class AppUnitTest
extends TestCase
{
/**
@ -15,7 +15,7 @@ public class AppTest
*
* @param testName name of the test case
*/
public AppTest( String testName )
public AppUnitTest(String testName )
{
super( testName );
}
@ -25,7 +25,7 @@ public class AppTest
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
return new TestSuite( AppUnitTest.class );
}
/**

View File

@ -5,7 +5,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;
public class StringAPITest {
public class StringAPIUnitTest {
@Test
public void whenPositiveArgument_thenReturnIndentedString() {

View File

@ -7,7 +7,7 @@ import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class PersonTest {
public class PersonUnitTest {
@Test
public void givenSameNameAndAddress_whenEquals_thenPersonsEqual() {

View File

@ -44,6 +44,16 @@
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
</dependencies>
<build>
@ -77,6 +87,7 @@
<maven.compiler.target>1.9</maven.compiler.target>
<guava.version>25.1-jre</guava.version>
<commons-collections4.version>4.1</commons-collections4.version>
<commons-collections3.version>3.2.2</commons-collections3.version>
</properties>
</project>

View File

@ -17,7 +17,7 @@ import org.junit.Test;
/**
* Test case for the {@link MethodHandles} API
*/
public class MethodHandlesTest {
public class MethodHandlesUnitTest {
@Test
public void givenConcatMethodHandle_whenInvoked_thenCorrectlyConcatenated() throws Throwable {

View File

@ -6,3 +6,4 @@ This module contains complete guides about arrays in Java
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
- [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)

View File

@ -0,0 +1,86 @@
package com.baeldung.collections.removeallperformance;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.RandomStringUtils;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import com.baeldung.collections.containsperformance.Employee;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5)
public class HashSetBenchmark {
@State(Scope.Thread)
public static class MyState {
private Set<Employee> employeeSet1 = new HashSet<>();
private List<Employee> employeeList1 = new ArrayList<>();
private Set<Employee> employeeSet2 = new HashSet<>();
private List<Employee> employeeList2 = new ArrayList<>();
private long set1Size = 60000;
private long list1Size = 50000;
private long set2Size = 50000;
private long list2Size = 60000;
@Setup(Level.Trial)
public void setUp() {
for (long i = 0; i < set1Size; i++) {
employeeSet1.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
for (long i = 0; i < list1Size; i++) {
employeeList1.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
for (long i = 0; i < set2Size; i++) {
employeeSet2.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
for (long i = 0; i < list2Size; i++) {
employeeList2.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
}
}
@Benchmark
public boolean given_SizeOfHashsetGreaterThanSizeOfCollection_When_RemoveAllFromHashSet_Then_GoodPerformance(MyState state) {
return state.employeeSet1.removeAll(state.employeeList1);
}
@Benchmark
public boolean given_SizeOfHashsetSmallerThanSizeOfCollection_When_RemoveAllFromHashSet_Then_BadPerformance(MyState state) {
return state.employeeSet2.removeAll(state.employeeList2);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder().include(HashSetBenchmark.class.getSimpleName())
.threads(1)
.forks(1)
.shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server")
.build();
new Runner(options).run();
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.collections.hashset;
import static org.junit.jupiter.api.Assertions.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
class HashSetUnitTest {
@Test
void whenRemoveAllFromHashset_thenRemovesAllElementsFromHashsetThatArePresentInCollection() {
Set<Integer> set = new HashSet<>();
Collection<Integer> collection = new ArrayList<>();
set.add(1);
set.add(2);
set.add(3);
set.add(4);
collection.add(1);
collection.add(3);
set.removeAll(collection);
assertEquals(2, set.size());
Integer[] actualElements = new Integer[set.size()];
Integer[] expectedElements = new Integer[] { 2, 4 };
assertArrayEquals(expectedElements, set.toArray(actualElements));
}
}

View File

@ -15,21 +15,24 @@ import org.junit.Test;
public class MapFirstPairUnitTest {
private Map.Entry<Integer, String> getFirstPairUsingIterator(Map<Integer, String> map) {
if (map == null || map.size() == 0)
if (map == null || map.size() == 0) {
return null;
}
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet()
.iterator();
if (iterator.hasNext())
if (iterator.hasNext()) {
return iterator.next();
}
return null;
}
private Map.Entry<Integer, String> getFirstPairUsingStream(Map<Integer, String> map) {
if (map == null || map.size() == 0)
if (map == null || map.size() == 0) {
return null;
}
Set<Map.Entry<Integer, String>> entrySet = map.entrySet();

View File

@ -1,6 +1,8 @@
package com.baeldung.date;
import static org.junit.Assert.assertEquals;
import org.joda.time.Days;
import org.joda.time.Minutes;
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
@ -16,7 +18,7 @@ import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import static org.junit.Assert.*;
public class DateDiffUnitTest {
@ -29,18 +31,39 @@ public class DateDiffUnitTest {
long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime());
long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
assertEquals(diff, 6);
assertEquals(6, diff);
}
@Test
public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() {
LocalDate now = LocalDate.now();
LocalDate sixDaysBehind = now.minusDays(6);
public void givenTwoDatesInJava8_whenUsingPeriodGetDays_thenWorks() {
LocalDate aDate = LocalDate.of(2020, 9, 11);
LocalDate sixDaysBehind = aDate.minusDays(6);
Period period = Period.between(now, sixDaysBehind);
Period period = Period.between(aDate, sixDaysBehind);
int diff = Math.abs(period.getDays());
assertEquals(diff, 6);
assertEquals(6, diff);
}
@Test
public void givenTwoDatesInJava8_whenUsingPeriodGetDays_thenDoesNotWork() {
LocalDate aDate = LocalDate.of(2020, 9, 11);
LocalDate sixtyDaysBehind = aDate.minusDays(60);
Period period = Period.between(aDate, sixtyDaysBehind);
int diff = Math.abs(period.getDays());
//not equals
assertNotEquals(60, diff);
}
@Test
public void givenTwoDatesInJava8_whenUsingPeriod_thenWeGet0Year1Month29Days() {
LocalDate aDate = LocalDate.of(2020, 9, 11);
LocalDate sixtyDaysBehind = aDate.minusDays(60);
Period period = Period.between(aDate, sixtyDaysBehind);
int years = Math.abs(period.getYears());
int months = Math.abs(period.getMonths());
int days = Math.abs(period.getDays());
assertArrayEquals(new int[] { 0, 1, 29 }, new int[] { years, months, days });
}
@Test
@ -51,7 +74,7 @@ public class DateDiffUnitTest {
Duration duration = Duration.between(now, sixMinutesBehind);
long diff = Math.abs(duration.toMinutes());
assertEquals(diff, 6);
assertEquals(6, diff);
}
@Test
@ -61,7 +84,7 @@ public class DateDiffUnitTest {
long diff = ChronoUnit.SECONDS.between(now, tenSecondsLater);
assertEquals(diff, 10);
assertEquals(10, diff);
}
@Test
@ -69,9 +92,9 @@ public class DateDiffUnitTest {
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime now = ldt.atZone(ZoneId.of("America/Montreal"));
ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore"))
.minusDays(6);
.minusDays(6);
long diff = ChronoUnit.DAYS.between(sixDaysBehind, now);
assertEquals(diff, 6);
assertEquals(6, diff);
}
@Test
@ -81,7 +104,7 @@ public class DateDiffUnitTest {
long diff = now.until(tenSecondsLater, ChronoUnit.SECONDS);
assertEquals(diff, 10);
assertEquals(10, diff);
}
@Test
@ -89,10 +112,9 @@ public class DateDiffUnitTest {
org.joda.time.LocalDate now = org.joda.time.LocalDate.now();
org.joda.time.LocalDate sixDaysBehind = now.minusDays(6);
org.joda.time.Period period = new org.joda.time.Period(now, sixDaysBehind);
long diff = Math.abs(period.getDays());
long diff = Math.abs(Days.daysBetween(now, sixDaysBehind).getDays());
assertEquals(diff, 6);
assertEquals(6, diff);
}
@Test
@ -100,8 +122,9 @@ public class DateDiffUnitTest {
org.joda.time.LocalDateTime now = org.joda.time.LocalDateTime.now();
org.joda.time.LocalDateTime sixMinutesBehind = now.minusMinutes(6);
org.joda.time.Period period = new org.joda.time.Period(now, sixMinutesBehind);
long diff = Math.abs(period.getDays());
long diff = Math.abs(Minutes.minutesBetween(now, sixMinutesBehind).getMinutes());
assertEquals(6, diff);
}
@Test
@ -111,6 +134,6 @@ public class DateDiffUnitTest {
long diff = Math.abs(now.numDaysFrom(sixDaysBehind));
assertEquals(diff, 6);
assertEquals(6, diff);
}
}
}

View File

@ -6,7 +6,7 @@ import org.junit.jupiter.api.Test;
import java.sql.Timestamp;
import java.time.format.DateTimeFormatter;
public class TimestampToStringConverterTest {
public class TimestampToStringConverterUnitTest {
@Test
public void givenDatePattern_whenFormatting_thenResultingStringIsCorrect() {

View File

@ -1,3 +1,5 @@
### Relevant Articles:
- [NoSuchMethodError in Java](https://www.baeldung.com/java-nosuchmethod-error)
- [IllegalArgumentException or NullPointerException for a Null Parameter?](https://www.baeldung.com/java-illegalargumentexception-or-nullpointerexception)
- [IllegalMonitorStateException in Java](https://www.baeldung.com/java-illegalmonitorstateexception)

View File

@ -9,4 +9,6 @@ This module contains articles about core Java input and output (IO)
- [Check If a File or Directory Exists in Java](https://www.baeldung.com/java-file-directory-exists)
- [Copy a Directory in Java](https://www.baeldung.com/java-copy-directory)
- [Java Files Open Options](https://www.baeldung.com/java-file-options)
- [Creating Temporary Directories in Java](https://www.baeldung.com/java-temp-directories)
- [Reading a Line at a Given Line Number From a File in Java](https://www.baeldung.com/java-read-line-at-number)
- [[<-- Prev]](/core-java-modules/core-java-io-2)

View File

@ -4,6 +4,7 @@ import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
@ -20,8 +21,8 @@ public class DirectoryEmptinessUnitTest {
}
@Test
public void givenPath_whenNotDirectory_thenReturnsFalse() throws IOException {
Path aFile = Paths.get(getClass().getResource("/notDir.txt").getPath());
public void givenPath_whenNotDirectory_thenReturnsFalse() throws IOException, URISyntaxException {
Path aFile = Paths.get(getClass().getResource("/notDir.txt").toURI());
assertThat(isEmpty(aFile)).isFalse();
}

View File

@ -4,10 +4,7 @@ import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.*;
import java.util.concurrent.ThreadLocalRandom;
import static org.junit.Assert.assertFalse;
@ -47,8 +44,18 @@ public class ExistenceUnitTest {
public void givenSymbolicLink_whenTargetDoesNotExists_thenFollowOrNotBasedOnTheOptions() throws IOException {
Path target = Files.createTempFile("baeldung", "target");
Path symbol = Paths.get("test-link-" + ThreadLocalRandom.current().nextInt());
Path symbolicLink = null;
try {
symbolicLink = Files.createSymbolicLink(symbol, target);
} catch (FileSystemException ex) {
System.out.println("Your OS security policy prevents the current user from creating symbolic links.\n" +
"Most probably you're running Windows with UAC.\n" +
"If this is the case, please see - https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/create-symbolic-links\n" +
"You must change your security settings to run this test under Windows.");
return;
}
Path symbolicLink = Files.createSymbolicLink(symbol, target);
assertTrue(Files.exists(symbolicLink));
assertTrue(Files.isSymbolicLink(symbolicLink));
assertFalse(Files.isSymbolicLink(target));

View File

@ -4,6 +4,7 @@ import org.apache.commons.io.FileUtils;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@ -66,10 +67,16 @@ public class TemporaryDirectoriesUnitTest {
@Test
public void givenTempDirWithPrefixWithFileAttrs_whenCreatePlainJava_thenAttributesAreSet() throws IOException {
final FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("r--------"));
boolean isPosix = FileSystems.getDefault().supportedFileAttributeViews().contains("posix");
final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix", attrs);
assertThat(tmpdir.toFile().getPath()).startsWith("target");
assertThat(tmpdir.toFile().canWrite()).isFalse();
if(!isPosix){
System.out.println("You must be under a Posix Compliant Filesystem to run this test.");
} else {
final FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("r--------"));
final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix", attrs);
assertThat(tmpdir.toFile().getPath()).startsWith("target");
assertThat(tmpdir.toFile().canWrite()).isFalse();
}
}
}

View File

@ -17,7 +17,7 @@
<dependencies>
<dependency>
<groupId>com.baeldung.servicemodule</groupId>
<artifactId>servicemodule</artifactId>
<artifactId>servicemodule1</artifactId>
<version>${servicemodule.version}</version>
</dependency>
</dependencies>

View File

@ -4,7 +4,8 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>servicemodule</artifactId>
<groupId>com.baeldung.servicemodule</groupId>
<artifactId>servicemodule1</artifactId>
<packaging>jar</packaging>
<parent>

View File

@ -17,7 +17,7 @@
<dependencies>
<dependency>
<groupId>com.baeldung.servicemodule</groupId>
<artifactId>servicemodule</artifactId>
<artifactId>servicemodule2</artifactId>
<version>${servicemodule.version}</version>
</dependency>
</dependencies>

View File

@ -4,7 +4,8 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>servicemodule</artifactId>
<groupId>com.baeldung.servicemodule</groupId>
<artifactId>servicemodule2</artifactId>
<version>1.0</version>
<parent>

View File

@ -5,4 +5,5 @@ This module contains articles about core features in the Java language
- [Class.isInstance vs Class.isAssignableFrom](https://www.baeldung.com/java-isinstance-isassignablefrom)
- [Converting a Java String Into a Boolean](https://www.baeldung.com/java-string-to-boolean)
- [When are Static Variables Initialized in Java?](https://www.baeldung.com/java-static-variables-initialization)
- [Checking if a Class Exists in Java](https://www.baeldung.com/java-check-class-exists)
- [[<-- Prev]](/core-java-modules/core-java-lang-2)

View File

@ -13,4 +13,5 @@
- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude)
- [Debugging with Eclipse](https://www.baeldung.com/eclipse-debugging)
- [Matrix Multiplication in Java](https://www.baeldung.com/java-matrix-multiplication)
- [Largest Power of 2 That Is Less Than the Given Number](https://www.baeldung.com/java-largest-power-of-2-less-than-number)
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math)

View File

@ -9,3 +9,4 @@ This module contains articles about methods in Java
- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts)
- [Guide to hashCode() in Java](https://www.baeldung.com/java-hashcode)
- [The Covariant Return Type in Java](https://www.baeldung.com/java-covariant-return-type)
- [Does a Methods Signature Include the Return Type in Java?](https://www.baeldung.com/java-method-signature-return-type)

View File

@ -0,0 +1,72 @@
package com.baeldung.signature;
import java.io.Serializable;
public class OverloadingErrors<T extends Serializable> {
public void print() {
System.out.println("Signature is: print()");
}
/*
// Uncommenting this method will lead to a compilation error: java: method print() is already defined in class
// The method signature is independent from return type
public int print() {
System.out.println("Signature is: print()");
return 0;
}
*/
/*
// Uncommenting this method will lead to a compilation error: java: method print() is already defined in class
// The method signature is independent from modifiers
private final void print() {
System.out.println("Signature is: print()");
}
*/
/*
// Uncommenting this method will lead to a compilation error: java: method print() is already defined in class
// The method signature is independent from thrown exception declaration
public void print() throws IllegalStateException {
System.out.println("Signature is: print()");
throw new IllegalStateException();
}
*/
public void print(int parameter) {
System.out.println("Signature is: print(int)");
}
/*
// Uncommenting this method will lead to a compilation error: java: method print(int) is already defined in class
// The method signature is independent from parameter names
public void print(int anotherParameter) {
System.out.println("Signature is: print(int)");
}
*/
public void printElement(T t) {
System.out.println("Signature is: printElement(T)");
}
/*
// Uncommenting this method will lead to a compilation error: java: name clash: printElement(java.io.Serializable) and printElement(T) have the same erasure
// Even though the signatures appear different, the compiler cannot statically bind the correct method after type erasure
public void printElement(Serializable o) {
System.out.println("Signature is: printElement(Serializable)");
}
*/
public void print(Object... parameter) {
System.out.println("Signature is: print(Object...)");
}
/*
// Uncommenting this method will lead to a compilation error: java cannot declare both sum(Object...) and sum(Object[])
// Even though the signatures appear different, after compilation they both resolve to sum(Object[])
public void print(Object[] parameter) {
System.out.println("Signature is: print(Object[])");
}
*/
}

View File

@ -0,0 +1,46 @@
package com.baeldung.signature;
public class StaticBinding {
public Number sum(Integer term1, Integer term2) {
System.out.println("Adding integers");
return term1 + term2;
}
public Number sum(Number term1, Number term2) {
System.out.println("Adding numbers");
return term1.doubleValue() + term2.doubleValue();
}
public Number sum(Object term1, Object term2) {
System.out.println("Adding objects");
return term1.hashCode() + term2.hashCode();
}
public Number sum(Object term1, Object... term2) {
System.out.println("Adding variable arguments: " + term2.length);
int result = term1.hashCode();
for (Object o : term2) {
result += o.hashCode();
}
return result;
}
public static void main(String[] args) {
StaticBinding obj = new StaticBinding();
obj.sum(2, 3); // "Adding integers" due to auto-boxing from int to Integer
obj.sum(Integer.valueOf(2), Integer.valueOf(3)); // "Adding integers" due to exact parameter types
obj.sum(2, 0x1); // "Adding integers" due to type promotion from byte to int
obj.sum((Number) 2, (Number) 3); // "Adding numbers" due to explicit cast to Number
obj.sum(2.0d, 3.0d); // "Adding numbers" due to auto-boxing from double to Double
obj.sum(Float.valueOf(2), Float.valueOf(3)); // "Adding numbers" due to polimorphism
obj.sum((Object) 2, (Object) 3); // "Adding objects" due to explicit cast to Object
obj.sum(2, "John"); // "Adding objects" due to polimorphism
obj.sum(new Object(), new Object(), new Object()); // "Adding variable arguments 2"
obj.sum(new Object(), new Object[]{new Object()}); // "Adding variable arguments 1"
}
}

View File

@ -13,4 +13,5 @@ This module contains articles about networking in Java
- [Download a File from an URL in Java](https://www.baeldung.com/java-download-file)
- [Handling java.net.ConnectException](https://www.baeldung.com/java-net-connectexception)
- [Getting MAC addresses in Java](https://www.baeldung.com/java-mac-address)
- [Sending Emails with Attachments in Java](https://www.baeldung.com/java-send-emails-attachments)
- [[<-- Prev]](/core-java-modules/core-java-networking)

View File

@ -4,7 +4,7 @@ import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class CurrentDirectoryFetcherTest {
public class CurrentDirectoryFetcherUnitTest {
private static final String CURRENT_DIR = "core-java-os";

View File

@ -2,3 +2,4 @@
- [Reading the Value of private Fields from a Different Class in Java](https://www.baeldung.com/java-reflection-read-private-field-value)
- [Set Field Value With Reflection](https://www.baeldung.com/java-set-private-field-value)
- [Checking If a Method is Static Using Reflection in Java](https://www.baeldung.com/java-check-method-is-static)

View File

@ -0,0 +1,19 @@
package com.baeldung.reflection.check.staticmethods;
import java.time.LocalDate;
import java.time.LocalTime;
public class StaticUtility {
public static String getAuthorName() {
return "Umang Budhwar";
}
public static LocalDate getLocalDate() {
return LocalDate.now();
}
public static LocalTime getLocalTime() {
return LocalTime.now();
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.reflection.check.staticmethods;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class StaticUtilityUnitTest {
@Test
void whenCheckStaticMethod_ThenSuccess() throws Exception {
Method method = StaticUtility.class.getMethod("getAuthorName", null);
Assertions.assertTrue(Modifier.isStatic(method.getModifiers()));
}
@Test
void whenCheckAllStaticMethods_thenSuccess() {
List<Method> methodList = Arrays.asList(StaticUtility.class.getMethods())
.stream()
.filter(method -> Modifier.isStatic(method.getModifiers()))
.collect(Collectors.toList());
Assertions.assertEquals(3, methodList.size());
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.cipher;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.Provider;
import java.security.Security;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class AvailableCiphersUnitTest {
private final Logger logger = LoggerFactory.getLogger(AvailableCiphersUnitTest.class);
@Test
public void whenGetServices_thenGetAllCipherAlgorithms() {
for (Provider provider : Security.getProviders()) {
for (Provider.Service service : provider.getServices()) {
logger.info(service.getAlgorithm());
}
}
}
@Test
public void whenGetServicesWithFilter_thenGetAllCompatibleCipherAlgorithms() {
List<String> algorithms = Arrays.stream(Security.getProviders())
.flatMap(provider -> provider.getServices().stream())
.filter(service -> "Cipher".equals(service.getType()))
.map(Provider.Service::getAlgorithm)
.collect(Collectors.toList());
algorithms.forEach(logger::info);
}
}

View File

@ -20,6 +20,10 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>

View File

@ -20,6 +20,10 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>

View File

@ -38,6 +38,10 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>

View File

@ -33,6 +33,10 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>

View File

@ -18,20 +18,9 @@
<modules>
<module>core-java</module>
<!-- <module>core-java-10</module> --> <!-- We haven't upgraded to java 10. Fixing in BAEL-10841 -->
<!-- <module>core-java-11</module> --> <!-- We haven't upgraded to java 11. Fixing in BAEL-10841 -->
<!-- <module>core-java-12</module> --> <!-- We haven't upgraded to java 12. Fixing in BAEL-10841 -->
<!-- <module>core-java-13</module> --> <!-- We haven't upgraded to java 12. Fixing in BAEL-10841 -->
<!-- <module>core-java-14</module> --> <!-- We haven't upgraded to java 14.-->
<module>core-java-8</module>
<module>core-java-8-2</module>
<!-- <module>core-java-9</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<!-- <module>core-java-9-improvements</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<!-- <module>core-java-9-jigsaw</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<!-- <module>core-java-9-new-features</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<!-- <module>core-java-9-streams</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<module>core-java-annotations</module>
<module>core-java-arrays-sorting</module>
@ -51,7 +40,6 @@
<module>core-java-collections-maps</module>
<module>core-java-collections-maps-2</module>
<module>core-java-collections-maps-3</module>
<!-- <module>core-java-collections-set</module> --> <!-- We haven't upgraded to java 11. Fixing in BAEL-10841 -->
<module>core-java-concurrency-2</module>
<module>core-java-concurrency-advanced</module>
@ -65,10 +53,7 @@
<!--<module>core-java-8-datetime</module>--> <!-- unit test case failure -->
<module>core-java-8-datetime-2</module>
<!-- <module>core-java-date-operations-1</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<module>core-java-date-operations-2</module>
<!-- We haven't upgraded to java 9. -->
<!-- <module>core-java-datetime-computations</module> <module>core-java-datetime-conversion</module> <module>core-java-datetime-java8</module> <module>core-java-datetime-string</module> -->
<module>core-java-8-datetime</module>
<module>core-java-exceptions</module>
@ -85,7 +70,6 @@
<module>core-java-jar</module>
<module>core-java-jndi</module>
<!-- <module>core-java-jpms</module> --> <!-- We haven't upgraded to java 10. Fixing in BAEL-10841 -->
<module>core-java-jvm</module>
<module>core-java-jvm-2</module>
@ -113,7 +97,6 @@
<module>core-java-nio-2</module>
<module>core-java-optional</module>
<!--<module>core-java-os</module> --> <!-- We haven't upgraded to java 9. -->
<module>core-java-perf</module>
@ -138,9 +121,6 @@
<module>core-java-sun</module>
<module>core-java-regex</module>
<!-- <module>core-java-time-measurements</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<!-- <module>multimodulemavenproject</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<module>pre-jpms</module>
</modules>

View File

@ -2,6 +2,6 @@
This module contains articles about core Kotlin collections.
### Relevant articles:
## Relevant articles:
- [Aggregate Operations in Kotlin](https://www.baeldung.com/kotlin/aggregate-operations)

View File

@ -0,0 +1,3 @@
## Relevant Articles:
- [Passing Command Line Arguments in Gradle](https://www.baeldung.com/gradle-command-line-arguments)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Gradle Source Sets](https://www.baeldung.com/gradle-source-sets)

View File

@ -0,0 +1,35 @@
The files in this project were generated using gradle wrapper command.
`gradle wrapper`
To test, download this project on your machine and run the following:
`./wrapper tasks`
This should generate output similar to:
```
> Task :tasks
------------------------------------------------------------
Tasks runnable from root project
------------------------------------------------------------
Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.
Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'gradle-wrapper'.
components - Displays the components produced by root project 'gradle-wrapper'. [incubating]
dependencies - Displays all dependencies declared in root project 'gradle-wrapper'.
dependencyInsight - Displays the insight into a specific dependency in root project 'gradle-wrapper'.
dependentComponents - Displays the dependent components of components in root project 'gradle-wrapper'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'gradle-wrapper'. [incubating]
outgoingVariants - Displays the outgoing variants of root project 'gradle-wrapper'.
projects - Displays the sub-projects of root project 'gradle-wrapper'.
properties - Displays the properties of root project 'gradle-wrapper'.
tasks - Displays the tasks runnable from root project 'gradle-wrapper'.
To see all tasks and more detail, run gradlew tasks --all
```

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

183
gradle/gradle-wrapper/gradlew vendored Executable file
View File

@ -0,0 +1,183 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

103
gradle/gradle-wrapper/gradlew.bat vendored Normal file
View File

@ -0,0 +1,103 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xmlns="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>hazelcast</artifactId>
<version>0.0.1-SNAPSHOT</version>
@ -15,7 +15,6 @@
</parent>
<dependencies>
<!-- Hazelcast Jet -->
<dependency>
<groupId>com.hazelcast.jet</groupId>
<artifactId>hazelcast-jet</artifactId>
@ -34,8 +33,7 @@
</build>
<properties>
<!-- hazelcast jet -->
<hazelcast.jet.version>0.6</hazelcast.jet.version>
<hazelcast.jet.version>4.2</hazelcast.jet.version>
</properties>
</project>

View File

@ -1,24 +1,20 @@
package com.baeldung.hazelcast.cluster;
import java.util.Map.Entry;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.config.GroupConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import java.util.Map;
public class NativeClient {
public static void main(String[] args) throws InterruptedException {
public static void main(String[] args) {
ClientConfig config = new ClientConfig();
GroupConfig groupConfig = config.getGroupConfig();
groupConfig.setName("dev");
groupConfig.setPassword("dev-pass");
config.setClusterName("dev");
HazelcastInstance hazelcastInstanceClient = HazelcastClient.newHazelcastClient(config);
IMap<Long, String> map = hazelcastInstanceClient.getMap("data");
for (Entry<Long, String> entry : map.entrySet()) {
System.out.println(String.format("Key: %d, Value: %s", entry.getKey(), entry.getValue()));
Map<Long, String> map = hazelcastInstanceClient.getMap("data");
for (Map.Entry<Long, String> entry : map.entrySet()) {
System.out.printf("Key: %d, Value: %s%n", entry.getKey(), entry.getValue());
}
}
}

View File

@ -1,19 +1,19 @@
package com.baeldung.hazelcast.cluster;
import java.util.Map;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IdGenerator;
import com.hazelcast.flakeidgen.FlakeIdGenerator;
import java.util.Map;
public class ServerNode {
public static void main(String[] args) {
HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance();
Map<Long, String> map = hazelcastInstance.getMap("data");
IdGenerator idGenerator = hazelcastInstance.getIdGenerator("newid");
FlakeIdGenerator idGenerator = hazelcastInstance.getFlakeIdGenerator("newid");
for (int i = 0; i < 10; i++) {
map.put(idGenerator.newId(), "message" + 1);
map.put(idGenerator.newId(), "message" + i);
}
}
}

View File

@ -1,33 +1,31 @@
package com.baeldung.hazelcast.jet;
import java.util.List;
import java.util.Map;
import static com.hazelcast.jet.Traversers.traverseArray;
import static com.hazelcast.jet.aggregate.AggregateOperations.counting;
import static com.hazelcast.jet.function.DistributedFunctions.wholeItem;
import com.hazelcast.jet.Jet;
import com.hazelcast.jet.JetInstance;
import com.hazelcast.jet.pipeline.Pipeline;
import com.hazelcast.jet.pipeline.Sinks;
import com.hazelcast.jet.pipeline.Sources;
import java.util.List;
import java.util.Map;
import static com.hazelcast.function.Functions.wholeItem;
import static com.hazelcast.jet.Traversers.traverseArray;
import static com.hazelcast.jet.aggregate.AggregateOperations.counting;
public class WordCounter {
private static final String LIST_NAME = "textList";
private static final String MAP_NAME = "countMap";
private Pipeline createPipeLine() {
Pipeline p = Pipeline.create();
p.drawFrom(Sources.<String> list(LIST_NAME))
.flatMap(word -> traverseArray(word.toLowerCase()
.split("\\W+")))
p.readFrom(Sources.<String>list(LIST_NAME))
.flatMap(word -> traverseArray(word.toLowerCase().split("\\W+")))
.filter(word -> !word.isEmpty())
.groupingKey(wholeItem())
.aggregate(counting())
.drainTo(Sinks.map(MAP_NAME));
.writeTo(Sinks.map(MAP_NAME));
return p;
}
@ -38,8 +36,7 @@ public class WordCounter {
List<String> textList = jet.getList(LIST_NAME);
textList.addAll(sentences);
Pipeline p = createPipeLine();
jet.newJob(p)
.join();
jet.newJob(p).join();
Map<String, Long> counts = jet.getMap(MAP_NAME);
count = counts.get(word);
} finally {

View File

@ -1,16 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<hazelcast xsi:schemaLocation="http://www.hazelcast.com/schema/config hazelcast-config-3.7.xsd"
xmlns="http://www.hazelcast.com/schema/config"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<hazelcast xmlns="http://www.hazelcast.com/schema/config"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.hazelcast.com/schema/config
http://www.hazelcast.com/schema/config/hazelcast-config-4.0.xsd">
<network>
<port auto-increment="true" port-count="20">5701</port>
<join>
<multicast enabled="false">
</multicast>
<tcp-ip enabled="true">
<member>machine1</member>
<member>localhost</member>
</tcp-ip>
<multicast enabled="false"/>
<tcp-ip enabled="true">
<member>machine1</member>
<member>localhost</member>
</tcp-ip>
</join>
</network>
</hazelcast>

View File

@ -1,11 +1,11 @@
package com.baeldung.hazelcast.jet;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class WordCounterUnitTest {
@ -15,7 +15,7 @@ public class WordCounterUnitTest {
sentences.add("The first second was alright, but the second second was tough.");
WordCounter wordCounter = new WordCounter();
long countSecond = wordCounter.countWord(sentences, "second");
assertTrue(countSecond == 3);
assertEquals(3, countSecond);
}
}

12
httpclient-2/README.md Normal file
View File

@ -0,0 +1,12 @@
## HttpClient 4.x
This module contains articles about HttpClient 4.x
### The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [How to Set TLS Version in Apache HttpClient](https://www.baeldung.com/TODO)
- More articles: [[<-- prev]](../httpclient)

43
httpclient-2/pom.xml Normal file
View File

@ -0,0 +1,43 @@
<?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>httpclient-2</artifactId>
<version>0.1-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<finalName>httpclient-2</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<httpclient.version>4.5.8</httpclient.version>
</properties>
</project>

View File

@ -0,0 +1,64 @@
package com.baeldung.tlsversion;
import javax.net.ssl.SSLSocket;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class ClientTlsVersionExamples {
public static CloseableHttpClient setViaSocketFactory() {
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
SSLContexts.createDefault(),
new String[] { "TLSv1.2", "TLSv1.3" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
public static CloseableHttpClient setTlsVersionPerConnection() {
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(SSLContexts.createDefault()) {
@Override
protected void prepareSocket(SSLSocket socket) {
String hostname = socket.getInetAddress().getHostName();
if (hostname.endsWith("internal.system.com")) {
socket.setEnabledProtocols(new String[] { "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3" });
} else {
socket.setEnabledProtocols(new String[] { "TLSv1.3" });
}
}
};
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
// To configure the TLS versions for the client, set the https.protocols system property during runtime.
// For example: java -Dhttps.protocols=TLSv1.1,TLSv1.2,TLSv1.3 -jar webClient.jar
public static CloseableHttpClient setViaSystemProperties() {
return HttpClients.createSystem();
// Alternatively:
// return HttpClients.custom().useSystemProperties().build();
}
public static void main(String[] args) throws IOException {
// Alternatively:
// CloseableHttpClient httpClient = setTlsVersionPerConnection();
// CloseableHttpClient httpClient = setViaSystemProperties();
try (CloseableHttpClient httpClient = setViaSocketFactory();
CloseableHttpResponse response = httpClient.execute(new HttpGet("https://httpbin.org/"))) {
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
}
}
}

View File

@ -18,3 +18,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Advanced HttpClient Configuration](https://www.baeldung.com/httpclient-advanced-config)
- [HttpClient 4 Do Not Follow Redirects](https://www.baeldung.com/httpclient-stop-follow-redirect)
- [Custom User-Agent in HttpClient 4](https://www.baeldung.com/httpclient-user-agent-header)
- More articles: [[next -->]](../httpclient-2)

View File

@ -7,4 +7,5 @@ This module contains articles about conversions among Collection types and array
- [Array to String Conversions](https://www.baeldung.com/java-array-to-string)
- [Mapping Lists with ModelMapper](https://www.baeldung.com/java-modelmapper-lists)
- [Converting List to Map With a Custom Supplier](https://www.baeldung.com/list-to-map-supplier)
- [Arrays.asList vs new ArrayList(Arrays.asList())](https://www.baeldung.com/java-arrays-aslist-vs-new-arraylist)
- More articles: [[<-- prev]](../java-collections-conversions)

View File

@ -116,4 +116,41 @@
<moshi.version>1.9.2</moshi.version>
<commons-lang3.version>3.9</commons-lang3.version>
</properties>
<build>
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>
org.apache.maven.plugins
</groupId>
<artifactId>
maven-pmd-plugin
</artifactId>
<versionRange>
[3.13.0,)
</versionRange>
<goals>
<goal>check</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

@ -0,0 +1,123 @@
package com.baeldung.jsonoptimization;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Customer {
private long id;
private String firstName;
private String lastName;
private String street;
private String postalCode;
private String city;
private String state;
private String phoneNumber;
private String email;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public int hashCode() {
return Objects.hash(city, email, firstName, id, lastName, phoneNumber, postalCode, state, street);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Customer)) {
return false;
}
Customer other = (Customer) obj;
return Objects.equals(city, other.city) && Objects.equals(email, other.email) && Objects.equals(firstName, other.firstName) && id == other.id && Objects.equals(lastName, other.lastName) && Objects.equals(phoneNumber, other.phoneNumber)
&& Objects.equals(postalCode, other.postalCode) && Objects.equals(state, other.state) && Objects.equals(street, other.street);
}
@Override
public String toString() {
return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", street=" + street + ", postalCode=" + postalCode + ", city=" + city + ", state=" + state + ", phoneNumber=" + phoneNumber + ", email=" + email + "]";
}
public static Customer[] fromMockFile() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
InputStream jsonFile = new FileInputStream("src/test/resources/json_optimization_mock_data.json");
Customer[] feedback = objectMapper.readValue(jsonFile, Customer[].class);
return feedback;
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.jsonoptimization;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
public class CustomerDeserializer extends StdDeserializer<Customer> {
private static final long serialVersionUID = 1L;
public CustomerDeserializer() {
this(null);
}
public CustomerDeserializer(Class<Customer> t) {
super(t);
}
@Override
public Customer deserialize(JsonParser parser, DeserializationContext deserializer) throws IOException {
Customer feedback = new Customer();
ObjectCodec codec = parser.getCodec();
JsonNode node = codec.readTree(parser);
feedback.setId(node.get(0)
.asLong());
feedback.setFirstName(node.get(1)
.asText());
feedback.setLastName(node.get(2)
.asText());
feedback.setStreet(node.get(3)
.asText());
feedback.setPostalCode(node.get(4)
.asText());
feedback.setCity(node.get(5)
.asText());
feedback.setState(node.get(6)
.asText());
JsonNode phoneNumber = node.get(7);
feedback.setPhoneNumber(phoneNumber.isNull() ? null : phoneNumber.asText());
JsonNode email = node.get(8);
feedback.setEmail(email.isNull() ? null : email.asText());
return feedback;
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.jsonoptimization;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class CustomerSerializer extends StdSerializer<Customer> {
private static final long serialVersionUID = 1L;
public CustomerSerializer() {
this(null);
}
public CustomerSerializer(Class<Customer> t) {
super(t);
}
@Override
public void serialize(Customer customer, JsonGenerator jsonGenerator, SerializerProvider serializer) throws IOException {
jsonGenerator.writeStartArray();
jsonGenerator.writeNumber(customer.getId());
jsonGenerator.writeString(customer.getFirstName());
jsonGenerator.writeString(customer.getLastName());
jsonGenerator.writeString(customer.getStreet());
jsonGenerator.writeString(customer.getPostalCode());
jsonGenerator.writeString(customer.getCity());
jsonGenerator.writeString(customer.getState());
jsonGenerator.writeString(customer.getPhoneNumber());
jsonGenerator.writeString(customer.getEmail());
jsonGenerator.writeEndArray();
}
}

View File

@ -0,0 +1,155 @@
package com.baeldung.jsonoptimization;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
public class CustomerShortNames {
@JsonProperty("i")
private long id;
@JsonProperty("f")
private String firstName;
@JsonProperty("l")
private String lastName;
@JsonProperty("s")
private String street;
@JsonProperty("p")
private String postalCode;
@JsonProperty("c")
private String city;
@JsonProperty("a")
private String state;
@JsonProperty("o")
private String phoneNumber;
@JsonProperty("e")
private String email;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public int hashCode() {
return Objects.hash(city, email, firstName, id, lastName, phoneNumber, postalCode, state, street);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof CustomerShortNames)) {
return false;
}
CustomerShortNames other = (CustomerShortNames) obj;
return Objects.equals(city, other.city) && Objects.equals(email, other.email) && Objects.equals(firstName, other.firstName) && id == other.id && Objects.equals(lastName, other.lastName) && Objects.equals(phoneNumber, other.phoneNumber)
&& Objects.equals(postalCode, other.postalCode) && Objects.equals(state, other.state) && Objects.equals(street, other.street);
}
@Override
public String toString() {
return "CustomerWithShorterAttributes [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", street=" + street + ", postalCode=" + postalCode + ", city=" + city + ", state=" + state + ", phoneNumber=" + phoneNumber + ", email=" + email
+ "]";
}
public static CustomerShortNames[] fromCustomers(Customer[] customers) {
CustomerShortNames[] feedback = new CustomerShortNames[customers.length];
for (int i = 0; i < customers.length; i++) {
Customer aCustomer = customers[i];
CustomerShortNames newOne = new CustomerShortNames();
newOne.setId(aCustomer.getId());
newOne.setFirstName(aCustomer.getFirstName());
newOne.setLastName(aCustomer.getLastName());
newOne.setStreet(aCustomer.getStreet());
newOne.setCity(aCustomer.getCity());
newOne.setPostalCode(aCustomer.getPostalCode());
newOne.setState(aCustomer.getState());
newOne.setPhoneNumber(aCustomer.getPhoneNumber());
newOne.setEmail(aCustomer.getEmail());
feedback[i] = newOne;
}
return feedback;
}
}

View File

@ -0,0 +1,73 @@
package com.baeldung.jsonoptimization;
import java.util.Objects;
public class CustomerSlim {
private long id;
private String name;
private String address;
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;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public int hashCode() {
return Objects.hash(address, id, name);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof CustomerSlim)) {
return false;
}
CustomerSlim other = (CustomerSlim) obj;
return Objects.equals(address, other.address) && id == other.id && Objects.equals(name, other.name);
}
@Override
public String toString() {
return "CustomerSlim [id=" + id + ", name=" + name + ", address=" + address + "]";
}
public static CustomerSlim[] fromCustomers(Customer[] customers) {
CustomerSlim[] feedback = new CustomerSlim[customers.length];
for (int i = 0; i < customers.length; i++) {
Customer aCustomer = customers[i];
CustomerSlim newOne = new CustomerSlim();
newOne.setId(aCustomer.getId());
newOne.setName(aCustomer.getFirstName() + " " + aCustomer.getLastName());
newOne.setAddress(aCustomer.getStreet() + ", " + aCustomer.getCity() + " " + aCustomer.getState() + " " + aCustomer.getPostalCode());
feedback[i] = newOne;
}
return feedback;
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.jsonoptimization;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
public class CustomerSlimDeserializer extends StdDeserializer<CustomerSlim> {
private static final long serialVersionUID = 1L;
public CustomerSlimDeserializer() {
this(null);
}
public CustomerSlimDeserializer(Class<CustomerSlim> t) {
super(t);
}
@Override
public CustomerSlim deserialize(JsonParser parser, DeserializationContext deserializer) throws IOException {
CustomerSlim feedback = new CustomerSlim();
ObjectCodec codec = parser.getCodec();
JsonNode node = codec.readTree(parser);
feedback.setId(node.get(0)
.asLong());
feedback.setName(node.get(1)
.asText());
feedback.setAddress(node.get(2)
.asText());
return feedback;
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.jsonoptimization;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class CustomerSlimSerializer extends StdSerializer<CustomerSlim> {
private static final long serialVersionUID = 1L;
public CustomerSlimSerializer() {
this(null);
}
public CustomerSlimSerializer(Class<CustomerSlim> t) {
super(t);
}
@Override
public void serialize(CustomerSlim customer, JsonGenerator jsonGenerator, SerializerProvider serializer) throws IOException {
jsonGenerator.writeStartArray();
jsonGenerator.writeNumber(customer.getId());
jsonGenerator.writeString(customer.getName());
jsonGenerator.writeString(customer.getAddress());
jsonGenerator.writeEndArray();
}
}

View File

@ -0,0 +1,81 @@
package com.baeldung.jsonoptimization;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
public class CustomerSlimShortNames {
@JsonProperty("i")
private long id;
@JsonProperty("n")
private String name;
@JsonProperty("a")
private String address;
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;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public int hashCode() {
return Objects.hash(address, id, name);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof CustomerSlimShortNames)) {
return false;
}
CustomerSlimShortNames other = (CustomerSlimShortNames) obj;
return Objects.equals(address, other.address) && id == other.id && Objects.equals(name, other.name);
}
@Override
public String toString() {
return "CustomerSlim [id=" + id + ", name=" + name + ", address=" + address + "]";
}
public static CustomerSlimShortNames[] fromCustomers(Customer[] customers) {
CustomerSlimShortNames[] feedback = new CustomerSlimShortNames[customers.length];
for (int i = 0; i < customers.length; i++) {
Customer aCustomer = customers[i];
CustomerSlimShortNames newOne = new CustomerSlimShortNames();
newOne.setId(aCustomer.getId());
newOne.setName(aCustomer.getFirstName() + " " + aCustomer.getLastName());
newOne.setAddress(aCustomer.getStreet() + ", " + aCustomer.getCity() + " " + aCustomer.getState() + " " + aCustomer.getPostalCode());
feedback[i] = newOne;
}
return feedback;
}
}

View File

@ -0,0 +1,180 @@
package com.baeldung.jsonoptimization;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.zip.GZIPOutputStream;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.module.SimpleModule;
class JsonOptimizationUnitTest {
private static final String TEST_LABEL_JACKSON_DEFAULT_OPTIONS = "Default JSON";
private static final String TEST_LABEL_DEFAULT_JSON_NO_NULL = "Default JSON without null";
private static final String TEST_LABEL_SHORTER_FIELD_NAMES = "Shorter field names";
private static final String TEST_LABEL_SHORTER_FIELD_NAMES_AND_NO_NULL = "Shorter field names without null";
private static final String TEST_LABEL_SERIALIZING_TO_ARRAY = "Custom serializer";
private static final String TEST_LABEL_SLIM_CUSTOM_SERIALIZER = "Slim custom serializer";
private static final String TEST_LABEL_SLIM_CUSTOMER = "Slim customer";
private static final String TEST_LABEL_SLIM_CUSTOMER_SHORT_NAMES = "Slim customer with shorter field names";
private static DecimalFormat LENGTH_FORMATTER = new DecimalFormat("###,###.0");
private static DecimalFormat PERCENT_FORMATTER = new DecimalFormat("###.0");
private static Customer[] customers;
private ObjectMapper mapper;
private static int defaultJsonLength;
@BeforeAll
static void setUpOnce() throws Exception {
customers = Customer.fromMockFile();
ObjectMapper oneTimeMapper = new ObjectMapper();
byte[] feedback = oneTimeMapper.writeValueAsBytes(customers);
defaultJsonLength = feedback.length;
System.out.println();
System.out.println("Default JSON length: " + defaultJsonLength);
System.out.println();
}
@BeforeEach
void setUp() {
mapper = new ObjectMapper();
}
@Test
void whenSetUp_ThenOneThousandCustomers() {
assertEquals(1000, customers.length, "There should be a 1000 customers");
}
@Test
void whenJacksonDefaultOptions_thenValid() throws IOException {
printBanner(TEST_LABEL_JACKSON_DEFAULT_OPTIONS);
byte[] plainJson = createJsonAndVerify(TEST_LABEL_JACKSON_DEFAULT_OPTIONS, customers);
compressJson(TEST_LABEL_JACKSON_DEFAULT_OPTIONS, plainJson);
}
@Test
void whenExcludingNull_thenValid() throws IOException {
printBanner(TEST_LABEL_DEFAULT_JSON_NO_NULL);
mapper.setSerializationInclusion(Include.NON_NULL);
byte[] plainJson = createJsonAndVerify(TEST_LABEL_DEFAULT_JSON_NO_NULL, customers);
compressJson(TEST_LABEL_DEFAULT_JSON_NO_NULL, plainJson);
}
@Test
void whenShorterFieldNames_thenValid() throws IOException {
printBanner(TEST_LABEL_SHORTER_FIELD_NAMES);
CustomerShortNames[] shorterOnes = CustomerShortNames.fromCustomers(customers);
byte[] shorterJson = createJsonAndVerify(TEST_LABEL_SHORTER_FIELD_NAMES, shorterOnes);
compressJson(TEST_LABEL_SHORTER_FIELD_NAMES, shorterJson);
}
@Test
void whenShorterFieldNamesAndExcludingNull_thenValid() throws IOException {
printBanner(TEST_LABEL_SHORTER_FIELD_NAMES_AND_NO_NULL);
CustomerShortNames[] shorterOnes = CustomerShortNames.fromCustomers(customers);
mapper.setSerializationInclusion(Include.NON_NULL);
byte[] shorterJson = createJsonAndVerify(TEST_LABEL_SHORTER_FIELD_NAMES_AND_NO_NULL, shorterOnes);
compressJson(TEST_LABEL_SHORTER_FIELD_NAMES_AND_NO_NULL, shorterJson);
}
@Test
void whenSlimCustomer_thenValid() throws IOException {
printBanner(TEST_LABEL_SLIM_CUSTOMER);
CustomerSlim[] slimOnes = CustomerSlim.fromCustomers(customers);
byte[] slimJson = createJsonAndVerify(TEST_LABEL_SLIM_CUSTOMER, slimOnes);
compressJson(TEST_LABEL_SLIM_CUSTOMER, slimJson);
}
@Test
void whenSlimCustomerAndShorterFieldNames_thenValid() throws IOException {
printBanner(TEST_LABEL_SLIM_CUSTOMER_SHORT_NAMES);
CustomerSlimShortNames[] slimOnes = CustomerSlimShortNames.fromCustomers(customers);
byte[] slimJson = createJsonAndVerify(TEST_LABEL_SLIM_CUSTOMER_SHORT_NAMES, slimOnes);
compressJson(TEST_LABEL_SLIM_CUSTOMER_SHORT_NAMES, slimJson);
}
@Test
void whenSerializingToArray_thenValid() throws IOException {
printBanner(TEST_LABEL_SERIALIZING_TO_ARRAY);
SimpleModule serializer = new SimpleModule("CustomDeSerializer", new Version(1, 0, 0, null, null, null));
serializer.addSerializer(Customer.class, new CustomerSerializer());
serializer.addDeserializer(Customer.class, new CustomerDeserializer());
mapper.registerModule(serializer);
byte[] plainJson = createJsonAndVerify(TEST_LABEL_SERIALIZING_TO_ARRAY, customers);
compressJson(TEST_LABEL_SERIALIZING_TO_ARRAY, plainJson);
}
@Test
void whenSerializingToArrayAndSlimCustomer_thenValid() throws IOException {
printBanner(TEST_LABEL_SLIM_CUSTOM_SERIALIZER);
SimpleModule serializer = new SimpleModule("SlimCustomDeSerializer", new Version(1, 0, 0, null, null, null));
serializer.addSerializer(CustomerSlim.class, new CustomerSlimSerializer());
serializer.addDeserializer(CustomerSlim.class, new CustomerSlimDeserializer());
mapper.registerModule(serializer);
CustomerSlim[] slimOnes = CustomerSlim.fromCustomers(customers);
byte[] plainJson = createJsonAndVerify(TEST_LABEL_SLIM_CUSTOM_SERIALIZER, slimOnes);
compressJson(TEST_LABEL_SLIM_CUSTOM_SERIALIZER, plainJson);
}
private void printBanner(String name) {
System.out.println();
System.out.println("************************************************");
System.out.println("Testing " + name);
System.out.println();
}
void compressJson(String label, byte[] plainJson) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GZIPOutputStream gzipStream = new GZIPOutputStream(outputStream);
gzipStream.write(plainJson);
gzipStream.close();
outputStream.close();
byte[] gzippedJson = outputStream.toByteArray();
double length = gzippedJson.length / 1024d;
double percent = gzippedJson.length * 100d / defaultJsonLength;
System.out.println(label + " GZIPped length: " + LENGTH_FORMATTER.format(length)
+ "kB (" + PERCENT_FORMATTER.format(percent) + "%)");
assertTrue(plainJson.length > gzippedJson.length, label + " should be longer than GZIPped data");
}
private byte[] createJsonAndVerify(String label, Object[] customers) throws IOException {
System.out.println(label + " sample: ");
ObjectWriter prettyWritter = mapper.writerWithDefaultPrettyPrinter();
System.out.println(prettyWritter.writeValueAsString(customers[0]));
byte[] feedback = mapper.writeValueAsBytes(customers);
double length = feedback.length / 1024d;
double percent = feedback.length * 100d / defaultJsonLength;
System.out.println(label + " length: " + LENGTH_FORMATTER.format(length)
+ "kB (" + PERCENT_FORMATTER.format(percent) + "%)");
assertTrue(feedback.length > 1, label + " should be there");
String prefix = label.replaceAll(" ", "-")
.toLowerCase();
File tempFile = File.createTempFile("jon-optimization-" + prefix, ".json");
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(feedback);
fos.close();
System.out.println(label + " file: " + tempFile.toString());
Object[] restoredOnes = mapper.readValue(feedback, customers.getClass());
assertArrayEquals(TEST_LABEL_JACKSON_DEFAULT_OPTIONS + ": restoring from JSON should work", customers, restoredOnes);
return feedback;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -13,3 +13,4 @@ This module contains articles about JSON.
- [Get a Value by Key in a JSONArray](https://www.baeldung.com/java-jsonarray-get-value-by-key)
- [Iterating Over an Instance of org.json.JSONObject](https://www.baeldung.com/jsonobject-iteration)
- [Escape JSON String in Java](https://www.baeldung.com/java-json-escaping)
- [Reducing JSON Data Size](https://www.baeldung.com/json-reduce-data-size)

View File

@ -11,3 +11,4 @@ This module contains articles about security libraries.
- [Intro to Jasypt](https://www.baeldung.com/jasypt)
- [Digital Signatures in Java](https://www.baeldung.com/java-digital-signature)
- [How to Read PEM File to Get Public and Private Keys](https://www.baeldung.com/java-read-pem-file-keys)
- [SSH Connection With Java](https://www.baeldung.com/java-ssh-connection)

View File

@ -12,3 +12,4 @@ This module contains articles about test libraries.
- [Introduction to Hoverfly in Java](https://www.baeldung.com/hoverfly)
- [Testing with Hamcrest](https://www.baeldung.com/java-junit-hamcrest-guide)
- [Introduction To DBUnit](https://www.baeldung.com/java-dbunit)
- [Introduction to ArchUnit](https://www.baeldung.com/java-archunit-intro)

View File

@ -0,0 +1,18 @@
package com.baeldung.lombok.builder;
import lombok.Builder;
import lombok.Getter;
import lombok.NonNull;
@Builder(builderMethodName = "internalBuilder")
@Getter
public class RequiredFieldAnnotation {
@NonNull
String name;
String description;
public static RequiredFieldAnnotationBuilder builder(String name) {
return internalBuilder().name(name);
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.lombok.builder;
import org.junit.Before;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class RequiredFieldAnnotationUnitTest {
RequiredFieldAnnotation requiredFieldTest;
@Before
public void setUp() {
requiredFieldTest = RequiredFieldAnnotation.builder("NameField").description("Field Description").build();
}
@Test
public void givenBuilderWithRequiredParameter_thenParameterIsPresent() {
assertEquals("NameField", requiredFieldTest.getName());
}
}

View File

@ -71,7 +71,7 @@
</build>
<properties>
<org.mapstruct.version>1.4.0.Beta1</org.mapstruct.version>
<org.mapstruct.version>1.3.1.Final</org.mapstruct.version>
<springframework.version>4.3.4.RELEASE</springframework.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>

View File

@ -5,7 +5,8 @@ import com.baeldung.mapstruct.mappingCollections.model.Company;
import org.mapstruct.CollectionMappingStrategy;
import org.mapstruct.Mapper;
@Mapper(collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED)
@Mapper(collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED,
uses = EmployeeMapper.class)
public interface CompanyMapperAdderPreferred {
CompanyDTO map(Company company);

View File

@ -11,6 +11,8 @@ import java.util.Set;
@Mapper
public interface EmployeeMapper {
EmployeeDTO map(Employee employee);
List<EmployeeDTO> map(List<Employee> employees);
Set<EmployeeDTO> map(Set<Employee> employees);

View File

@ -1,22 +0,0 @@
<?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.entitymodule</groupId>
<artifactId>entitymodule</artifactId>
<version>1.0</version>
<name>entitymodule</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.multimodule-maven-project</groupId>
<artifactId>multimodule-maven-project</artifactId>
<version>1.0</version>
</parent>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
</project>

View File

@ -1,19 +0,0 @@
package com.baeldung.entity;
public class User {
private final String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "User{" + "name=" + name + '}';
}
}

View File

@ -1,3 +0,0 @@
module com.baeldung.entity {
exports com.baeldung.entity;
}

View File

@ -1,41 +0,0 @@
<?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.mainappmodule</groupId>
<artifactId>mainappmodule</artifactId>
<version>1.0</version>
<name>mainappmodule</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.multimodule-maven-project</groupId>
<artifactId>multimodule-maven-project</artifactId>
<version>1.0</version>
</parent>
<dependencies>
<dependency>
<groupId>com.baeldung.entitymodule</groupId>
<artifactId>entitymodule</artifactId>
<version>${entitymodule.version}</version>
</dependency>
<dependency>
<groupId>com.baeldung.daomodule</groupId>
<artifactId>daomodule</artifactId>
<version>${daomodule.version}</version>
</dependency>
<dependency>
<groupId>com.baeldung.userdaomodule</groupId>
<artifactId>userdaomodule</artifactId>
<version>${userdaomodule.version}</version>
</dependency>
</dependencies>
<properties>
<entitymodule.version>1.0</entitymodule.version>
<daomodule.version>1.0</daomodule.version>
<userdaomodule.version>1.0</userdaomodule.version>
</properties>
</project>

View File

@ -1,19 +0,0 @@
package com.baeldung.mainapp;
import com.baeldung.dao.Dao;
import com.baeldung.entity.User;
import com.baeldung.userdao.UserDao;
import java.util.HashMap;
import java.util.Map;
public class Application {
public static void main(String[] args) {
Map<Integer, User> users = new HashMap<>();
users.put(1, new User("Julie"));
users.put(2, new User("David"));
Dao userDao = new UserDao(users);
userDao.findAll().forEach(System.out::println);
}
}

View File

@ -1,6 +0,0 @@
module com.baeldung.mainapp {
requires com.baeldung.entity;
requires com.baeldung.userdao;
requires com.baeldung.dao;
uses com.baeldung.dao.Dao;
}

View File

@ -14,6 +14,11 @@
<relativePath>../..</relativePath>
</parent>
<modules>
<!--<module>custom-rule</module>--> <!-- Fixing in JAVA-2819 -->
<module>maven-enforcer</module>
</modules>
<build>
<plugins>
<plugin>

View File

@ -1,3 +1,4 @@
### Relevant Articles:
- [Service Locator Pattern](https://www.baeldung.com/java-service-locator-pattern)
- [The DAO Pattern in Java](https://www.baeldung.com/java-dao-pattern)
- [DAO vs Repository Patterns](https://www.baeldung.com/java-dao-vs-repository)

View File

@ -11,9 +11,8 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<artifactId>persistence-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>

View File

@ -188,13 +188,6 @@
<scope>provided</scope>
</dependency>
<!-- Needed for running tests (you may also use TestNG) -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- Others -->
<dependency>
<groupId>org.apache.commons</groupId>

View File

@ -75,6 +75,11 @@
<properties>
<flyway.configFiles>src/main/resources/application-${spring-boot.run.profiles}.properties</flyway.configFiles>
<!-- testing -->
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
<junit.version>4.13</junit.version>
</properties>
</project>

View File

@ -1,3 +1,4 @@
### Relevant Articles:
- [Database Migrations with Flyway](http://www.baeldung.com/database-migrations-with-flyway)
- [A Guide to Flyway Callbacks](http://www.baeldung.com/flyway-callbacks)
- [Rolling Back Migrations with Flyway](https://www.baeldung.com/flyway-roll-back)

View File

@ -65,6 +65,11 @@
<properties>
<flyway-core.version>5.2.3</flyway-core.version>
<flyway-maven-plugin.version>5.0.2</flyway-maven-plugin.version>
<!-- testing -->
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
<junit.version>4.13</junit.version>
</properties>
</project>

View File

@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jooq</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jooq-examples</name>
<packaging>jar</packaging>
<description>jOOQ Examples</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>persistence-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jooq</artifactId>
<version>3.13.4</version>
</dependency>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jooq-meta</artifactId>
<version>3.13.4</version>
</dependency>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jooq-codegen</artifactId>
<version>3.13.4</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.16</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,57 @@
package com.baeldung.jooq;
import org.jooq.Condition;
import org.jooq.DSLContext;
import org.jooq.Field;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.SelectFieldOrAsterisk;
import org.jooq.Table;
import org.jooq.UpdatableRecord;
import java.util.Map;
public class Crud {
public static <R extends UpdatableRecord<R>> void save(UpdatableRecord<R> record) {
record.store();
}
public static Result<Record> getAll(DSLContext context, Table<? extends Record> table) {
return context.select()
.from(table)
.fetch();
}
public static Result<Record> getFields(DSLContext context, Table<? extends Record> table, SelectFieldOrAsterisk... fields) {
return context.select(fields)
.from(table)
.fetch();
}
public static <R extends Record> R getOne(DSLContext context, Table<R> table, Condition condition) {
return context.fetchOne(table, condition);
}
public static <T> void update(DSLContext context, Table<? extends Record> table, Map<Field<T>, T> values, Condition condition) {
context.update(table)
.set(values)
.where(condition)
.execute();
}
public static <R extends UpdatableRecord<R>> void update(UpdatableRecord<R> record) {
record.update();
}
public static void delete(DSLContext context, Table<? extends Record> table, Condition condition) {
context.delete(table)
.where(condition)
.execute();
}
public static <R extends UpdatableRecord<R>> void delete(UpdatableRecord<R> record) {
record.delete();
}
}

View File

@ -0,0 +1,117 @@
package com.baeldung.jooq;
import com.baeldung.jooq.model.tables.Article;
import com.baeldung.jooq.model.tables.Author;
import com.baeldung.jooq.model.tables.records.ArticleRecord;
import com.baeldung.jooq.model.tables.records.AuthorRecord;
import org.jooq.DSLContext;
import org.jooq.Field;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import static com.baeldung.jooq.Crud.delete;
import static com.baeldung.jooq.Crud.getAll;
import static com.baeldung.jooq.Crud.getFields;
import static com.baeldung.jooq.Crud.getOne;
import static com.baeldung.jooq.Crud.save;
import static com.baeldung.jooq.Crud.update;
public class CrudExamples {
public void crudExamples() throws SQLException {
String userName = "username";
String password = "password";
String url = "jdbc:postgresql://db_url:5432/baeldung_database";
Connection conn = DriverManager.getConnection(url, userName, password);
DSLContext context = DSL.using(conn, SQLDialect.POSTGRES);
createValues(context);
readValues(context);
updateValues(context);
deleteValues(context);
}
private void createValues(DSLContext context) {
ArticleRecord article = context.newRecord(Article.ARTICLE);
article.setId(2);
article.setTitle("jOOQ examples");
article.setDescription("A few examples of jOOQ CRUD operations");
article.setAuthorId(1);
save(article);
AuthorRecord author = context.newRecord(Author.AUTHOR);
author.setId(1);
author.setFirstName("John");
author.setLastName("Smith");
author.setAge(40);
save(author);
}
private void readValues(DSLContext context) {
Result<Record> authors = getAll(
context,
Author.AUTHOR
);
authors.forEach(author -> {
Integer id = author.getValue(Author.AUTHOR.ID);
String firstName = author.getValue(Author.AUTHOR.FIRST_NAME);
String lastName = author.getValue(Author.AUTHOR.LAST_NAME);
Integer age = author.getValue(Author.AUTHOR.AGE);
System.out.printf("Author %s %s has id: %d and age: %d%n", firstName, lastName, id, age);
});
Result<Record> articles = getFields(
context,
Author.AUTHOR,
Article.ARTICLE.ID, Article.ARTICLE.TITLE
);
AuthorRecord author = getOne(
context,
Author.AUTHOR,
Author.AUTHOR.ID.eq(1)
);
}
private void updateValues(DSLContext context) {
HashMap<Field<String>, String> fieldsToUpdate = new HashMap<>();
fieldsToUpdate.put(Author.AUTHOR.FIRST_NAME, "David");
fieldsToUpdate.put(Author.AUTHOR.LAST_NAME, "Brown");
update(
context,
Author.AUTHOR,
fieldsToUpdate,
Author.AUTHOR.ID.eq(1)
);
ArticleRecord article = context.fetchOne(Article.ARTICLE, Article.ARTICLE.ID.eq(1));
article.setTitle("A New Article Title");
update(
article
);
}
private void deleteValues(DSLContext context) {
delete(
context,
Article.ARTICLE,
Article.ARTICLE.ID.eq(1)
);
AuthorRecord author = context.fetchOne(Author.AUTHOR, Author.AUTHOR.ID.eq(1));
delete(author);
}
}

View File

@ -0,0 +1,44 @@
/*
* This file is generated by jOOQ.
*/
package com.baeldung.jooq.model;
import org.jooq.Schema;
import org.jooq.impl.CatalogImpl;
import java.util.Arrays;
import java.util.List;
/**
* This class is generated by jOOQ.
*/
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class DefaultCatalog extends CatalogImpl {
private static final long serialVersionUID = 1035293962;
/**
* The reference instance of <code>DEFAULT_CATALOG</code>
*/
public static final DefaultCatalog DEFAULT_CATALOG = new DefaultCatalog();
/**
* The schema <code>public</code>.
*/
public final Public PUBLIC = Public.PUBLIC;
/**
* No further instances allowed
*/
private DefaultCatalog() {
super("");
}
@Override
public final List<Schema> getSchemas() {
return Arrays.<Schema>asList(
Public.PUBLIC);
}
}

Some files were not shown because too many files have changed in this diff Show More