Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
fcb493e6ba
|
@ -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)
|
||||
|
|
|
@ -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>
|
|
@ -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)
|
||||
}
|
||||
|
||||
}
|
|
@ -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 );
|
||||
}
|
||||
|
||||
/**
|
|
@ -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() {
|
|
@ -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() {
|
|
@ -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>
|
||||
|
|
|
@ -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 {
|
|
@ -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)
|
||||
|
|
|
@ -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
|
||||
|
@ -71,7 +94,7 @@ public class DateDiffUnitTest {
|
|||
ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore"))
|
||||
.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);
|
||||
}
|
||||
}
|
|
@ -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() {
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
|
||||
|
|
|
@ -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));
|
||||
|
|
|
@ -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,6 +67,11 @@ public class TemporaryDirectoriesUnitTest {
|
|||
|
||||
@Test
|
||||
public void givenTempDirWithPrefixWithFileAttrs_whenCreatePlainJava_thenAttributesAreSet() throws IOException {
|
||||
boolean isPosix = FileSystems.getDefault().supportedFileAttributeViews().contains("posix");
|
||||
|
||||
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);
|
||||
|
@ -73,3 +79,4 @@ public class TemporaryDirectoriesUnitTest {
|
|||
assertThat(tmpdir.toFile().canWrite()).isFalse();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -17,7 +17,7 @@
|
|||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.baeldung.servicemodule</groupId>
|
||||
<artifactId>servicemodule</artifactId>
|
||||
<artifactId>servicemodule1</artifactId>
|
||||
<version>${servicemodule.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -17,7 +17,7 @@
|
|||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.baeldung.servicemodule</groupId>
|
||||
<artifactId>servicemodule</artifactId>
|
||||
<artifactId>servicemodule2</artifactId>
|
||||
<version>${servicemodule.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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";
|
||||
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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>
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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>
|
||||
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant Articles:
|
||||
|
||||
- [Passing Command Line Arguments in Gradle](https://www.baeldung.com/gradle-command-line-arguments)
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Gradle Source Sets](https://www.baeldung.com/gradle-source-sets)
|
|
@ -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>
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -1,12 +1,12 @@
|
|||
<?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>
|
||||
<multicast enabled="false"/>
|
||||
<tcp-ip enabled="true">
|
||||
<member>machine1</member>
|
||||
<member>localhost</member>
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
100
pom.xml
100
pom.xml
|
@ -383,6 +383,7 @@
|
|||
<module>core-groovy</module>
|
||||
<module>core-groovy-2</module>
|
||||
<module>core-groovy-collections</module>
|
||||
<module>core-groovy-strings</module>
|
||||
|
||||
<module>core-java-modules</module>
|
||||
<module>core-kotlin-modules</module>
|
||||
|
@ -894,6 +895,7 @@
|
|||
<module>core-groovy</module>
|
||||
<module>core-groovy-2</module>
|
||||
<module>core-groovy-collections</module>
|
||||
<module>core-groovy-strings</module>
|
||||
|
||||
<module>core-java-modules</module>
|
||||
<module>core-kotlin-modules</module>
|
||||
|
@ -1332,6 +1334,104 @@
|
|||
|
||||
</profile>
|
||||
|
||||
<profile>
|
||||
<id>default-jdk9-and-above</id>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<forkCount>3</forkCount>
|
||||
<reuseForks>true</reuseForks>
|
||||
<includes>
|
||||
<include>SpringContextTest</include>
|
||||
<include>**/*UnitTest</include>
|
||||
</includes>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*IntTest.java</exclude>
|
||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
<exclude>**/JdbcTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<modules>
|
||||
<module>core-java-modules/core-java-9</module>
|
||||
<module>core-java-modules/core-java-9-improvements</module>
|
||||
<!-- <module>core-java-modules/core-java-9-jigsaw</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<!-- <module>core-java-modules/core-java-9-new-features</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<module>core-java-modules/core-java-9-streams</module>
|
||||
<module>core-java-modules/core-java-10</module>
|
||||
<!-- <module>core-java-modules/core-java-11</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<!-- <module>core-java-modules/core-java-12</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<!-- <module>core-java-modules/core-java-13</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<!-- <module>core-java-modules/core-java-14</module> --> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<module>core-java-modules/core-java-collections-set</module>
|
||||
<!-- <module>core-java-modules/core-java-date-operations-1</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<!-- <module>core-java-modules/core-java-datetime-conversion</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<!-- <module>core-java-modules/core-java-datetime-string</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<module>core-java-modules/core-java-jpms</module>
|
||||
<!-- <module>core-java-modules/core-java-os</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<!-- <module>core-java-modules/core-java-time-measurements</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<module>core-java-modules/multimodulemavenproject</module>
|
||||
<!-- <module>maven-java-11</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
</modules>
|
||||
</profile>
|
||||
|
||||
<profile>
|
||||
<id>integration-jdk9-and-above</id>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
<includes>
|
||||
<include>**/*IntegrationTest.java</include>
|
||||
<include>**/*IntTest.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<modules>
|
||||
<module>core-java-modules/core-java-9</module>
|
||||
<module>core-java-modules/core-java-9-improvements</module>
|
||||
<!-- <module>core-java-modules/core-java-9-jigsaw</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<!-- <module>core-java-modules/core-java-9-new-features</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<module>core-java-modules/core-java-9-streams</module>
|
||||
<module>core-java-modules/core-java-10</module>
|
||||
<!-- <module>core-java-modules/core-java-11</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<!-- <module>core-java-modules/core-java-12</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<!-- <module>core-java-modules/core-java-13</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<!-- <module>core-java-modules/core-java-14</module> --> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<module>core-java-modules/core-java-collections-set</module>
|
||||
<!-- <module>core-java-modules/core-java-date-operations-1</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<!-- <module>core-java-modules/core-java-datetime-conversion</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<!-- <module>core-java-modules/core-java-datetime-string</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<module>core-java-modules/core-java-jpms</module>
|
||||
<!-- <module>core-java-modules/core-java-os</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<!-- <module>core-java-modules/core-java-time-measurements</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
<module>core-java-modules/multimodulemavenproject</module>
|
||||
<!-- <module>maven-java-11</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
|
||||
</modules>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<reporting>
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
## Relevant Articles:
|
||||
|
||||
- [Guide to QuarkusIO](https://www.baeldung.com/quarkus-io)
|
||||
- [Testing Quarkus Applications](https://www.baeldung.com/java-quarkus-testing)
|
||||
|
|
|
@ -99,6 +99,8 @@
|
|||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<forkCount>1</forkCount>
|
||||
<reuseForks>true</reuseForks>
|
||||
<systemProperties>
|
||||
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
|
||||
</systemProperties>
|
||||
|
|
|
@ -7,3 +7,4 @@ This module contains articles about Spring 5 OAuth Security
|
|||
- [Spring Security 5 – OAuth2 Login](https://www.baeldung.com/spring-security-5-oauth2-login)
|
||||
- [Extracting Principal and Authorities using Spring Security OAuth](https://www.baeldung.com/spring-security-oauth-principal-authorities-extractor)
|
||||
- [Customizing Authorization and Token Requests with Spring Security 5.1 Client](https://www.baeldung.com/spring-security-custom-oauth-requests)
|
||||
- [Social Login with Spring Security in a Jersey Application](https://www.baeldung.com/spring-security-social-login-jersey)
|
||||
|
|
|
@ -32,6 +32,10 @@
|
|||
<groupId>org.thymeleaf.extras</groupId>
|
||||
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jersey</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- oauth2 -->
|
||||
<dependency>
|
||||
|
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.jersey;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
@SpringBootApplication
|
||||
@PropertySource("classpath:jersey-application.properties")
|
||||
public class JerseyApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(JerseyApplication.class, args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.jersey;
|
||||
|
||||
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
|
||||
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
|
||||
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.SecurityContext;
|
||||
|
||||
@Path("/")
|
||||
public class JerseyResource {
|
||||
@GET
|
||||
@Path("login")
|
||||
@Produces(MediaType.TEXT_HTML)
|
||||
public String login() {
|
||||
return "Log in with <a href=\"/oauth2/authorization/github\">GitHub</a>";
|
||||
}
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.TEXT_PLAIN)
|
||||
public String home(@Context SecurityContext securityContext) {
|
||||
OAuth2AuthenticationToken authenticationToken = (OAuth2AuthenticationToken) securityContext.getUserPrincipal();
|
||||
OAuth2AuthenticatedPrincipal authenticatedPrincipal = authenticationToken.getPrincipal();
|
||||
String userName = authenticatedPrincipal.getAttribute("login");
|
||||
return "Hello " + userName;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.jersey;
|
||||
|
||||
import org.glassfish.jersey.server.ResourceConfig;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class RestConfig extends ResourceConfig {
|
||||
public RestConfig() {
|
||||
register(JerseyResource.class);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.jersey;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
|
||||
@Configuration
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.authorizeRequests()
|
||||
.antMatchers("/login")
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
.authenticated()
|
||||
.and()
|
||||
.oauth2Login()
|
||||
.loginPage("/login");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
server.port=8083
|
||||
spring.security.oauth2.client.registration.github.client-id=<your-client-id>
|
||||
spring.security.oauth2.client.registration.github.client-secret=<your-client-secret>
|
|
@ -0,0 +1,72 @@
|
|||
package com.baeldung.jersey;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.boot.web.server.LocalServerPort;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
import static org.springframework.http.MediaType.TEXT_HTML;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = RANDOM_PORT)
|
||||
@TestPropertySource(properties = "spring.security.oauth2.client.registration.github.client-id:test-id")
|
||||
public class JerseyResourceUnitTest {
|
||||
@Autowired
|
||||
private TestRestTemplate restTemplate;
|
||||
|
||||
@LocalServerPort
|
||||
private int port;
|
||||
|
||||
private String basePath;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
basePath = "http://localhost:" + port + "/";
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUserIsUnauthenticated_thenTheyAreRedirectedToLoginPage() {
|
||||
ResponseEntity<Object> response = restTemplate.getForEntity(basePath, Object.class);
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FOUND);
|
||||
assertThat(response.getBody()).isNull();
|
||||
|
||||
URI redirectLocation = response.getHeaders().getLocation();
|
||||
assertThat(redirectLocation).isNotNull();
|
||||
assertThat(redirectLocation.toString()).isEqualTo(basePath + "login");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUserAttemptsToLogin_thenAuthorizationPathIsReturned() {
|
||||
ResponseEntity<String> response = restTemplate.getForEntity(basePath + "login", String.class);
|
||||
assertThat(response.getHeaders().getContentType()).isEqualTo(TEXT_HTML);
|
||||
assertThat(response.getBody()).isEqualTo("Log in with <a href=\"/oauth2/authorization/github\">GitHub</a>");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUserAccessesAuthorizationEndpoint_thenTheyAresRedirectedToProvider() {
|
||||
ResponseEntity<String> response = restTemplate.getForEntity(basePath + "oauth2/authorization/github", String.class);
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FOUND);
|
||||
assertThat(response.getBody()).isNull();
|
||||
|
||||
URI redirectLocation = response.getHeaders().getLocation();
|
||||
assertThat(redirectLocation).isNotNull();
|
||||
assertThat(redirectLocation.getHost()).isEqualTo("github.com");
|
||||
assertThat(redirectLocation.getPath()).isEqualTo("/login/oauth/authorize");
|
||||
|
||||
String redirectionQuery = redirectLocation.getQuery();
|
||||
assertThat(redirectionQuery.contains("response_type=code"));
|
||||
assertThat(redirectionQuery.contains("client_id=test-id"));
|
||||
assertThat(redirectionQuery.contains("scope=read:user"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.inmemory;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
|
||||
//@Configuration
|
||||
public class InMemoryNoOpAuthWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.inMemoryAuthentication()
|
||||
.withUser("spring")
|
||||
.password("{noop}secret")
|
||||
.roles("USER");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests()
|
||||
.antMatchers("/private/**")
|
||||
.authenticated()
|
||||
.antMatchers("/public/**")
|
||||
.permitAll()
|
||||
.and()
|
||||
.httpBasic();
|
||||
}
|
||||
}
|
|
@ -8,3 +8,4 @@ This module contains articles about Spring 5 WebFlux
|
|||
- [How to Return 404 with Spring WebFlux](https://www.baeldung.com/spring-webflux-404)
|
||||
- [Spring WebClient Requests with Parameters](https://www.baeldung.com/webflux-webclient-parameters)
|
||||
- [RSocket Using Spring Boot](https://www.baeldung.com/spring-boot-rsocket)
|
||||
- [Spring MVC Async vs Spring WebFlux](https://www.baeldung.com/spring-mvc-async-vs-webflux)
|
||||
|
|
|
@ -9,3 +9,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
|||
|
||||
- [Liveness and Readiness Probes in Spring Boot](https://www.baeldung.com/spring-liveness-readiness-probes)
|
||||
- [Custom Information in Spring Boot Info Endpoint](https://www.baeldung.com/spring-boot-info-actuator-custom)
|
||||
- [Health Indicators in Spring Boot](https://www.baeldung.com/spring-boot-health-indicators)
|
||||
|
|
|
@ -11,3 +11,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
|||
- [Guide to ApplicationContextRunner in Spring Boot](https://www.baeldung.com/spring-boot-context-runner)
|
||||
- [A Guide to Spring Boot Configuration Metadata](https://www.baeldung.com/spring-boot-configuration-metadata)
|
||||
- [Display Auto-Configuration Report in Spring Boot](https://www.baeldung.com/spring-boot-auto-configuration-report)
|
||||
- [The Spring @ConditionalOnProperty Annotation](https://www.baeldung.com/spring-conditionalonproperty)
|
||||
|
|
|
@ -16,14 +16,6 @@
|
|||
<name>spring-boot-exceptions</name>
|
||||
<description>Demo project for working with Spring Boot exceptions</description>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>spring-boot-exceptions</finalName>
|
||||
<resources>
|
||||
|
@ -32,68 +24,6 @@
|
|||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<configuration>
|
||||
<delimiters>
|
||||
<delimiter>@</delimiter>
|
||||
</delimiters>
|
||||
<useDefaultDelimiters>false</useDefaultDelimiters>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>autoconfiguration</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*IntTest.java</exclude>
|
||||
</excludes>
|
||||
<includes>
|
||||
<include>**/AutoconfigurationTest.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<test.mime>json</test.mime>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<!-- The main class to start by executing java -jar -->
|
||||
<start-class>com.baeldung.intro.App</start-class>
|
||||
<spring-boot.version>2.2.3.RELEASE</spring-boot.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
|
@ -4,3 +4,4 @@ This module contains articles about Keycloak in Spring Boot projects.
|
|||
|
||||
## Relevant articles:
|
||||
- [A Quick Guide to Using Keycloak with Spring Boot](https://www.baeldung.com/spring-boot-keycloak)
|
||||
- [Custom User Attributes with Keycloak](https://www.baeldung.com/keycloak-custom-user-attributes)
|
||||
|
|
|
@ -6,4 +6,5 @@ This module contains articles about Spring Web MVC in Spring Boot projects.
|
|||
|
||||
- [Circular View Path Error](https://www.baeldung.com/spring-circular-view-path-error)
|
||||
- [Download an Image or a File with Spring MVC](https://www.baeldung.com/spring-controller-return-image-file)
|
||||
- [Spring MVC Async vs Spring WebFlux](https://www.baeldung.com/spring-mvc-async-vs-webflux)
|
||||
- More articles: [[prev -->]](/spring-boot-modules/spring-boot-mvc-2)
|
||||
|
|
|
@ -22,6 +22,10 @@
|
|||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.springvalidation;
|
||||
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||
|
||||
public class ServletInitializer extends SpringBootServletInitializer {
|
||||
|
||||
@Override
|
||||
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
|
||||
return application.sources(SpringValidationApplication.class);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.springvalidation;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class SpringValidationApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringValidationApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.springvalidation.controller;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.ui.ModelMap;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
|
||||
import com.baeldung.springvalidation.domain.UserAccount;
|
||||
import com.baeldung.springvalidation.interfaces.BasicInfo;
|
||||
|
||||
@Controller
|
||||
public class UserAccountController {
|
||||
|
||||
@GetMapping("/getUserForm")
|
||||
public String showUserForm(Model theModel) {
|
||||
UserAccount theUser = new UserAccount();
|
||||
theModel.addAttribute("useraccount", theUser);
|
||||
return "userHome";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/saveBasicInfo", method = RequestMethod.POST)
|
||||
public String saveBasicInfo(@Valid @ModelAttribute("useraccount") UserAccount useraccount, BindingResult result, ModelMap model) {
|
||||
if (result.hasErrors()) {
|
||||
return "error";
|
||||
}
|
||||
return "success";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/saveBasicInfoStep1", method = RequestMethod.POST)
|
||||
public String saveBasicInfoStep1(@Validated(BasicInfo.class) @ModelAttribute("useraccount") UserAccount useraccount, BindingResult result, ModelMap model) {
|
||||
if (result.hasErrors()) {
|
||||
return "error";
|
||||
}
|
||||
return "success";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,80 @@
|
|||
package com.baeldung.springvalidation.domain;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
import com.baeldung.springvalidation.interfaces.AdvanceInfo;
|
||||
import com.baeldung.springvalidation.interfaces.BasicInfo;
|
||||
|
||||
public class UserAccount {
|
||||
|
||||
@NotNull(groups = BasicInfo.class)
|
||||
@Size(min = 4, max = 15, groups = BasicInfo.class)
|
||||
private String password;
|
||||
|
||||
@NotBlank(groups = BasicInfo.class)
|
||||
private String name;
|
||||
|
||||
@Min(value = 18, message = "Age should not be less than 18", groups = AdvanceInfo.class)
|
||||
private int age;
|
||||
|
||||
@NotBlank(groups = AdvanceInfo.class)
|
||||
private String phone;
|
||||
|
||||
@Valid
|
||||
@NotNull(groups = AdvanceInfo.class)
|
||||
private UserAddress useraddress;
|
||||
|
||||
public UserAddress getUseraddress() {
|
||||
return useraddress;
|
||||
}
|
||||
|
||||
public void setUseraddress(UserAddress useraddress) {
|
||||
this.useraddress = useraddress;
|
||||
}
|
||||
|
||||
public UserAccount() {
|
||||
|
||||
}
|
||||
|
||||
public UserAccount(String email, String password, String name, int age) {
|
||||
this.password = password;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getPhone() {
|
||||
return phone;
|
||||
}
|
||||
|
||||
public void setPhone(String phone) {
|
||||
this.phone = phone;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.springvalidation.domain;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
public class UserAddress {
|
||||
|
||||
@NotBlank
|
||||
private String countryCode;
|
||||
|
||||
public String getCountryCode() {
|
||||
return countryCode;
|
||||
}
|
||||
|
||||
public void setCountryCode(String countryCode) {
|
||||
this.countryCode = countryCode;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
package com.baeldung.springvalidation.interfaces;
|
||||
|
||||
public interface AdvanceInfo {
|
||||
// validation group marker interface
|
||||
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
package com.baeldung.springvalidation.interfaces;
|
||||
|
||||
public interface BasicInfo {
|
||||
// validation group marker interface
|
||||
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
spring.mvc.view.prefix=/WEB-INF/views/
|
||||
spring.mvc.view.suffix=.html
|
|
@ -0,0 +1,10 @@
|
|||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>SpringValidation</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h3>Error!!!</h3>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,10 @@
|
|||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>SpringValidation</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h3>SUCCESS!!!</h3>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,57 @@
|
|||
package com.baeldung.springvalidation;
|
||||
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
@AutoConfigureMockMvc
|
||||
public class UserAccountUnitTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Test
|
||||
public void givenSaveBasicInfo_whenCorrectInput_thenSuccess() throws Exception {
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.post("/saveBasicInfo")
|
||||
.accept(MediaType.TEXT_HTML)
|
||||
.param("name", "test123")
|
||||
.param("password", "pass"))
|
||||
.andExpect(view().name("success"))
|
||||
.andExpect(status().isOk())
|
||||
.andDo(print());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSaveBasicInfoStep1_whenCorrectInput_thenSuccess() throws Exception {
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.post("/saveBasicInfoStep1")
|
||||
.accept(MediaType.TEXT_HTML)
|
||||
.param("name", "test123")
|
||||
.param("password", "pass"))
|
||||
.andExpect(view().name("success"))
|
||||
.andExpect(status().isOk())
|
||||
.andDo(print());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSaveBasicInfoStep1_whenIncorrectInput_thenError() throws Exception {
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.post("/saveBasicInfoStep1")
|
||||
.accept(MediaType.TEXT_HTML))
|
||||
// .param("name", "test123")
|
||||
// .param("password", "pass"))
|
||||
.andExpect(model().errorCount(2))
|
||||
// .andExpect(view().name("error"))
|
||||
.andExpect(status().isOk())
|
||||
.andDo(print());
|
||||
}
|
||||
|
||||
}
|
|
@ -6,4 +6,4 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [How to Define a Map in YAML for a POJO?](https://www.baeldung.com/yaml-map-pojo)
|
||||
|
||||
- [Using application.yml vs application.properties in Spring Boot](https://www.baeldung.com/spring-boot-yaml-vs-properties)
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant Articles:
|
||||
|
||||
- [Hiding Endpoints From Swagger Documentation in Spring Boot](https://www.baeldung.com/spring-swagger-hiding-endpoints)
|
|
@ -1,3 +1,4 @@
|
|||
|
||||
### Relevant Articles:
|
||||
- [A Quick Guide to Spring Cloud Consul](http://www.baeldung.com/spring-cloud-consul)
|
||||
- [Leadership Election With Consul](https://www.baeldung.com/consul-leadership-election)
|
||||
|
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.jsonparams.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.ViewResolver;
|
||||
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan(basePackages = { "com.baeldung.jsonparams" })
|
||||
public class JsonParamsConfig implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
|
||||
configurer.enable();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ViewResolver viewResolver() {
|
||||
InternalResourceViewResolver bean = new InternalResourceViewResolver();
|
||||
bean.setPrefix("/WEB-INF/");
|
||||
bean.setSuffix(".jsp");
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ObjectMapper objectMapper() {
|
||||
return new ObjectMapper();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.jsonparams.config;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRegistration;
|
||||
|
||||
import org.springframework.web.context.ContextLoaderListener;
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
import org.springframework.web.servlet.DispatcherServlet;
|
||||
|
||||
public class JsonParamsInit // implements WebApplicationInitializer
|
||||
{
|
||||
|
||||
//uncomment to run the product controller example
|
||||
//@Override
|
||||
public void onStartup(ServletContext sc) throws ServletException {
|
||||
AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
|
||||
root.register(JsonParamsConfig.class);
|
||||
root.setServletContext(sc);
|
||||
sc.addListener(new ContextLoaderListener(root));
|
||||
|
||||
DispatcherServlet dv = new DispatcherServlet(root);
|
||||
|
||||
ServletRegistration.Dynamic appServlet = sc.addServlet("jsonparams-mvc", dv);
|
||||
appServlet.setLoadOnStartup(1);
|
||||
appServlet.addMapping("/");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
package com.baeldung.jsonparams.controller;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.WebDataBinder;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.InitBinder;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import com.baeldung.jsonparams.model.Product;
|
||||
import com.baeldung.jsonparams.propertyeditor.ProductEditor;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/products")
|
||||
public class ProductController {
|
||||
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@Autowired
|
||||
public void setObjectMapper(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@InitBinder
|
||||
public void initBinder(WebDataBinder binder) {
|
||||
binder.registerCustomEditor(Product.class, new ProductEditor(objectMapper));
|
||||
}
|
||||
|
||||
@PostMapping("/create")
|
||||
@ResponseBody
|
||||
public Product createProduct(@RequestBody Product product) {
|
||||
// custom logic
|
||||
return product;
|
||||
}
|
||||
|
||||
@GetMapping("/get")
|
||||
@ResponseBody
|
||||
public Product getProduct(@RequestParam String product) throws JsonMappingException, JsonProcessingException {
|
||||
final Product prod = objectMapper.readValue(product, Product.class);
|
||||
return prod;
|
||||
}
|
||||
|
||||
@GetMapping("/get2")
|
||||
@ResponseBody
|
||||
public Product get2Product(@RequestParam Product product) {
|
||||
// custom logic
|
||||
return product;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.jsonparams.model;
|
||||
|
||||
public class Product {
|
||||
|
||||
private int id;
|
||||
private String name;
|
||||
private double price;
|
||||
|
||||
public Product() {
|
||||
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String nom) {
|
||||
this.name = nom;
|
||||
}
|
||||
|
||||
public double getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(double price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.jsonparams.propertyeditor;
|
||||
|
||||
import java.beans.PropertyEditorSupport;
|
||||
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.baeldung.jsonparams.model.Product;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class ProductEditor extends PropertyEditorSupport {
|
||||
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
public ProductEditor(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAsText(String text) throws IllegalArgumentException {
|
||||
if (StringUtils.isEmpty(text)) {
|
||||
setValue(null);
|
||||
} else {
|
||||
Product prod = new Product();
|
||||
try {
|
||||
prod = objectMapper.readValue(text, Product.class);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
setValue(prod);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,71 @@
|
|||
package com.baeldung.jsonparams;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
import com.baeldung.jsonparams.config.JsonParamsConfig;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = { JsonParamsConfig.class }, loader = AnnotationConfigWebContextLoader.class)
|
||||
public class JsonParamsIntegrationTest {
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext wac;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJsonIsPassedWithPost_thenResponseOK() throws Exception {
|
||||
|
||||
this.mockMvc.perform(post("/products/create").accept(MediaType.APPLICATION_JSON)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"id\": 1,\"name\": \"Asus Zenbook\",\"price\": 800}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value("1"))
|
||||
.andExpect(jsonPath("$.name").value("Asus Zenbook"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJsonIsPassedWithGet_thenResponseOK() throws Exception {
|
||||
|
||||
this.mockMvc.perform(get("/products/get").contentType(MediaType.APPLICATION_JSON)
|
||||
.queryParam("product", "{\"id\": 2,\"name\": \"HP EliteBook\",\"price\": 700}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value("2"))
|
||||
.andExpect(jsonPath("$.name").value("HP EliteBook"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJsonIsPassedWithGet2_thenResponseOK() throws Exception {
|
||||
|
||||
this.mockMvc.perform(get("/products/get2").contentType(MediaType.APPLICATION_JSON)
|
||||
.queryParam("product", "{\"id\": 3,\"name\": \"Dell G5 15\",\"price\": 1200}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value("3"))
|
||||
.andExpect(jsonPath("$.name").value("Dell G5 15"));
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -7,4 +7,4 @@ The "REST With Spring 2" Classes: http://bit.ly/restwithspring
|
|||
|
||||
### Relevant Articles:
|
||||
|
||||
|
||||
- [How to Turn Off Swagger-ui in Production](https://www.baeldung.com/swagger-ui-turn-off-in-production)
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue