Merge remote-tracking branch 'eugenp/master'
This commit is contained in:
commit
2bcc38ec52
|
@ -1,13 +1,9 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<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/maven-v4_0_0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
<groupId>com.mabsisa</groupId>
|
|
||||||
<artifactId>Twitter4J</artifactId>
|
<artifactId>Twitter4J</artifactId>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
<version>1.0-SNAPSHOT</version>
|
|
||||||
<name>Twitter4J</name>
|
<name>Twitter4J</name>
|
||||||
<url>http://maven.apache.org</url>
|
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
|
@ -23,27 +19,6 @@
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
|
||||||
<finalName>${project.artifactId}</finalName>
|
|
||||||
<resources>
|
|
||||||
<resource>
|
|
||||||
<directory>src/main/resources</directory>
|
|
||||||
</resource>
|
|
||||||
</resources>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
|
||||||
<version>${maven-surefire-plugin.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<excludes>
|
|
||||||
<exclude>**/ApplicationTest.java</exclude>
|
|
||||||
</excludes>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<twitter4j-stream.version>4.0.6</twitter4j-stream.version>
|
<twitter4j-stream.version>4.0.6</twitter4j-stream.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
|
@ -1,7 +1,6 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<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">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>activejdbc</artifactId>
|
<artifactId>activejdbc</artifactId>
|
||||||
<version>1.0-SNAPSHOT</version>
|
<version>1.0-SNAPSHOT</version>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
@ -79,55 +78,11 @@
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
|
||||||
<version>${maven-surefire-plugin.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<reportFormat>brief</reportFormat>
|
|
||||||
<trimStackTrace>true</trimStackTrace>
|
|
||||||
<useFile>false</useFile>
|
|
||||||
<includes>
|
|
||||||
<include>**/*Spec*.java</include>
|
|
||||||
<include>**/*Test*.java</include>
|
|
||||||
</includes>
|
|
||||||
<excludes>
|
|
||||||
<exclude>**/helpers/*</exclude>
|
|
||||||
<exclude>**/*$*</exclude>
|
|
||||||
</excludes>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<repositories>
|
|
||||||
<repository>
|
|
||||||
<id>snapshots1</id>
|
|
||||||
<name>JavaLite Snapshots1</name>
|
|
||||||
<url>http://repo.javalite.io/</url>
|
|
||||||
<snapshots>
|
|
||||||
<enabled>true</enabled>
|
|
||||||
<updatePolicy>always</updatePolicy>
|
|
||||||
<checksumPolicy>warn</checksumPolicy>
|
|
||||||
</snapshots>
|
|
||||||
</repository>
|
|
||||||
</repositories>
|
|
||||||
|
|
||||||
<pluginRepositories>
|
|
||||||
<pluginRepository>
|
|
||||||
<id>snapshots2</id>
|
|
||||||
<name>JavaLite Snapshots2</name>
|
|
||||||
<url>http://repo.javalite.io/</url>
|
|
||||||
<snapshots>
|
|
||||||
<enabled>true</enabled>
|
|
||||||
<updatePolicy>always</updatePolicy>
|
|
||||||
<checksumPolicy>warn</checksumPolicy>
|
|
||||||
</snapshots>
|
|
||||||
</pluginRepository>
|
|
||||||
</pluginRepositories>
|
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<activejdbc.version>1.4.13</activejdbc.version>
|
<activejdbc.version>2.0</activejdbc.version>
|
||||||
<environments>development.test,development</environments>
|
<environments>development.test,development</environments>
|
||||||
<mysql.connector.version>5.1.34</mysql.connector.version>
|
<mysql.connector.version>5.1.34</mysql.connector.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
|
@ -16,4 +16,8 @@ public class Employee extends Model {
|
||||||
set("created_by",createdBy);
|
set("created_by",createdBy);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getLastName() {
|
||||||
|
return getString("last_name");
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,4 +15,8 @@ public class Role extends Model {
|
||||||
set("role_name",role);
|
set("role_name",role);
|
||||||
set("created_by",createdBy);
|
set("created_by",createdBy);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getRoleName() {
|
||||||
|
return getString("role_name");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,7 +7,7 @@ import org.junit.Test;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class ActiveJDBCAppTest extends DBSpec
|
public class ActiveJDBCAppManualTest extends DBSpec
|
||||||
{
|
{
|
||||||
@Test
|
@Test
|
||||||
public void ifEmployeeCreated_thenIsValid() {
|
public void ifEmployeeCreated_thenIsValid() {
|
|
@ -0,0 +1 @@
|
||||||
|
/bin/
|
|
@ -0,0 +1,20 @@
|
||||||
|
package com.java.src;
|
||||||
|
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
|
public class RoundUpToHundred {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Scanner scanner = new Scanner(System.in);
|
||||||
|
double input = scanner.nextDouble();
|
||||||
|
scanner.close();
|
||||||
|
|
||||||
|
RoundUpToHundred.round(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
static long round(double input) {
|
||||||
|
long i = (long) Math.ceil(input);
|
||||||
|
return ((i + 99) / 100) * 100;
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,14 @@
|
||||||
|
package com.java.src;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class RoundUpToHundredTest {
|
||||||
|
@Test
|
||||||
|
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
|
||||||
|
assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
|
||||||
|
assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
|
||||||
|
assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
|
||||||
|
}
|
||||||
|
}
|
|
@ -3,7 +3,6 @@
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
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">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>apache-shiro</artifactId>
|
<artifactId>apache-shiro</artifactId>
|
||||||
<version>1.0-SNAPSHOT</version>
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
|
||||||
|
@ -36,13 +35,11 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>jcl-over-slf4j</artifactId>
|
<artifactId>jcl-over-slf4j</artifactId>
|
||||||
<version>${slf4j-version}</version>
|
|
||||||
<scope>runtime</scope>
|
<scope>runtime</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>slf4j-log4j12</artifactId>
|
<artifactId>slf4j-log4j12</artifactId>
|
||||||
<version>${slf4j-version}</version>
|
|
||||||
<scope>runtime</scope>
|
<scope>runtime</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
|
@ -53,26 +50,9 @@
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
|
||||||
<version>${maven-compiler-plugin.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<source>${java.version}</source>
|
|
||||||
<target>${java.version}</target>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<apache-shiro-core-version>1.4.0</apache-shiro-core-version>
|
<apache-shiro-core-version>1.4.0</apache-shiro-core-version>
|
||||||
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
|
||||||
<java.version>1.8</java.version>
|
|
||||||
<log4j-version>1.2.17</log4j-version>
|
<log4j-version>1.2.17</log4j-version>
|
||||||
<slf4j-version>1.7.25</slf4j-version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -42,14 +42,6 @@
|
||||||
</archive>
|
</archive>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
|
||||||
<version>${maven-surefire-plugin.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<argLine>-javaagent:"C:\asm-1.0.jar"</argLine>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
|
|
@ -2,12 +2,10 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<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">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>cas-secured-app</artifactId>
|
<artifactId>cas-secured-app</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
<name>cas-secured-app</name>
|
<name>cas-secured-app</name>
|
||||||
<description>Demo project for Spring Boot</description>
|
<description>Demo project for CAS</description>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<artifactId>parent-boot-1</artifactId>
|
<artifactId>parent-boot-1</artifactId>
|
||||||
|
@ -60,10 +58,4 @@
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
|
||||||
<java.version>1.8</java.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -2,11 +2,17 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<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 ">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>cas-server</artifactId>
|
<artifactId>cas-server</artifactId>
|
||||||
<packaging>war</packaging>
|
<packaging>war</packaging>
|
||||||
<version>1.0</version>
|
<version>1.0</version>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<artifactId>parent-boot-1</artifactId>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../../parent-boot-1</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apereo.cas</groupId>
|
<groupId>org.apereo.cas</groupId>
|
||||||
|
@ -39,7 +45,6 @@
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
<version>${springboot.version}</version>
|
|
||||||
<configuration>
|
<configuration>
|
||||||
<mainClass>${mainClassName}</mainClass>
|
<mainClass>${mainClassName}</mainClass>
|
||||||
<addResources>true</addResources>
|
<addResources>true</addResources>
|
||||||
|
@ -74,42 +79,10 @@
|
||||||
</overlays>
|
</overlays>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
|
||||||
<version>${maven-compiler-plugin.version}</version>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
</plugins>
|
||||||
<finalName>cas</finalName>
|
<finalName>cas</finalName>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<repositories>
|
|
||||||
<repository>
|
|
||||||
<id>sonatype-releases</id>
|
|
||||||
<url>http://oss.sonatype.org/content/repositories/releases/</url>
|
|
||||||
<snapshots>
|
|
||||||
<enabled>false</enabled>
|
|
||||||
</snapshots>
|
|
||||||
<releases>
|
|
||||||
<enabled>true</enabled>
|
|
||||||
</releases>
|
|
||||||
</repository>
|
|
||||||
<repository>
|
|
||||||
<id>sonatype-snapshots</id>
|
|
||||||
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
|
|
||||||
<snapshots>
|
|
||||||
<enabled>true</enabled>
|
|
||||||
</snapshots>
|
|
||||||
<releases>
|
|
||||||
<enabled>false</enabled>
|
|
||||||
</releases>
|
|
||||||
</repository>
|
|
||||||
<repository>
|
|
||||||
<id>shibboleth-releases</id>
|
|
||||||
<url>https://build.shibboleth.net/nexus/content/repositories/releases</url>
|
|
||||||
</repository>
|
|
||||||
</repositories>
|
|
||||||
|
|
||||||
<profiles>
|
<profiles>
|
||||||
<profile>
|
<profile>
|
||||||
<activation>
|
<activation>
|
||||||
|
@ -214,8 +187,7 @@
|
||||||
</profiles>
|
</profiles>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<cas.version>5.3.0-SNAPSHOT</cas.version>
|
<cas.version>5.3.3</cas.version>
|
||||||
<springboot.version>1.5.13.RELEASE</springboot.version>
|
|
||||||
<!-- app.server could be -jetty, -undertow, -tomcat, or blank if you plan to provide appserver -->
|
<!-- app.server could be -jetty, -undertow, -tomcat, or blank if you plan to provide appserver -->
|
||||||
<app.server>-tomcat</app.server>
|
<app.server>-tomcat</app.server>
|
||||||
|
|
||||||
|
@ -223,12 +195,10 @@
|
||||||
<isExecutable>false</isExecutable>
|
<isExecutable>false</isExecutable>
|
||||||
<manifestFileToUse>${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF</manifestFileToUse>
|
<manifestFileToUse>${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF</manifestFileToUse>
|
||||||
|
|
||||||
<maven.compiler.source>1.8</maven.compiler.source>
|
|
||||||
<maven.compiler.target>1.8</maven.compiler.target>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<wrapper-maven-plugin.version>0.0.4</wrapper-maven-plugin.version>
|
<wrapper-maven-plugin.version>0.0.4</wrapper-maven-plugin.version>
|
||||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||||
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
|
||||||
|
|
||||||
<echo-maven-plugin.version>0.3.0</echo-maven-plugin.version>
|
<echo-maven-plugin.version>0.3.0</echo-maven-plugin.version>
|
||||||
<pgpverify-maven-plugin.version>1.1.0</pgpverify-maven-plugin.version>
|
<pgpverify-maven-plugin.version>1.1.0</pgpverify-maven-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
|
@ -63,6 +63,12 @@
|
||||||
<artifactId>jmh-generator-annprocess</artifactId>
|
<artifactId>jmh-generator-annprocess</artifactId>
|
||||||
<version>${openjdk.jmh.version}</version>
|
<version>${openjdk.jmh.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-exec</artifactId>
|
||||||
|
<version>1.3</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,39 @@
|
||||||
|
package com.baeldung.combiningcollections;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.ArrayUtils;
|
||||||
|
|
||||||
|
import com.google.common.collect.ObjectArrays;
|
||||||
|
|
||||||
|
public class CombiningArrays {
|
||||||
|
|
||||||
|
public static Object[] usingNativeJava(Object[] first, Object[] second) {
|
||||||
|
Object[] combined = new Object[first.length + second.length];
|
||||||
|
System.arraycopy(first, 0, combined, 0, first.length);
|
||||||
|
System.arraycopy(second, 0, combined, first.length, second.length);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Object[] usingJava8ObjectStream(Object[] first, Object[] second) {
|
||||||
|
Object[] combined = Stream.concat(Arrays.stream(first), Arrays.stream(second)).toArray();
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Object[] usingJava8FlatMaps(Object[] first, Object[] second) {
|
||||||
|
Object[] combined = Stream.of(first, second).flatMap(Stream::of).toArray(String[]::new);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Object[] usingApacheCommons(Object[] first, Object[] second) {
|
||||||
|
Object[] combined = ArrayUtils.addAll(first, second);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Object[] usingGuava(Object[] first, Object[] second) {
|
||||||
|
Object [] combined = ObjectArrays.concat(first, second, Object.class);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,46 @@
|
||||||
|
package com.baeldung.combiningcollections;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.apache.commons.collections4.ListUtils;
|
||||||
|
|
||||||
|
import com.google.common.collect.Iterables;
|
||||||
|
import com.google.common.collect.Lists;
|
||||||
|
|
||||||
|
public class CombiningLists {
|
||||||
|
|
||||||
|
public static List<Object> usingNativeJava(List<Object> first, List<Object> second) {
|
||||||
|
List<Object> combined = new ArrayList<>();
|
||||||
|
combined.addAll(first);
|
||||||
|
combined.addAll(second);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<Object> usingJava8ObjectStream(List<Object> first, List<Object> second) {
|
||||||
|
List<Object> combined = Stream.concat(first.stream(), second.stream()).collect(Collectors.toList());
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<Object> usingJava8FlatMaps(List<Object> first, List<Object> second) {
|
||||||
|
List<Object> combined = Stream.of(first, second).flatMap(Collection::stream).collect(Collectors.toList());
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<Object> usingApacheCommons(List<Object> first, List<Object> second) {
|
||||||
|
List<Object> combined = ListUtils.union(first, second);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<Object> usingGuava(List<Object> first, List<Object> second) {
|
||||||
|
Iterable<Object> combinedIterables = Iterables.unmodifiableIterable(
|
||||||
|
Iterables.concat(first, second));
|
||||||
|
|
||||||
|
List<Object> combined = Lists.newArrayList(combinedIterables);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,47 @@
|
||||||
|
package com.baeldung.combiningcollections;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.apache.commons.exec.util.MapUtils;
|
||||||
|
|
||||||
|
import com.google.common.collect.ImmutableMap;
|
||||||
|
|
||||||
|
public class CombiningMaps {
|
||||||
|
|
||||||
|
public static Map<String, String> usingPlainJava(Map<String, String> first, Map<String, String> second) {
|
||||||
|
Map<String, String> combined = new HashMap<>();
|
||||||
|
combined.putAll(first);
|
||||||
|
combined.putAll(second);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Map<String, String> usingJava8ForEach(Map<String, String> first, Map<String, String> second) {
|
||||||
|
second.forEach((key, value) -> first.merge(key, value, String::concat));
|
||||||
|
return first;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Map<String, String> usingJava8FlatMaps(Map<String, String> first, Map<String, String> second) {
|
||||||
|
Map<String, String> combined = Stream.of(first, second).map(Map::entrySet).flatMap(Collection::stream)
|
||||||
|
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, String::concat));
|
||||||
|
return combined;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Map<String, String> usingApacheCommons(Map<String, String> first, Map<String, String> second) {
|
||||||
|
Map<String, String> combined = MapUtils.merge(first, second);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Map<String, String> usingGuava(Map<String, String> first, Map<String, String> second) {
|
||||||
|
Map<String, String> combined = ImmutableMap.<String, String>builder()
|
||||||
|
.putAll(first)
|
||||||
|
.putAll(second)
|
||||||
|
.build();
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,42 @@
|
||||||
|
package com.baeldung.combiningcollections;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.apache.commons.collections4.SetUtils;
|
||||||
|
|
||||||
|
import com.google.common.collect.Sets;
|
||||||
|
|
||||||
|
public class CombiningSets {
|
||||||
|
|
||||||
|
public static Set<Object> usingNativeJava(Set<Object> first, Set<Object> second) {
|
||||||
|
Set<Object> combined = new HashSet<>();
|
||||||
|
combined.addAll(first);
|
||||||
|
combined.addAll(second);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Set<Object> usingJava8ObjectStream(Set<Object> first, Set<Object> second) {
|
||||||
|
Set<Object> combined = Stream.concat(first.stream(), second.stream()).collect(Collectors.toSet());
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Set<Object> usingJava8FlatMaps(Set<Object> first, Set<Object> second) {
|
||||||
|
Set<Object> combined = Stream.of(first, second).flatMap(Collection::stream).collect(Collectors.toSet());
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Set<Object> usingApacheCommons(Set<Object> first, Set<Object> second) {
|
||||||
|
Set<Object> combined = SetUtils.union(first, second);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Set<Object> usingGuava(Set<Object> first, Set<Object> second) {
|
||||||
|
Set<Object> combined = Sets.union(first, second);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -44,4 +44,12 @@ public class Employee {
|
||||||
result = 31 * result + name.hashCode();
|
result = 31 * result + name.hashCode();
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Employee{" +
|
||||||
|
"id=" + id +
|
||||||
|
", name='" + name + '\'' +
|
||||||
|
'}';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,60 @@
|
||||||
|
package com.baeldung.sort;
|
||||||
|
|
||||||
|
public class Employee implements Comparable<Employee> {
|
||||||
|
|
||||||
|
private Long id;
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
public Employee(Long id, String name) {
|
||||||
|
this.name = name;
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) return true;
|
||||||
|
if (o == null || getClass() != o.getClass()) return false;
|
||||||
|
|
||||||
|
Employee employee = (Employee) o;
|
||||||
|
|
||||||
|
if (!id.equals(employee.id)) return false;
|
||||||
|
return name.equals(employee.name);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
int result = id.hashCode();
|
||||||
|
result = 31 * result + name.hashCode();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Employee{" +
|
||||||
|
"id=" + id +
|
||||||
|
", name='" + name + '\'' +
|
||||||
|
'}';
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int compareTo(Employee employee) {
|
||||||
|
return (int)(this.id - employee.getId());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,104 @@
|
||||||
|
package com.baeldung.sort;
|
||||||
|
|
||||||
|
import com.google.common.base.Functions;
|
||||||
|
import com.google.common.collect.ImmutableSortedMap;
|
||||||
|
import com.google.common.collect.Lists;
|
||||||
|
import com.google.common.collect.Ordering;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
public class SortHashMap {
|
||||||
|
|
||||||
|
private static Map<String, Employee> map = new HashMap<>();
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
initialize();
|
||||||
|
|
||||||
|
treeMapSortByKey();
|
||||||
|
|
||||||
|
arrayListSortByValue();
|
||||||
|
arrayListSortByKey();
|
||||||
|
|
||||||
|
sortStream();
|
||||||
|
|
||||||
|
sortGuava();
|
||||||
|
|
||||||
|
addDuplicates();
|
||||||
|
|
||||||
|
treeSetByKey();
|
||||||
|
treeSetByValue();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void sortGuava() {
|
||||||
|
final Ordering naturalOrdering =
|
||||||
|
Ordering.natural().onResultOf(Functions.forMap(map, null));
|
||||||
|
|
||||||
|
System.out.println(ImmutableSortedMap.copyOf(map, naturalOrdering));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void sortStream() {
|
||||||
|
map.entrySet().stream()
|
||||||
|
.sorted(Map.Entry.<String, Employee>comparingByKey().reversed())
|
||||||
|
.forEach(System.out::println);
|
||||||
|
|
||||||
|
Map<String, Employee> result = map.entrySet().stream()
|
||||||
|
.sorted(Map.Entry.comparingByValue())
|
||||||
|
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
|
||||||
|
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
|
||||||
|
|
||||||
|
result.entrySet().forEach(System.out::println);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void treeSetByValue() {
|
||||||
|
SortedSet<Employee> values = new TreeSet<>(map.values());
|
||||||
|
System.out.println(values);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void treeSetByKey() {
|
||||||
|
SortedSet<String> keysSet = new TreeSet<>(map.keySet());
|
||||||
|
System.out.println(keysSet);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void treeMapSortByKey() {
|
||||||
|
TreeMap<String, Employee> sorted = new TreeMap<>(map);
|
||||||
|
sorted.putAll(map);
|
||||||
|
|
||||||
|
sorted.entrySet().forEach(System.out::println);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void arrayListSortByValue() {
|
||||||
|
List<Employee> employeeById = new ArrayList<>(map.values());
|
||||||
|
|
||||||
|
Collections.sort(employeeById);
|
||||||
|
|
||||||
|
System.out.println(employeeById);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void arrayListSortByKey() {
|
||||||
|
List<String> employeeByKey = new ArrayList<>(map.keySet());
|
||||||
|
Collections.sort(employeeByKey);
|
||||||
|
System.out.println(employeeByKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void initialize() {
|
||||||
|
Employee employee1 = new Employee(1L, "Mher");
|
||||||
|
map.put(employee1.getName(), employee1);
|
||||||
|
Employee employee2 = new Employee(22L, "Annie");
|
||||||
|
map.put(employee2.getName(), employee2);
|
||||||
|
Employee employee3 = new Employee(8L, "John");
|
||||||
|
map.put(employee3.getName(), employee3);
|
||||||
|
Employee employee4 = new Employee(2L, "George");
|
||||||
|
map.put(employee4.getName(), employee4);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void addDuplicates() {
|
||||||
|
Employee employee5 = new Employee(1L, "Mher");
|
||||||
|
map.put(employee5.getName(), employee5);
|
||||||
|
Employee employee6 = new Employee(22L, "Annie");
|
||||||
|
map.put(employee6.getName(), employee6);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,52 @@
|
||||||
|
package com.baeldung.combiningcollections;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class CombiningArraysUnitTest {
|
||||||
|
private static final String first[] = {
|
||||||
|
"One",
|
||||||
|
"Two",
|
||||||
|
"Three"
|
||||||
|
};
|
||||||
|
|
||||||
|
private static final String second[] = {
|
||||||
|
"Four",
|
||||||
|
"Five",
|
||||||
|
"Six"
|
||||||
|
};
|
||||||
|
|
||||||
|
private static final String expected[] = {
|
||||||
|
"One",
|
||||||
|
"Two",
|
||||||
|
"Three",
|
||||||
|
"Four",
|
||||||
|
"Five",
|
||||||
|
"Six"
|
||||||
|
};
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoArrays_whenUsingNativeJava_thenArraysCombined() {
|
||||||
|
assertArrayEquals(expected, CombiningArrays.usingNativeJava(first, second));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoArrays_whenUsingObjectStreams_thenArraysCombined() {
|
||||||
|
assertArrayEquals(expected, CombiningArrays.usingJava8ObjectStream(first, second));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoArrays_whenUsingFlatMaps_thenArraysCombined() {
|
||||||
|
assertArrayEquals(expected, CombiningArrays.usingJava8FlatMaps(first, second));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoArrays_whenUsingApacheCommons_thenArraysCombined() {
|
||||||
|
assertArrayEquals(expected, CombiningArrays.usingApacheCommons(first, second));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoArrays_whenUsingGuava_thenArraysCombined() {
|
||||||
|
assertArrayEquals(expected, CombiningArrays.usingGuava(first, second));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,57 @@
|
||||||
|
package com.baeldung.combiningcollections;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class CombiningListsUnitTest {
|
||||||
|
private static final List<Object> first = Arrays.asList(new Object[]{
|
||||||
|
"One",
|
||||||
|
"Two",
|
||||||
|
"Three"
|
||||||
|
});
|
||||||
|
|
||||||
|
private static final List<Object> second = Arrays.asList(new Object[]{
|
||||||
|
"Four",
|
||||||
|
"Five",
|
||||||
|
"Six"
|
||||||
|
});
|
||||||
|
|
||||||
|
private static final List<Object> expected = Arrays.asList(new Object[]{
|
||||||
|
"One",
|
||||||
|
"Two",
|
||||||
|
"Three",
|
||||||
|
"Four",
|
||||||
|
"Five",
|
||||||
|
"Six"
|
||||||
|
});
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenUsingNativeJava_thenArraysCombined() {
|
||||||
|
assertThat(CombiningLists.usingNativeJava(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenUsingObjectStreams_thenArraysCombined() {
|
||||||
|
assertThat(CombiningLists.usingJava8ObjectStream(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenUsingFlatMaps_thenArraysCombined() {
|
||||||
|
assertThat(CombiningLists.usingJava8FlatMaps(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenUsingApacheCommons_thenArraysCombined() {
|
||||||
|
assertThat(CombiningLists.usingApacheCommons(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenUsingGuava_thenArraysCombined() {
|
||||||
|
assertThat(CombiningLists.usingGuava(first, second), is(expected));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,54 @@
|
||||||
|
package com.baeldung.combiningcollections;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class CombiningMapsUnitTest {
|
||||||
|
private static final Map<String, String> first = new HashMap<>();
|
||||||
|
private static final Map<String, String> second = new HashMap<>();
|
||||||
|
private static Map<String, String> expected = new HashMap<>();
|
||||||
|
|
||||||
|
static {
|
||||||
|
first.put("one", "first String");
|
||||||
|
first.put("two", "second String");
|
||||||
|
|
||||||
|
second.put("three", "third String");
|
||||||
|
second.put("four", "fourth String");
|
||||||
|
|
||||||
|
expected.put("one", "first String");
|
||||||
|
expected.put("two", "second String");
|
||||||
|
expected.put("three", "third String");
|
||||||
|
expected.put("four", "fourth String");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoMaps_whenUsingNativeJava_thenMapsCombined() {
|
||||||
|
assertThat(CombiningMaps.usingPlainJava(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoMaps_whenUsingForEach_thenMapsCombined() {
|
||||||
|
assertThat(CombiningMaps.usingJava8ForEach(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoMaps_whenUsingFlatMaps_thenMapsCombined() {
|
||||||
|
assertThat(CombiningMaps.usingJava8FlatMaps(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoMaps_whenUsingApacheCommons_thenMapsCombined() {
|
||||||
|
assertThat(CombiningMaps.usingApacheCommons(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoMaps_whenUsingGuava_thenMapsCombined() {
|
||||||
|
assertThat(CombiningMaps.usingGuava(first, second), is(expected));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,45 @@
|
||||||
|
|
||||||
|
package com.baeldung.combiningcollections;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class CombiningSetsUnitTest {
|
||||||
|
private static final Set<Object> first = new HashSet<Object>(Arrays.asList(new Object[] { "One", "Two", "Three" }));
|
||||||
|
|
||||||
|
private static final Set<Object> second = new HashSet<Object>(Arrays.asList(new Object[] { "Four", "Five", "Six" }));
|
||||||
|
|
||||||
|
private static final Set<Object> expected = new HashSet<Object>(Arrays
|
||||||
|
.asList(new Object[] { "One", "Two", "Three", "Four", "Five", "Six" }));
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoSets_whenUsingNativeJava_thenArraysCombined() {
|
||||||
|
assertThat(CombiningSets.usingNativeJava(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoSets_whenUsingObjectStreams_thenArraysCombined() {
|
||||||
|
assertThat(CombiningSets.usingJava8ObjectStream(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoSets_whenUsingFlatMaps_thenArraysCombined() {
|
||||||
|
assertThat(CombiningSets.usingJava8FlatMaps(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoSets_whenUsingApacheCommons_thenArraysCombined() {
|
||||||
|
assertThat(CombiningSets.usingApacheCommons(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoSets_whenUsingGuava_thenArraysCombined() {
|
||||||
|
assertThat(CombiningSets.usingGuava(first, second), is(expected));
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,7 +1,6 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<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">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>core-java-io</artifactId>
|
<artifactId>core-java-io</artifactId>
|
||||||
<version>0.1.0-SNAPSHOT</version>
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
@ -166,36 +165,6 @@
|
||||||
</resource>
|
</resource>
|
||||||
</resources>
|
</resources>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
|
||||||
<configuration>
|
|
||||||
<excludes>
|
|
||||||
<exclude>**/*LiveTest.java</exclude>
|
|
||||||
<exclude>**/*IntegrationTest.java</exclude>
|
|
||||||
<exclude>**/*IntTest.java</exclude>
|
|
||||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
|
||||||
<exclude>**/*ManualTest.java</exclude>
|
|
||||||
</excludes>
|
|
||||||
<testFailureIgnore>true</testFailureIgnore>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
|
||||||
<version>${spring-boot-maven-plugin.version}</version>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<goals>
|
|
||||||
<goal>repackage</goal>
|
|
||||||
</goals>
|
|
||||||
<configuration>
|
|
||||||
<classifier>spring-boot</classifier>
|
|
||||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.codehaus.mojo</groupId>
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
<artifactId>exec-maven-plugin</artifactId>
|
<artifactId>exec-maven-plugin</artifactId>
|
||||||
|
@ -229,32 +198,6 @@
|
||||||
<id>integration</id>
|
<id>integration</id>
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<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>**/*ManualTest.java</exclude>
|
|
||||||
</excludes>
|
|
||||||
<includes>
|
|
||||||
<include>**/*IntegrationTest.java</include>
|
|
||||||
<include>**/*IntTest.java</include>
|
|
||||||
</includes>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
<configuration>
|
|
||||||
<systemPropertyVariables>
|
|
||||||
<test.mime>json</test.mime>
|
|
||||||
</systemPropertyVariables>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.codehaus.mojo</groupId>
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
<artifactId>exec-maven-plugin</artifactId>
|
<artifactId>exec-maven-plugin</artifactId>
|
||||||
|
@ -310,14 +253,11 @@
|
||||||
<avaitility.version>1.7.0</avaitility.version>
|
<avaitility.version>1.7.0</avaitility.version>
|
||||||
|
|
||||||
<!-- maven plugins -->
|
<!-- maven plugins -->
|
||||||
<maven.compiler.source>1.8</maven.compiler.source>
|
|
||||||
<maven.compiler.target>1.8</maven.compiler.target>
|
|
||||||
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
||||||
<hsqldb.version>2.4.0</hsqldb.version>
|
<hsqldb.version>2.4.0</hsqldb.version>
|
||||||
<esapi.version>2.1.0.1</esapi.version>
|
<esapi.version>2.1.0.1</esapi.version>
|
||||||
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
|
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
|
||||||
<async-http-client.version>2.4.5</async-http-client.version>
|
<async-http-client.version>2.4.5</async-http-client.version>
|
||||||
<spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -24,6 +24,13 @@ public class ZipDirectory {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (fileToZip.isDirectory()) {
|
if (fileToZip.isDirectory()) {
|
||||||
|
if (fileName.endsWith("/")) {
|
||||||
|
zipOut.putNextEntry(new ZipEntry(fileName));
|
||||||
|
zipOut.closeEntry();
|
||||||
|
} else {
|
||||||
|
zipOut.putNextEntry(new ZipEntry(fileName + "/"));
|
||||||
|
zipOut.closeEntry();
|
||||||
|
}
|
||||||
final File[] children = fileToZip.listFiles();
|
final File[] children = fileToZip.listFiles();
|
||||||
for (final File childFile : children) {
|
for (final File childFile : children) {
|
||||||
zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
|
zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
package com.baeldung.file;
|
package com.baeldung.file;
|
||||||
|
|
||||||
import org.apache.commons.io.FileUtils;
|
import org.apache.commons.io.FileUtils;
|
||||||
|
import org.apache.commons.io.IOUtils;
|
||||||
import org.hamcrest.CoreMatchers;
|
import org.hamcrest.CoreMatchers;
|
||||||
import org.hamcrest.Matchers;
|
import org.hamcrest.Matchers;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
@ -120,4 +121,14 @@ public class FileOperationsManualTest {
|
||||||
|
|
||||||
return resultStringBuilder.toString();
|
return resultStringBuilder.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFileName_whenUsingIOUtils_thenFileData() throws IOException {
|
||||||
|
String expectedData = "This is a content of the file";
|
||||||
|
|
||||||
|
FileInputStream fis = new FileInputStream("src/test/resources/fileToRead.txt");
|
||||||
|
String data = IOUtils.toString(fis, "UTF-8");
|
||||||
|
|
||||||
|
assertEquals(expectedData, data.trim());
|
||||||
|
}
|
||||||
}
|
}
|
|
@ -9,7 +9,7 @@ import java.nio.file.Paths;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class SymLinkExampleUnitTest {
|
public class SymLinkExampleManualTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingFiles_thenCreateSymbolicLink() throws IOException {
|
public void whenUsingFiles_thenCreateSymbolicLink() throws IOException {
|
|
@ -0,0 +1,40 @@
|
||||||
|
package com.baeldung.doubles;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
public class SplitFloatingPointNumbers {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
double doubleNumber = 24.04;
|
||||||
|
splitUsingFloatingTypes(doubleNumber);
|
||||||
|
splitUsingString(doubleNumber);
|
||||||
|
splitUsingBigDecimal(doubleNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void splitUsingFloatingTypes(double doubleNumber) {
|
||||||
|
System.out.println("Using Floating Point Arithmetics:");
|
||||||
|
int intPart = (int) doubleNumber;
|
||||||
|
System.out.println("Double Number: "+doubleNumber);
|
||||||
|
System.out.println("Integer Part: "+ intPart);
|
||||||
|
System.out.println("Decimal Part: "+ (doubleNumber - intPart));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void splitUsingString(double doubleNumber) {
|
||||||
|
System.out.println("Using String Operations:");
|
||||||
|
String doubleAsString = String.valueOf(doubleNumber);
|
||||||
|
int indexOfDecimal = doubleAsString.indexOf(".");
|
||||||
|
System.out.println("Double Number: "+doubleNumber);
|
||||||
|
System.out.println("Integer Part: "+ doubleAsString.substring(0, indexOfDecimal));
|
||||||
|
System.out.println("Decimal Part: "+ doubleAsString.substring(indexOfDecimal));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void splitUsingBigDecimal(double doubleNumber) {
|
||||||
|
System.out.println("Using BigDecimal Operations:");
|
||||||
|
BigDecimal bigDecimal = new BigDecimal(String.valueOf(doubleNumber));
|
||||||
|
int intValue = bigDecimal.intValue();
|
||||||
|
System.out.println("Double Number: "+bigDecimal.toPlainString());
|
||||||
|
System.out.println("Integer Part: "+intValue);
|
||||||
|
System.out.println("Decimal Part: "+bigDecimal.subtract(new BigDecimal(intValue)).toPlainString());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,25 @@
|
||||||
|
package com.baeldung.heapdump;
|
||||||
|
|
||||||
|
import com.sun.management.HotSpotDiagnosticMXBean;
|
||||||
|
|
||||||
|
import javax.management.MBeanServer;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.lang.management.ManagementFactory;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
|
||||||
|
public class HeapDump {
|
||||||
|
|
||||||
|
public static void dumpHeap(String filePath, boolean live) throws IOException {
|
||||||
|
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
|
||||||
|
HotSpotDiagnosticMXBean mxBean = ManagementFactory.newPlatformMXBeanProxy(
|
||||||
|
server, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class);
|
||||||
|
mxBean.dumpHeap(filePath, live);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws IOException {
|
||||||
|
String file = Paths.get("dump.hprof").toFile().getPath();
|
||||||
|
|
||||||
|
dumpHeap(file, true);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,149 @@
|
||||||
|
package com.baeldung.passwordhashing;
|
||||||
|
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.security.spec.InvalidKeySpecException;
|
||||||
|
import java.security.spec.KeySpec;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import javax.crypto.SecretKeyFactory;
|
||||||
|
import javax.crypto.spec.PBEKeySpec;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hash passwords for storage, and test passwords against password tokens.
|
||||||
|
*
|
||||||
|
* Instances of this class can be used concurrently by multiple threads.
|
||||||
|
*
|
||||||
|
* @author erickson
|
||||||
|
* @see <a href="http://stackoverflow.com/a/2861125/3474">StackOverflow</a>
|
||||||
|
*/
|
||||||
|
public final class PBKDF2Hasher
|
||||||
|
{
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Each token produced by this class uses this identifier as a prefix.
|
||||||
|
*/
|
||||||
|
public static final String ID = "$31$";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The minimum recommended cost, used by default
|
||||||
|
*/
|
||||||
|
public static final int DEFAULT_COST = 16;
|
||||||
|
|
||||||
|
private static final String ALGORITHM = "PBKDF2WithHmacSHA1";
|
||||||
|
|
||||||
|
private static final int SIZE = 128;
|
||||||
|
|
||||||
|
private static final Pattern layout = Pattern.compile("\\$31\\$(\\d\\d?)\\$(.{43})");
|
||||||
|
|
||||||
|
private final SecureRandom random;
|
||||||
|
|
||||||
|
private final int cost;
|
||||||
|
|
||||||
|
public PBKDF2Hasher()
|
||||||
|
{
|
||||||
|
this(DEFAULT_COST);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a password manager with a specified cost
|
||||||
|
*
|
||||||
|
* @param cost the exponential computational cost of hashing a password, 0 to 30
|
||||||
|
*/
|
||||||
|
public PBKDF2Hasher(int cost)
|
||||||
|
{
|
||||||
|
iterations(cost); /* Validate cost */
|
||||||
|
this.cost = cost;
|
||||||
|
this.random = new SecureRandom();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int iterations(int cost)
|
||||||
|
{
|
||||||
|
if ((cost < 0) || (cost > 30))
|
||||||
|
throw new IllegalArgumentException("cost: " + cost);
|
||||||
|
return 1 << cost;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hash a password for storage.
|
||||||
|
*
|
||||||
|
* @return a secure authentication token to be stored for later authentication
|
||||||
|
*/
|
||||||
|
public String hash(char[] password)
|
||||||
|
{
|
||||||
|
byte[] salt = new byte[SIZE / 8];
|
||||||
|
random.nextBytes(salt);
|
||||||
|
byte[] dk = pbkdf2(password, salt, 1 << cost);
|
||||||
|
byte[] hash = new byte[salt.length + dk.length];
|
||||||
|
System.arraycopy(salt, 0, hash, 0, salt.length);
|
||||||
|
System.arraycopy(dk, 0, hash, salt.length, dk.length);
|
||||||
|
Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding();
|
||||||
|
return ID + cost + '$' + enc.encodeToString(hash);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authenticate with a password and a stored password token.
|
||||||
|
*
|
||||||
|
* @return true if the password and token match
|
||||||
|
*/
|
||||||
|
public boolean checkPassword(char[] password, String token)
|
||||||
|
{
|
||||||
|
Matcher m = layout.matcher(token);
|
||||||
|
if (!m.matches())
|
||||||
|
throw new IllegalArgumentException("Invalid token format");
|
||||||
|
int iterations = iterations(Integer.parseInt(m.group(1)));
|
||||||
|
byte[] hash = Base64.getUrlDecoder().decode(m.group(2));
|
||||||
|
byte[] salt = Arrays.copyOfRange(hash, 0, SIZE / 8);
|
||||||
|
byte[] check = pbkdf2(password, salt, iterations);
|
||||||
|
int zero = 0;
|
||||||
|
for (int idx = 0; idx < check.length; ++idx)
|
||||||
|
zero |= hash[salt.length + idx] ^ check[idx];
|
||||||
|
return zero == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] pbkdf2(char[] password, byte[] salt, int iterations)
|
||||||
|
{
|
||||||
|
KeySpec spec = new PBEKeySpec(password, salt, iterations, SIZE);
|
||||||
|
try {
|
||||||
|
SecretKeyFactory f = SecretKeyFactory.getInstance(ALGORITHM);
|
||||||
|
return f.generateSecret(spec).getEncoded();
|
||||||
|
}
|
||||||
|
catch (NoSuchAlgorithmException ex) {
|
||||||
|
throw new IllegalStateException("Missing algorithm: " + ALGORITHM, ex);
|
||||||
|
}
|
||||||
|
catch (InvalidKeySpecException ex) {
|
||||||
|
throw new IllegalStateException("Invalid SecretKeyFactory", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hash a password in an immutable {@code String}.
|
||||||
|
*
|
||||||
|
* <p>Passwords should be stored in a {@code char[]} so that it can be filled
|
||||||
|
* with zeros after use instead of lingering on the heap and elsewhere.
|
||||||
|
*
|
||||||
|
* @deprecated Use {@link #hash(char[])} instead
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
public String hash(String password)
|
||||||
|
{
|
||||||
|
return hash(password.toCharArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authenticate with a password in an immutable {@code String} and a stored
|
||||||
|
* password token.
|
||||||
|
*
|
||||||
|
* @deprecated Use {@link #checkPassword(char[],String)} instead.
|
||||||
|
* @see #hash(String)
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
public boolean checkPassword(String password, String token)
|
||||||
|
{
|
||||||
|
return checkPassword(password.toCharArray(), token);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,35 @@
|
||||||
|
package com.baeldung.passwordhashing;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
|
||||||
|
|
||||||
|
/** A really simple SHA_512 Encryption example.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class SHA512Hasher {
|
||||||
|
|
||||||
|
public String hash(String passwordToHash, byte[] salt){
|
||||||
|
String generatedPassword = null;
|
||||||
|
try {
|
||||||
|
MessageDigest md = MessageDigest.getInstance("SHA-512");
|
||||||
|
md.update(salt);
|
||||||
|
byte[] bytes = md.digest(passwordToHash.getBytes(StandardCharsets.UTF_8));
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
for(int i=0; i< bytes.length ;i++){
|
||||||
|
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
|
||||||
|
}
|
||||||
|
generatedPassword = sb.toString();
|
||||||
|
}
|
||||||
|
catch (NoSuchAlgorithmException e){
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return generatedPassword;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean checkPassword(String hash, String attempt, byte[] salt){
|
||||||
|
String generatedHash = hash(attempt, salt);
|
||||||
|
return hash.equals(generatedHash);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
package com.baeldung.passwordhashing;
|
||||||
|
|
||||||
|
import javax.crypto.SecretKeyFactory;
|
||||||
|
import javax.crypto.spec.PBEKeySpec;
|
||||||
|
import java.security.spec.KeySpec;
|
||||||
|
|
||||||
|
/** A really simple SimplePBKDF2 Encryption example.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class SimplePBKDF2Hasher {
|
||||||
|
|
||||||
|
public static String hashSimple(String password, byte[] salt) throws Exception{
|
||||||
|
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128);
|
||||||
|
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
|
||||||
|
byte[] hash = f.generateSecret(spec).getEncoded();
|
||||||
|
return String.valueOf(hash);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,70 @@
|
||||||
|
package com.baeldung.switchstatement;
|
||||||
|
|
||||||
|
public class SwitchStatement {
|
||||||
|
|
||||||
|
public String exampleOfIF(String animal) {
|
||||||
|
|
||||||
|
String result;
|
||||||
|
|
||||||
|
if (animal.equals("DOG") || animal.equals("CAT")) {
|
||||||
|
result = "domestic animal";
|
||||||
|
} else if (animal.equals("TIGER")) {
|
||||||
|
result = "wild animal";
|
||||||
|
} else {
|
||||||
|
result = "unknown animal";
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String exampleOfSwitch(String animal) {
|
||||||
|
|
||||||
|
String result;
|
||||||
|
|
||||||
|
switch (animal) {
|
||||||
|
case "DOG":
|
||||||
|
case "CAT":
|
||||||
|
result = "domestic animal";
|
||||||
|
break;
|
||||||
|
case "TIGER":
|
||||||
|
result = "wild animal";
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
result = "unknown animal";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String forgetBreakInSwitch(String animal) {
|
||||||
|
|
||||||
|
String result;
|
||||||
|
|
||||||
|
switch (animal) {
|
||||||
|
|
||||||
|
case "DOG":
|
||||||
|
System.out.println("domestic animal");
|
||||||
|
result = "domestic animal";
|
||||||
|
|
||||||
|
default:
|
||||||
|
System.out.println("unknown animal");
|
||||||
|
result = "unknown animal";
|
||||||
|
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String constantCaseValue(String animal) {
|
||||||
|
|
||||||
|
String result = "";
|
||||||
|
|
||||||
|
final String dog = "DOG";
|
||||||
|
|
||||||
|
switch (animal) {
|
||||||
|
|
||||||
|
case dog:
|
||||||
|
result = "domestic animal";
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,16 +1,12 @@
|
||||||
package com.baeldung.zoneddatetime;
|
package com.baeldung.zoneddatetime;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.time.OffsetDateTime;
|
import java.time.OffsetDateTime;
|
||||||
import java.time.ZoneId;
|
|
||||||
import java.time.ZoneOffset;
|
import java.time.ZoneOffset;
|
||||||
|
|
||||||
public class OffsetDateTimeExample {
|
public class OffsetDateTimeExample {
|
||||||
|
|
||||||
public OffsetDateTime getCurrentTimeByZoneOffset(String region) {
|
public OffsetDateTime getCurrentTimeByZoneOffset(String offset) {
|
||||||
LocalDateTime now = LocalDateTime.now();
|
ZoneOffset zoneOffSet= ZoneOffset.of(offset);
|
||||||
ZoneId zone = ZoneId.of(region);
|
|
||||||
ZoneOffset zoneOffSet= zone.getRules().getOffset(now);
|
|
||||||
OffsetDateTime date = OffsetDateTime.now(zoneOffSet);
|
OffsetDateTime date = OffsetDateTime.now(zoneOffSet);
|
||||||
return date;
|
return date;
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,17 +1,12 @@
|
||||||
package com.baeldung.zoneddatetime;
|
package com.baeldung.zoneddatetime;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.time.OffsetTime;
|
import java.time.OffsetTime;
|
||||||
import java.time.ZoneId;
|
|
||||||
import java.time.ZoneOffset;
|
import java.time.ZoneOffset;
|
||||||
|
|
||||||
public class OffsetTimeExample {
|
public class OffsetTimeExample {
|
||||||
|
|
||||||
public OffsetTime getCurrentTimeByZoneOffset(String region) {
|
public OffsetTime getCurrentTimeByZoneOffset(String offset) {
|
||||||
LocalDateTime now = LocalDateTime.now();
|
ZoneOffset zoneOffSet = ZoneOffset.of(offset);
|
||||||
ZoneId zone = ZoneId.of(region);
|
|
||||||
ZoneOffset zoneOffSet = zone.getRules()
|
|
||||||
.getOffset(now);
|
|
||||||
OffsetTime time = OffsetTime.now(zoneOffSet);
|
OffsetTime time = OffsetTime.now(zoneOffSet);
|
||||||
return time;
|
return time;
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,41 @@
|
||||||
|
package com.baeldung.passwordhashing;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
|
||||||
|
public class PBKDF2HasherUnitTest {
|
||||||
|
|
||||||
|
private PBKDF2Hasher mPBKDF2Hasher;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
mPBKDF2Hasher = new PBKDF2Hasher();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCorrectMessageAndHash_whenAuthenticated_checkAuthenticationSucceeds() throws Exception {
|
||||||
|
String message1 = "password123";
|
||||||
|
|
||||||
|
String hash1 = mPBKDF2Hasher.hash(message1.toCharArray());
|
||||||
|
|
||||||
|
assertTrue(mPBKDF2Hasher.checkPassword(message1.toCharArray(), hash1));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenWrongMessage_whenAuthenticated_checkAuthenticationFails() throws Exception {
|
||||||
|
String message1 = "password123";
|
||||||
|
|
||||||
|
String hash1 = mPBKDF2Hasher.hash(message1.toCharArray());
|
||||||
|
|
||||||
|
String wrongPasswordAttempt = "IamWrong";
|
||||||
|
|
||||||
|
assertFalse(mPBKDF2Hasher.checkPassword(wrongPasswordAttempt.toCharArray(), hash1));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,70 @@
|
||||||
|
package com.baeldung.passwordhashing;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Created by PhysicsSam on 06-Sep-18.
|
||||||
|
*/
|
||||||
|
public class SHA512HasherUnitTest {
|
||||||
|
|
||||||
|
private SHA512Hasher hasher;
|
||||||
|
private SecureRandom secureRandom;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
hasher = new SHA512Hasher();
|
||||||
|
secureRandom = new SecureRandom();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSamePasswordAndSalt_whenHashed_checkResultingHashesAreEqual() throws Exception {
|
||||||
|
|
||||||
|
byte[] salt = new byte[16];
|
||||||
|
secureRandom.nextBytes(salt);
|
||||||
|
|
||||||
|
String hash1 = hasher.hash("password", salt);
|
||||||
|
String hash2 = hasher.hash("password", salt);
|
||||||
|
|
||||||
|
assertEquals(hash1, hash2);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSamePasswordAndDifferentSalt_whenHashed_checkResultingHashesNotEqual() throws Exception {
|
||||||
|
|
||||||
|
byte[] salt = new byte[16];
|
||||||
|
secureRandom.nextBytes(salt);
|
||||||
|
String hash1 = hasher.hash("password", salt);
|
||||||
|
//generate a second salt
|
||||||
|
byte[] secondSalt = new byte[16];
|
||||||
|
String hash2 = hasher.hash("password", secondSalt);
|
||||||
|
|
||||||
|
assertNotEquals(hash1, hash2);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPredefinedHash_whenCorrectAttemptGiven_checkAuthenticationSucceeds() throws Exception {
|
||||||
|
byte[] salt = new byte[16];
|
||||||
|
secureRandom.nextBytes(salt);
|
||||||
|
|
||||||
|
String originalHash = hasher.hash("password123", salt);
|
||||||
|
|
||||||
|
assertTrue(hasher.checkPassword(originalHash, "password123", salt));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPredefinedHash_whenIncorrectAttemptGiven_checkAuthenticationFails() throws Exception {
|
||||||
|
byte[] salt = new byte[16];
|
||||||
|
secureRandom.nextBytes(salt);
|
||||||
|
|
||||||
|
String originalHash = hasher.hash("password123", salt);
|
||||||
|
|
||||||
|
assertFalse(hasher.checkPassword(originalHash, "password124", salt));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,38 @@
|
||||||
|
package com.baeldung.switchstatement;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
|
||||||
|
public class SwitchStatementUnitTest {
|
||||||
|
private SwitchStatement s = new SwitchStatement();
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenDog_thenDomesticAnimal() {
|
||||||
|
|
||||||
|
String animal = "DOG";
|
||||||
|
Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenNoBreaks_thenGoThroughBlocks() {
|
||||||
|
String animal = "DOG";
|
||||||
|
Assert.assertEquals("unknown animal", s.forgetBreakInSwitch(animal));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected=NullPointerException.class)
|
||||||
|
public void whenSwitchAgumentIsNull_thenNullPointerException() {
|
||||||
|
String animal = null;
|
||||||
|
Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCompareStrings_thenByEqual() {
|
||||||
|
String animal = new String("DOG");
|
||||||
|
Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
|
@ -2,9 +2,8 @@ package com.baeldung.zoneddatetime;
|
||||||
|
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.time.OffsetDateTime;
|
import java.time.OffsetDateTime;
|
||||||
import java.time.ZoneId;
|
import java.time.ZoneOffset;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
@ -14,12 +13,10 @@ public class OffsetDateTimeExampleUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenZoneOffset_whenGetCurrentTime_thenResultHasZone() {
|
public void givenZoneOffset_whenGetCurrentTime_thenResultHasZone() {
|
||||||
String zone = "Europe/Berlin";
|
String offset = "+02:00";
|
||||||
OffsetDateTime time = offsetDateTimeExample.getCurrentTimeByZoneOffset(zone);
|
OffsetDateTime time = offsetDateTimeExample.getCurrentTimeByZoneOffset(offset);
|
||||||
|
|
||||||
assertTrue(time.getOffset()
|
assertTrue(time.getOffset()
|
||||||
.equals(ZoneId.of(zone)
|
.equals(ZoneOffset.of(offset)));
|
||||||
.getRules()
|
|
||||||
.getOffset(LocalDateTime.now())));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,9 +2,8 @@ package com.baeldung.zoneddatetime;
|
||||||
|
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.time.OffsetTime;
|
import java.time.OffsetTime;
|
||||||
import java.time.ZoneId;
|
import java.time.ZoneOffset;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
@ -14,12 +13,10 @@ public class OffsetTimeExampleUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenZoneOffset_whenGetCurrentTime_thenResultHasZone() {
|
public void givenZoneOffset_whenGetCurrentTime_thenResultHasZone() {
|
||||||
String zone = "Europe/Berlin";
|
String offset = "+02:00";
|
||||||
OffsetTime time = offsetTimeExample.getCurrentTimeByZoneOffset(zone);
|
OffsetTime time = offsetTimeExample.getCurrentTimeByZoneOffset(offset);
|
||||||
|
|
||||||
assertTrue(time.getOffset()
|
assertTrue(time.getOffset()
|
||||||
.equals(ZoneId.of(zone)
|
.equals(ZoneOffset.of(offset)));
|
||||||
.getRules()
|
|
||||||
.getOffset(LocalDateTime.now())));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,6 +15,7 @@ public class ZoneDateTimeExampleUnitTest {
|
||||||
public void givenZone_whenGetCurrentTime_thenResultHasZone() {
|
public void givenZone_whenGetCurrentTime_thenResultHasZone() {
|
||||||
String zone = "Europe/Berlin";
|
String zone = "Europe/Berlin";
|
||||||
ZonedDateTime time = zoneDateTimeExample.getCurrentTimeByZoneId(zone);
|
ZonedDateTime time = zoneDateTimeExample.getCurrentTimeByZoneId(zone);
|
||||||
|
|
||||||
assertTrue(time.getZone()
|
assertTrue(time.getZone()
|
||||||
.equals(ZoneId.of(zone)));
|
.equals(ZoneId.of(zone)));
|
||||||
}
|
}
|
||||||
|
@ -25,6 +26,8 @@ public class ZoneDateTimeExampleUnitTest {
|
||||||
String destZone = "Asia/Tokyo";
|
String destZone = "Asia/Tokyo";
|
||||||
ZonedDateTime sourceDate = zoneDateTimeExample.getCurrentTimeByZoneId(sourceZone);
|
ZonedDateTime sourceDate = zoneDateTimeExample.getCurrentTimeByZoneId(sourceZone);
|
||||||
ZonedDateTime destDate = zoneDateTimeExample.convertZonedDateTime(sourceDate, destZone);
|
ZonedDateTime destDate = zoneDateTimeExample.convertZonedDateTime(sourceDate, destZone);
|
||||||
assertTrue(sourceDate.toInstant().compareTo(destDate.toInstant()) == 0);
|
|
||||||
|
assertTrue(sourceDate.toInstant()
|
||||||
|
.compareTo(destDate.toInstant()) == 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -105,7 +105,7 @@
|
||||||
<commons-lang3.version>3.5</commons-lang3.version>
|
<commons-lang3.version>3.5</commons-lang3.version>
|
||||||
<lombok.version>1.16.12</lombok.version>
|
<lombok.version>1.16.12</lombok.version>
|
||||||
<vavr.version>0.9.0</vavr.version>
|
<vavr.version>0.9.0</vavr.version>
|
||||||
<protonpack.version>1.13</protonpack.version>
|
<protonpack.version>1.15</protonpack.version>
|
||||||
<streamex.version>0.6.5</streamex.version>
|
<streamex.version>0.6.5</streamex.version>
|
||||||
<joda.version>2.10</joda.version>
|
<joda.version>2.10</joda.version>
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
|
|
|
@ -0,0 +1,209 @@
|
||||||
|
package com.baeldung.protonpack;
|
||||||
|
|
||||||
|
import com.codepoetics.protonpack.Indexed;
|
||||||
|
import com.codepoetics.protonpack.StreamUtils;
|
||||||
|
import com.codepoetics.protonpack.collectors.CollectorUtils;
|
||||||
|
import com.codepoetics.protonpack.collectors.NonUniqueValueException;
|
||||||
|
import com.codepoetics.protonpack.selectors.Selector;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.function.Function;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static java.util.Arrays.asList;
|
||||||
|
import static java.util.Arrays.stream;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public class ProtonpackUnitTest {
|
||||||
|
@Test
|
||||||
|
public void whenTakeWhile_thenTakenWhile() {
|
||||||
|
Stream<Integer> streamOfInt = Stream.iterate(1, i -> i + 1);
|
||||||
|
List<Integer> result = StreamUtils.takeWhile(streamOfInt, i -> i < 5).collect(Collectors.toList());
|
||||||
|
assertThat(result).contains(1, 2, 3, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenTakeUntil_thenTakenUntil() {
|
||||||
|
Stream<Integer> streamOfInt = Stream.iterate(1, i -> i + 1);
|
||||||
|
List<Integer> result = StreamUtils.takeUntil(streamOfInt, i -> i > 50).collect(Collectors.toList());
|
||||||
|
assertThat(result).contains(10, 20, 30, 40);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMultipleStream_whenZipped_thenZipped() {
|
||||||
|
String[] clubs = { "Juventus", "Barcelona", "Liverpool", "PSG" };
|
||||||
|
String[] players = { "Ronaldo", "Messi", "Salah" };
|
||||||
|
Set<String> zippedFrom2Sources = StreamUtils.zip(stream(clubs), stream(players), (club, player) -> club + " " + player)
|
||||||
|
.collect(Collectors.toSet());
|
||||||
|
assertThat(zippedFrom2Sources).contains("Juventus Ronaldo", "Barcelona Messi", "Liverpool Salah");
|
||||||
|
|
||||||
|
String[] leagues = { "Serie A", "La Liga", "Premier League" };
|
||||||
|
Set<String> zippedFrom3Sources = StreamUtils.zip(stream(clubs), stream(players), stream(leagues),
|
||||||
|
(club, player, league) -> club + " " + player + " " + league).collect(Collectors.toSet());
|
||||||
|
assertThat(zippedFrom3Sources).contains("Juventus Ronaldo Serie A", "Barcelona Messi La Liga",
|
||||||
|
"Liverpool Salah Premier League");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenZippedWithIndex_thenZippedWithIndex() {
|
||||||
|
Stream<String> streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool");
|
||||||
|
Set<Indexed<String>> zipsWithIndex = StreamUtils.zipWithIndex(streamOfClubs).collect(Collectors.toSet());
|
||||||
|
assertThat(zipsWithIndex).contains(Indexed.index(0, "Juventus"), Indexed.index(1, "Barcelona"),
|
||||||
|
Indexed.index(2, "Liverpool"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMultipleStream_whenMerged_thenMerged() {
|
||||||
|
Stream<String> streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool", "PSG");
|
||||||
|
Stream<String> streamOfPlayers = Stream.of("Ronaldo", "Messi", "Salah");
|
||||||
|
Stream<String> streamOfLeagues = Stream.of("Serie A", "La Liga", "Premier League");
|
||||||
|
|
||||||
|
Set<String> merged = StreamUtils.merge(() -> "", (valOne, valTwo) -> valOne + " " + valTwo, streamOfClubs,
|
||||||
|
streamOfPlayers, streamOfLeagues).collect(Collectors.toSet());
|
||||||
|
|
||||||
|
assertThat(merged).contains(" Juventus Ronaldo Serie A", " Barcelona Messi La Liga", " Liverpool Salah Premier League",
|
||||||
|
" PSG");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMultipleStream_whenMergedToList_thenMergedToList() {
|
||||||
|
Stream<String> streamOfClubs = Stream.of("Juventus", "Barcelona", "PSG");
|
||||||
|
Stream<String> streamOfPlayers = Stream.of("Ronaldo", "Messi");
|
||||||
|
|
||||||
|
List<List<String>> mergedListOfList = StreamUtils.mergeToList(streamOfClubs, streamOfPlayers)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
assertThat(mergedListOfList.get(0)).isInstanceOf(List.class);
|
||||||
|
assertThat(mergedListOfList.get(0)).containsExactly("Juventus", "Ronaldo");
|
||||||
|
assertThat(mergedListOfList.get(1)).containsExactly("Barcelona", "Messi");
|
||||||
|
assertThat(mergedListOfList.get(2)).containsExactly("PSG");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMultipleStream_whenInterleaved_thenInterleaved() {
|
||||||
|
Stream<String> streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool");
|
||||||
|
Stream<String> streamOfPlayers = Stream.of("Ronaldo", "Messi");
|
||||||
|
Stream<String> streamOfLeagues = Stream.of("Serie A", "La Liga");
|
||||||
|
|
||||||
|
AtomicInteger counter = new AtomicInteger(0);
|
||||||
|
Selector roundRobinSelector = (o) -> {
|
||||||
|
Object[] vals = (Object[]) o;
|
||||||
|
while (counter.get() >= vals.length || vals[counter.get()] == null) {
|
||||||
|
if (counter.incrementAndGet() >= vals.length)
|
||||||
|
counter.set(0);
|
||||||
|
}
|
||||||
|
return counter.getAndIncrement();
|
||||||
|
};
|
||||||
|
Stream<String> interleavedStream = StreamUtils.interleave(roundRobinSelector, streamOfClubs, streamOfPlayers,
|
||||||
|
streamOfLeagues);
|
||||||
|
List<String> interleavedList = interleavedStream.collect(Collectors.toList());
|
||||||
|
assertThat(interleavedList).containsExactly("Juventus", "Ronaldo", "Serie A", "Barcelona", "Messi", "La Liga",
|
||||||
|
"Liverpool");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSkippedUntil_thenSkippedUntil() {
|
||||||
|
Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
|
||||||
|
List<Integer> skippedUntilGreaterThan5 = StreamUtils.skipUntil(stream(numbers), i -> i > 5).collect(Collectors.toList());
|
||||||
|
assertThat(skippedUntilGreaterThan5).containsExactly(6, 7, 8, 9, 10);
|
||||||
|
|
||||||
|
List<Integer> skippedUntilLessThanEquals5 = StreamUtils.skipUntil(stream(numbers), i -> i <= 5)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
assertThat(skippedUntilLessThanEquals5).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSkippedWhile_thenSkippedWhile() {
|
||||||
|
Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
|
||||||
|
List<Integer> skippedWhileLessThanEquals5 = StreamUtils.skipWhile(stream(numbers), i -> i <= 5)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
assertThat(skippedWhileLessThanEquals5).containsExactly(6, 7, 8, 9, 10);
|
||||||
|
|
||||||
|
List<Integer> skippedWhileGreaterThan5 = StreamUtils.skipWhile(stream(numbers), i -> i > 5).collect(Collectors.toList());
|
||||||
|
assertThat(skippedWhileGreaterThan5).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFibonacciGenerator_whenUnfolded_thenUnfolded() {
|
||||||
|
AtomicInteger lastValue = new AtomicInteger(0);
|
||||||
|
Function<Integer, Optional<Integer>> fibonacciGenerator = (i) -> (i < 10) ?
|
||||||
|
Optional.of(i + lastValue.getAndSet(i)) :
|
||||||
|
Optional.empty();
|
||||||
|
|
||||||
|
List<Integer> fib = StreamUtils.unfold(1, fibonacciGenerator).collect(Collectors.toList());
|
||||||
|
assertThat(fib).containsExactly(1, 1, 2, 3, 5, 8, 13);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenWindowed_thenWindowed() {
|
||||||
|
Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7 };
|
||||||
|
|
||||||
|
List<List<Integer>> windowedWithSkip1 = StreamUtils.windowed(stream(numbers), 3, 1).collect(Collectors.toList());
|
||||||
|
assertThat(windowedWithSkip1).containsExactly(asList(1, 2, 3), asList(2, 3, 4), asList(3, 4, 5), asList(4, 5, 6),
|
||||||
|
asList(5, 6, 7));
|
||||||
|
|
||||||
|
List<List<Integer>> windowedWithSkip2 = StreamUtils.windowed(stream(numbers), 3, 2).collect(Collectors.toList());
|
||||||
|
assertThat(windowedWithSkip2).containsExactly(asList(1, 2, 3), asList(3, 4, 5), asList(5, 6, 7));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenAggregated_thenAggregated() {
|
||||||
|
Integer[] numbers = { 1, 2, 2, 3, 4, 4, 4, 5 };
|
||||||
|
List<List<Integer>> aggregated = StreamUtils.aggregate(stream(numbers), (int1, int2) -> int1.compareTo(int2) == 0)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
assertThat(aggregated).containsExactly(asList(1), asList(2, 2), asList(3), asList(4, 4, 4), asList(5));
|
||||||
|
|
||||||
|
List<List<Integer>> aggregatedFixSize = StreamUtils.aggregate(stream(numbers), 5).collect(Collectors.toList());
|
||||||
|
assertThat(aggregatedFixSize).containsExactly(asList(1, 2, 2, 3, 4), asList(4, 4, 5));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGroupedRun_thenGroupedRun() {
|
||||||
|
Integer[] numbers = { 1, 1, 2, 3, 4, 4, 5 };
|
||||||
|
List<List<Integer>> grouped = StreamUtils.groupRuns(stream(numbers)).collect(Collectors.toList());
|
||||||
|
assertThat(grouped).containsExactly(asList(1, 1), asList(2), asList(3), asList(4, 4), asList(5));
|
||||||
|
|
||||||
|
Integer[] numbers2 = { 1, 2, 3, 1 };
|
||||||
|
List<List<Integer>> grouped2 = StreamUtils.groupRuns(stream(numbers2)).collect(Collectors.toList());
|
||||||
|
assertThat(grouped2).containsExactly(asList(1), asList(2), asList(3), asList(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenAggregatedOnListCondition_thenAggregatedOnListCondition() {
|
||||||
|
Integer[] numbers = { 1, 1, 2, 3, 4, 4, 5 };
|
||||||
|
Stream<List<Integer>> aggregated = StreamUtils.aggregateOnListCondition(stream(numbers),
|
||||||
|
(currentList, nextInt) -> currentList.stream().mapToInt(Integer::intValue).sum() + nextInt <= 5);
|
||||||
|
assertThat(aggregated).containsExactly(asList(1, 1, 2), asList(3), asList(4), asList(4), asList(5));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenProjectionFunction_whenMaxedBy_thenMaxedBy() {
|
||||||
|
Stream<String> clubs = Stream.of("Juventus", "Barcelona", "PSG");
|
||||||
|
Optional<String> longestName = clubs.collect(CollectorUtils.maxBy(String::length));
|
||||||
|
assertThat(longestName.get()).isEqualTo("Barcelona");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStreamOfMultipleElem_whenUniqueCollector_thenValueReturned() {
|
||||||
|
Stream<Integer> singleElement = Stream.of(1);
|
||||||
|
Optional<Integer> unique = singleElement.collect(CollectorUtils.unique());
|
||||||
|
assertThat(unique.get()).isEqualTo(1);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStreamOfMultipleElem_whenUniqueCollector_thenExceptionThrown() {
|
||||||
|
Stream<Integer> multipleElement = Stream.of(1, 2, 3);
|
||||||
|
assertThatExceptionOfType(NonUniqueValueException.class).isThrownBy(() -> {
|
||||||
|
multipleElement.collect(CollectorUtils.unique());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -47,11 +47,21 @@
|
||||||
<artifactId>jmh-core</artifactId>
|
<artifactId>jmh-core</artifactId>
|
||||||
<version>${jmh-core.version}</version>
|
<version>${jmh-core.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-generator-annprocess</artifactId>
|
||||||
|
<version>${jmh-core.version}</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.ibm.icu</groupId>
|
<groupId>com.ibm.icu</groupId>
|
||||||
<artifactId>icu4j</artifactId>
|
<artifactId>icu4j</artifactId>
|
||||||
<version>${icu4j.version}</version>
|
<version>${icu4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.guava</groupId>
|
||||||
|
<artifactId>guava</artifactId>
|
||||||
|
<version>${guava.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.vdurmont</groupId>
|
<groupId>com.vdurmont</groupId>
|
||||||
|
@ -92,6 +102,7 @@
|
||||||
<assertj.version>3.6.1</assertj.version>
|
<assertj.version>3.6.1</assertj.version>
|
||||||
<jmh-core.version>1.19</jmh-core.version>
|
<jmh-core.version>1.19</jmh-core.version>
|
||||||
<icu4j.version>61.1</icu4j.version>
|
<icu4j.version>61.1</icu4j.version>
|
||||||
|
<guava.version>26.0-jre</guava.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -0,0 +1,163 @@
|
||||||
|
package com.baeldung.string;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.openjdk.jmh.annotations.*;
|
||||||
|
import org.openjdk.jmh.runner.Runner;
|
||||||
|
import org.openjdk.jmh.runner.options.Options;
|
||||||
|
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
@BenchmarkMode(Mode.SingleShotTime)
|
||||||
|
@OutputTimeUnit(TimeUnit.MILLISECONDS)
|
||||||
|
@Measurement(batchSize = 10000, iterations = 10)
|
||||||
|
@Warmup(batchSize = 10000, iterations = 10)
|
||||||
|
public class StringPerformance extends StringPerformanceHints {
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public String benchmarkStringDynamicConcat() {
|
||||||
|
return dynamicConcat();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public StringBuilder benchmarkStringBuilder() {
|
||||||
|
StringBuilder stringBuilder = new StringBuilder(result);
|
||||||
|
stringBuilder.append(baeldung);
|
||||||
|
return stringBuilder;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public StringBuffer benchmarkStringBuffer() {
|
||||||
|
StringBuffer stringBuffer = new StringBuffer(result);
|
||||||
|
stringBuffer.append(baeldung);
|
||||||
|
return stringBuffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public String benchmarkStringConstructor() {
|
||||||
|
return stringConstructor();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public String benchmarkStringLiteral() {
|
||||||
|
return stringLiteral();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public String benchmarkStringFormat_s() {
|
||||||
|
return stringFormat_s();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public String benchmarkStringConcat() {
|
||||||
|
return stringConcat();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public String benchmarkStringIntern() {
|
||||||
|
return stringIntern();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public String benchmarkStringReplace() {
|
||||||
|
return longString.replace("average", " average !!!");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public String benchmarkStringUtilsReplace() {
|
||||||
|
return StringUtils.replace(longString, "average", " average !!!");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public List<String> benchmarkGuavaSplitter() {
|
||||||
|
return guavaSplitter();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public String [] benchmarkStringSplit() {
|
||||||
|
return stringSplit();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public String [] benchmarkStringSplitPattern() {
|
||||||
|
return stringSplitPattern();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public List benchmarkStringTokenizer() {
|
||||||
|
return stringTokenizer();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public List benchmarkStringIndexOf() {
|
||||||
|
return stringIndexOf();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public String benchmarkIntegerToString() {
|
||||||
|
return stringIntegerToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public String benchmarkStringValueOf() {
|
||||||
|
return stringValueOf();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public String benchmarkStringConvertPlus() {
|
||||||
|
return stringConvertPlus();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public String benchmarkStringFormat_d() {
|
||||||
|
return stringFormat_d();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public boolean benchmarkStringEquals() {
|
||||||
|
return stringEquals();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public boolean benchmarkStringEqualsIgnoreCase() {
|
||||||
|
return stringEqualsIgnoreCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public boolean benchmarkStringMatches() {
|
||||||
|
return stringIsMatch();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public boolean benchmarkPrecompiledMatches() {
|
||||||
|
return precompiledMatches();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public int benchmarkStringCompareTo() {
|
||||||
|
return stringCompareTo();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public boolean benchmarkStringIsEmpty() {
|
||||||
|
return stringIsEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public boolean benchmarkStringLengthZero() {
|
||||||
|
return stringLengthZero();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
Options options = new OptionsBuilder()
|
||||||
|
.include(StringPerformance.class.getSimpleName()).threads(1)
|
||||||
|
.forks(1).shouldFailOnError(true)
|
||||||
|
.shouldDoGC(true)
|
||||||
|
.jvmArgs("-server").build();
|
||||||
|
new Runner(options).run();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,133 @@
|
||||||
|
package com.baeldung.string;
|
||||||
|
|
||||||
|
import com.google.common.base.Splitter;
|
||||||
|
import org.openjdk.jmh.annotations.Scope;
|
||||||
|
import org.openjdk.jmh.annotations.State;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.StringTokenizer;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
@State(Scope.Thread)
|
||||||
|
public class StringPerformanceHints {
|
||||||
|
|
||||||
|
protected String baeldung = "baeldung";
|
||||||
|
protected String longString = "Hello baeldung, I am a bit longer than other Strings";
|
||||||
|
protected String formatString = "hello %s, nice to meet you";
|
||||||
|
protected String formatDigit = "%d";
|
||||||
|
protected String emptyString = " ";
|
||||||
|
protected String result = "";
|
||||||
|
|
||||||
|
protected int sampleNumber = 100;
|
||||||
|
|
||||||
|
protected Pattern spacePattern = Pattern.compile(emptyString);
|
||||||
|
protected Pattern longPattern = Pattern.compile(longString);
|
||||||
|
protected List<String> stringSplit = new ArrayList<>();
|
||||||
|
protected List<String> stringTokenizer = new ArrayList<>();
|
||||||
|
|
||||||
|
protected String dynamicConcat() {
|
||||||
|
result += baeldung;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected String stringConstructor() {
|
||||||
|
return new String(baeldung);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected String stringLiteral() {
|
||||||
|
result = baeldung;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected String stringFormat_s() {
|
||||||
|
return String.format(formatString, baeldung);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected String stringFormat_d() {
|
||||||
|
return String.format(formatDigit, sampleNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected String stringConcat() {
|
||||||
|
result = result.concat(baeldung);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected List stringTokenizer() {
|
||||||
|
StringTokenizer st = new StringTokenizer(longString);
|
||||||
|
while (st.hasMoreTokens()) {
|
||||||
|
stringTokenizer.add(st.nextToken());
|
||||||
|
}
|
||||||
|
return stringTokenizer;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected List stringIndexOf() {
|
||||||
|
int pos = 0, end;
|
||||||
|
while ((end = longString.indexOf(' ', pos)) >= 0) {
|
||||||
|
stringSplit.add(longString.substring(pos, end));
|
||||||
|
pos = end + 1;
|
||||||
|
}
|
||||||
|
return stringSplit;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected String stringIntegerToString() {
|
||||||
|
return Integer.toString(sampleNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected String stringValueOf() {
|
||||||
|
return String.valueOf(sampleNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
protected String stringConvertPlus() {
|
||||||
|
return sampleNumber + "";
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
protected boolean stringEquals() {
|
||||||
|
return longString.equals(baeldung);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
protected boolean stringEqualsIgnoreCase() {
|
||||||
|
return longString.equalsIgnoreCase(baeldung);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected boolean stringIsMatch() {
|
||||||
|
return longString.matches(baeldung);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected boolean precompiledMatches() {
|
||||||
|
return longPattern.matcher(baeldung).matches();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected int stringCompareTo() {
|
||||||
|
return longString.compareTo(baeldung);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected boolean stringIsEmpty() {
|
||||||
|
return longString.isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected boolean stringLengthZero() {
|
||||||
|
return longString.length() == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected String [] stringSplitPattern() {
|
||||||
|
return spacePattern.split(longString, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected String [] stringSplit() {
|
||||||
|
return longString.split(emptyString);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected List<String> guavaSplitter() {
|
||||||
|
return Splitter.on(" ").trimResults()
|
||||||
|
.omitEmptyStrings()
|
||||||
|
.splitToList(longString);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected String stringIntern() {
|
||||||
|
return baeldung.intern();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,51 @@
|
||||||
|
package com.baeldung.string;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.not;
|
||||||
|
import static org.hamcrest.text.IsEmptyString.isEmptyOrNullString;
|
||||||
|
import static org.hamcrest.text.IsEmptyString.isEmptyString;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNotEquals;
|
||||||
|
import static org.junit.Assert.assertNotSame;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.assertj.core.api.Assertions;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.google.common.base.Strings;
|
||||||
|
|
||||||
|
public class StringEmptyUnitTest {
|
||||||
|
|
||||||
|
private String text = "baeldung";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAString_whenCheckedForEmptyUsingJunit_shouldAssertSuccessfully() {
|
||||||
|
assertTrue(!text.isEmpty());
|
||||||
|
assertFalse(text.isEmpty());
|
||||||
|
assertNotEquals("", text);
|
||||||
|
assertNotSame("", text);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAString_whenCheckedForEmptyUsingHamcrest_shouldAssertSuccessfully() {
|
||||||
|
assertThat(text, not(isEmptyString()));
|
||||||
|
assertThat(text, not(isEmptyOrNullString()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAString_whenCheckedForEmptyUsingCommonsLang_shouldAssertSuccessfully() {
|
||||||
|
assertTrue(StringUtils.isNotBlank(text));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAString_whenCheckedForEmptyUsingAssertJ_shouldAssertSuccessfully() {
|
||||||
|
Assertions.assertThat(text).isNotEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAString_whenCheckedForEmptyUsingGuava_shouldAssertSuccessfully() {
|
||||||
|
assertFalse(Strings.isNullOrEmpty(text));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,14 @@
|
||||||
|
*.class
|
||||||
|
|
||||||
|
#folders#
|
||||||
|
/target
|
||||||
|
/neoDb*
|
||||||
|
/data
|
||||||
|
/src/main/webapp/WEB-INF/classes
|
||||||
|
*/META-INF/*
|
||||||
|
|
||||||
|
# Packaged files #
|
||||||
|
*.jar
|
||||||
|
*.war
|
||||||
|
*.ear
|
||||||
|
/bin/
|
|
@ -0,0 +1,51 @@
|
||||||
|
<?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>libraries-security</artifactId>
|
||||||
|
<name>libraries-security</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-boot-1</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../parent-boot-1</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.security.oauth</groupId>
|
||||||
|
<artifactId>spring-security-oauth2</artifactId>
|
||||||
|
<version>2.3.3.RELEASE</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.github.scribejava</groupId>
|
||||||
|
<artifactId>scribejava-apis</artifactId>
|
||||||
|
<version>${scribejava.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>${junit.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<junit.version>4.12</junit.version>
|
||||||
|
<spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version>
|
||||||
|
<scribejava.version>5.6.0</scribejava.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,15 @@
|
||||||
|
package com.baeldung.scribejava;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class ScribejavaApplication {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(ScribejavaApplication.class, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,27 @@
|
||||||
|
package com.baeldung.scribejava.api;
|
||||||
|
|
||||||
|
import com.github.scribejava.core.builder.api.DefaultApi20;
|
||||||
|
|
||||||
|
public class MyApi extends DefaultApi20 {
|
||||||
|
|
||||||
|
private MyApi() {
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class InstanceHolder {
|
||||||
|
private static final MyApi INSTANCE = new MyApi();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static MyApi instance() {
|
||||||
|
return InstanceHolder.INSTANCE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getAccessTokenEndpoint() {
|
||||||
|
return "http://localhost:8080/oauth/token";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String getAuthorizationBaseUrl() {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,49 @@
|
||||||
|
package com.baeldung.scribejava.controller;
|
||||||
|
|
||||||
|
import com.baeldung.scribejava.service.GoogleService;
|
||||||
|
import com.github.scribejava.core.model.OAuth2AccessToken;
|
||||||
|
import com.github.scribejava.core.model.OAuthRequest;
|
||||||
|
import com.github.scribejava.core.model.Response;
|
||||||
|
import com.github.scribejava.core.model.Verb;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
public class GoogleController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private GoogleService service;
|
||||||
|
|
||||||
|
|
||||||
|
@GetMapping(value ="/me/google")
|
||||||
|
public void me(HttpServletResponse response){
|
||||||
|
String auth = service.getService().getAuthorizationUrl();
|
||||||
|
|
||||||
|
response.setHeader("Location", auth);
|
||||||
|
response.setStatus(302);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping(value = "/auth/google")
|
||||||
|
public String google(@RequestParam String code, HttpServletResponse servletResponse){
|
||||||
|
|
||||||
|
try {
|
||||||
|
OAuth2AccessToken token = service.getService().getAccessToken(code);
|
||||||
|
|
||||||
|
OAuthRequest request = new OAuthRequest(Verb.GET, "https://www.googleapis.com/oauth2/v1/userinfo?alt=json");
|
||||||
|
service.getService().signRequest(token, request);
|
||||||
|
Response response = service.getService().execute(request);
|
||||||
|
return response.getBody();
|
||||||
|
|
||||||
|
}catch (Exception e){
|
||||||
|
servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,57 @@
|
||||||
|
package com.baeldung.scribejava.controller;
|
||||||
|
|
||||||
|
import com.baeldung.scribejava.service.TwitterService;
|
||||||
|
import com.github.scribejava.core.model.*;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Scanner;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
public class TwitterController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private TwitterService service;
|
||||||
|
|
||||||
|
|
||||||
|
@GetMapping(value ="/me/twitter")
|
||||||
|
public String me(HttpServletResponse servletResponse){
|
||||||
|
try {
|
||||||
|
OAuth1RequestToken requestToken = service.getService().getRequestToken();
|
||||||
|
|
||||||
|
String auth = service.getService().getAuthorizationUrl(requestToken);
|
||||||
|
|
||||||
|
Runtime runtime = Runtime.getRuntime();
|
||||||
|
try {
|
||||||
|
runtime.exec("rundll32 url.dll,FileProtocolHandler " + auth);
|
||||||
|
} catch (IOException e) {
|
||||||
|
servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("Insert twitter code:");
|
||||||
|
Scanner in = new Scanner(System.in);
|
||||||
|
|
||||||
|
String oauthverifier = in.nextLine();
|
||||||
|
|
||||||
|
final OAuth1AccessToken accessToken = service.getService().getAccessToken(requestToken,oauthverifier);
|
||||||
|
|
||||||
|
OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.twitter.com/1.1/account/verify_credentials.json");
|
||||||
|
service.getService().signRequest(accessToken, request);
|
||||||
|
Response response = service.getService().execute(request);
|
||||||
|
return response.getBody();
|
||||||
|
|
||||||
|
} catch (IOException | InterruptedException | ExecutionException e) {
|
||||||
|
servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,46 @@
|
||||||
|
package com.baeldung.scribejava.controller;
|
||||||
|
|
||||||
|
import com.baeldung.scribejava.service.MyService;
|
||||||
|
import com.github.scribejava.core.model.OAuth2AccessToken;
|
||||||
|
import com.github.scribejava.core.model.OAuthRequest;
|
||||||
|
import com.github.scribejava.core.model.Response;
|
||||||
|
import com.github.scribejava.core.model.Verb;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
import java.security.Principal;
|
||||||
|
|
||||||
|
@RestController(value = "/user")
|
||||||
|
public class UserController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private MyService service;
|
||||||
|
|
||||||
|
@GetMapping("/me/myapi")
|
||||||
|
public String me(@RequestParam String username, @RequestParam String password, HttpServletResponse responsehttp) {
|
||||||
|
|
||||||
|
try {
|
||||||
|
OAuth2AccessToken token = service.getService().getAccessTokenPasswordGrant(username, password);
|
||||||
|
|
||||||
|
OAuthRequest request = new OAuthRequest(Verb.GET, "http://localhost:8080/me");
|
||||||
|
service.getService().signRequest(token, request);
|
||||||
|
Response response = service.getService().execute(request);
|
||||||
|
|
||||||
|
return response.getBody();
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
responsehttp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/me")
|
||||||
|
public Principal user(Principal principal) {
|
||||||
|
return principal;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,45 @@
|
||||||
|
package com.baeldung.scribejava.oauth;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
|
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
|
||||||
|
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
|
||||||
|
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
|
||||||
|
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
|
||||||
|
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
|
||||||
|
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableAuthorizationServer
|
||||||
|
public class AuthServiceConfig extends AuthorizationServerConfigurerAdapter {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
@Qualifier("authenticationManagerBean")
|
||||||
|
private AuthenticationManager authenticationManager;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
|
||||||
|
oauthServer.tokenKeyAccess("permitAll()")
|
||||||
|
.checkTokenAccess("isAuthenticated()");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
|
||||||
|
clients.inMemory()
|
||||||
|
.withClient("baeldung_api_key")
|
||||||
|
.secret("baeldung_api_secret")
|
||||||
|
.authorizedGrantTypes("password","refresh_token")
|
||||||
|
.scopes("read","write").autoApprove(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
|
||||||
|
endpoints
|
||||||
|
.authenticationManager(authenticationManager)
|
||||||
|
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,53 @@
|
||||||
|
package com.baeldung.scribejava.oauth;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
|
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;
|
||||||
|
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
|
||||||
|
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableResourceServer
|
||||||
|
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
|
http
|
||||||
|
.headers().frameOptions().disable()
|
||||||
|
.and()
|
||||||
|
.csrf().disable();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||||
|
auth.inMemoryAuthentication()
|
||||||
|
.withUser("baeldung")
|
||||||
|
.password("scribejava")
|
||||||
|
.roles("USER");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Bean
|
||||||
|
public AuthenticationManager authenticationManagerBean() throws Exception {
|
||||||
|
return super.authenticationManagerBean();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@EnableResourceServer
|
||||||
|
@Configuration
|
||||||
|
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void configure(HttpSecurity http) throws Exception {
|
||||||
|
http
|
||||||
|
.authorizeRequests()
|
||||||
|
.antMatchers("/user/me").authenticated()
|
||||||
|
.and()
|
||||||
|
.csrf().disable();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
package com.baeldung.scribejava.service;
|
||||||
|
|
||||||
|
import com.github.scribejava.apis.GoogleApi20;
|
||||||
|
import com.github.scribejava.core.builder.ServiceBuilder;
|
||||||
|
import com.github.scribejava.core.oauth.OAuth20Service;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import javax.annotation.PostConstruct;
|
||||||
|
@Component
|
||||||
|
public class GoogleService {
|
||||||
|
|
||||||
|
private OAuth20Service service;
|
||||||
|
private final String API_KEY = "api_key";
|
||||||
|
private final String API_SECRET = "api_secret";
|
||||||
|
private final String SCOPE = "https://www.googleapis.com/auth/userinfo.email";
|
||||||
|
private final String CALLBACK = "http://localhost:8080/auth/google";
|
||||||
|
|
||||||
|
@PostConstruct
|
||||||
|
private void init(){
|
||||||
|
this.service = new ServiceBuilder(API_KEY)
|
||||||
|
.apiSecret(API_SECRET)
|
||||||
|
.scope(SCOPE)
|
||||||
|
.callback(CALLBACK)
|
||||||
|
.build(GoogleApi20.instance());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public OAuth20Service getService() {
|
||||||
|
return service;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,29 @@
|
||||||
|
package com.baeldung.scribejava.service;
|
||||||
|
|
||||||
|
import com.baeldung.scribejava.api.MyApi;
|
||||||
|
import com.github.scribejava.core.builder.ServiceBuilder;
|
||||||
|
import com.github.scribejava.core.oauth.OAuth20Service;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import javax.annotation.PostConstruct;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class MyService {
|
||||||
|
|
||||||
|
private OAuth20Service service;
|
||||||
|
private final String API_KEY = "baeldung_api_key";
|
||||||
|
private final String API_SECRET = "baeldung_api_secret";
|
||||||
|
|
||||||
|
@PostConstruct
|
||||||
|
private void init(){
|
||||||
|
this.service = new ServiceBuilder(API_KEY)
|
||||||
|
.apiSecret(API_SECRET)
|
||||||
|
.scope("read write")
|
||||||
|
.build(MyApi.instance());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public OAuth20Service getService() {
|
||||||
|
return service;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,29 @@
|
||||||
|
package com.baeldung.scribejava.service;
|
||||||
|
|
||||||
|
import com.github.scribejava.apis.TwitterApi;
|
||||||
|
import com.github.scribejava.core.builder.ServiceBuilder;
|
||||||
|
import com.github.scribejava.core.oauth.OAuth10aService;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import javax.annotation.PostConstruct;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class TwitterService {
|
||||||
|
|
||||||
|
private final String API_KEY = "api_key";
|
||||||
|
private final String API_SECRET = "api_secret";
|
||||||
|
private OAuth10aService service;
|
||||||
|
|
||||||
|
@PostConstruct
|
||||||
|
private void init(){
|
||||||
|
this.service = new ServiceBuilder(API_KEY)
|
||||||
|
.apiSecret(API_SECRET)
|
||||||
|
.build(TwitterApi.instance());
|
||||||
|
}
|
||||||
|
|
||||||
|
public OAuth10aService getService(){
|
||||||
|
return service;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1 @@
|
||||||
|
security.oauth2.resource.filter-order = 3
|
|
@ -0,0 +1,17 @@
|
||||||
|
package com.baeldung.scribejava;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest
|
||||||
|
public class ScribejavaUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void contextLoad(){
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,56 @@
|
||||||
|
package com.baeldung.kafka;
|
||||||
|
|
||||||
|
import org.apache.kafka.clients.producer.KafkaProducer;
|
||||||
|
import org.apache.kafka.clients.producer.ProducerRecord;
|
||||||
|
import org.apache.kafka.common.KafkaException;
|
||||||
|
|
||||||
|
import java.util.Properties;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG;
|
||||||
|
import static org.apache.kafka.clients.producer.ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG;
|
||||||
|
import static org.apache.kafka.clients.producer.ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG;
|
||||||
|
import static org.apache.kafka.clients.producer.ProducerConfig.TRANSACTIONAL_ID_CONFIG;
|
||||||
|
import static org.apache.kafka.clients.producer.ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG;
|
||||||
|
|
||||||
|
public class TransactionalMessageProducer {
|
||||||
|
|
||||||
|
private static final String DATA_MESSAGE_1 = "Put any space separated data here for count";
|
||||||
|
private static final String DATA_MESSAGE_2 = "Output will contain count of every word in the message";
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
KafkaProducer<String, String> producer = createKafkaProducer();
|
||||||
|
|
||||||
|
producer.initTransactions();
|
||||||
|
|
||||||
|
try{
|
||||||
|
|
||||||
|
producer.beginTransaction();
|
||||||
|
|
||||||
|
Stream.of(DATA_MESSAGE_1, DATA_MESSAGE_2).forEach(s -> producer.send(
|
||||||
|
new ProducerRecord<String, String>("input", null, s)));
|
||||||
|
|
||||||
|
producer.commitTransaction();
|
||||||
|
|
||||||
|
}catch (KafkaException e){
|
||||||
|
|
||||||
|
producer.abortTransaction();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static KafkaProducer<String, String> createKafkaProducer() {
|
||||||
|
|
||||||
|
Properties props = new Properties();
|
||||||
|
props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
|
||||||
|
props.put(ENABLE_IDEMPOTENCE_CONFIG, "true");
|
||||||
|
props.put(TRANSACTIONAL_ID_CONFIG, "prod-0");
|
||||||
|
props.put(KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
|
||||||
|
props.put(VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
|
||||||
|
|
||||||
|
return new KafkaProducer(props);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
|
@ -14,6 +14,8 @@ import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import static java.time.Duration.ofSeconds;
|
import static java.time.Duration.ofSeconds;
|
||||||
import static java.util.Collections.singleton;
|
import static java.util.Collections.singleton;
|
||||||
|
@ -21,16 +23,16 @@ import static org.apache.kafka.clients.consumer.ConsumerConfig.*;
|
||||||
import static org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG;
|
import static org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG;
|
||||||
import static org.apache.kafka.clients.producer.ProducerConfig.*;
|
import static org.apache.kafka.clients.producer.ProducerConfig.*;
|
||||||
|
|
||||||
public class TransactionalApp {
|
public class TransactionalWordCount {
|
||||||
|
|
||||||
private static final String CONSUMER_GROUP_ID = "test";
|
private static final String CONSUMER_GROUP_ID = "my-group-id";
|
||||||
private static final String OUTPUT_TOPIC = "output";
|
private static final String OUTPUT_TOPIC = "output";
|
||||||
private static final String INPUT_TOPIC = "input";
|
private static final String INPUT_TOPIC = "input";
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
|
||||||
KafkaConsumer<String, String> consumer = initConsumer();
|
KafkaConsumer<String, String> consumer = createKafkaConsumer();
|
||||||
KafkaProducer<String, String> producer = initProducer();
|
KafkaProducer<String, String> producer = createKafkaProducer();
|
||||||
|
|
||||||
producer.initTransactions();
|
producer.initTransactions();
|
||||||
|
|
||||||
|
@ -38,12 +40,17 @@ public class TransactionalApp {
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
|
|
||||||
ConsumerRecords<String, String> records = consumer.poll(ofSeconds(20));
|
ConsumerRecords<String, String> records = consumer.poll(ofSeconds(60));
|
||||||
|
|
||||||
|
Map<String, Integer> wordCountMap = records.records(new TopicPartition(INPUT_TOPIC, 0))
|
||||||
|
.stream()
|
||||||
|
.flatMap(record -> Stream.of(record.value().split(" ")))
|
||||||
|
.map(word -> Tuple.of(word, 1))
|
||||||
|
.collect(Collectors.toMap(tuple -> tuple.getKey(), t1 -> t1.getValue(), (v1, v2) -> v1 + v2));
|
||||||
|
|
||||||
producer.beginTransaction();
|
producer.beginTransaction();
|
||||||
|
|
||||||
for (ConsumerRecord record : records)
|
wordCountMap.forEach((key, value) -> producer.send(new ProducerRecord<String, String>(OUTPUT_TOPIC, key, value.toString())));
|
||||||
producer.send(new ProducerRecord(OUTPUT_TOPIC, record));
|
|
||||||
|
|
||||||
Map<TopicPartition, OffsetAndMetadata> offsetsToCommit = new HashMap<>();
|
Map<TopicPartition, OffsetAndMetadata> offsetsToCommit = new HashMap<>();
|
||||||
|
|
||||||
|
@ -51,7 +58,7 @@ public class TransactionalApp {
|
||||||
List<ConsumerRecord<String, String>> partitionedRecords = records.records(partition);
|
List<ConsumerRecord<String, String>> partitionedRecords = records.records(partition);
|
||||||
long offset = partitionedRecords.get(partitionedRecords.size() - 1).offset();
|
long offset = partitionedRecords.get(partitionedRecords.size() - 1).offset();
|
||||||
|
|
||||||
offsetsToCommit.put(partition, new OffsetAndMetadata(offset));
|
offsetsToCommit.put(partition, new OffsetAndMetadata(offset + 1));
|
||||||
}
|
}
|
||||||
|
|
||||||
producer.sendOffsetsToTransaction(offsetsToCommit, CONSUMER_GROUP_ID);
|
producer.sendOffsetsToTransaction(offsetsToCommit, CONSUMER_GROUP_ID);
|
||||||
|
@ -68,11 +75,12 @@ public class TransactionalApp {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static KafkaConsumer<String, String> initConsumer() {
|
private static KafkaConsumer<String, String> createKafkaConsumer() {
|
||||||
Properties props = new Properties();
|
Properties props = new Properties();
|
||||||
props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
|
props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
|
||||||
props.put(GROUP_ID_CONFIG, CONSUMER_GROUP_ID);
|
props.put(GROUP_ID_CONFIG, CONSUMER_GROUP_ID);
|
||||||
props.put(ENABLE_AUTO_COMMIT_CONFIG, "false");
|
props.put(ENABLE_AUTO_COMMIT_CONFIG, "false");
|
||||||
|
props.put(ISOLATION_LEVEL_CONFIG, "read_committed");
|
||||||
props.put(KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
|
props.put(KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
|
||||||
props.put(VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
|
props.put(VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
|
||||||
|
|
||||||
|
@ -81,19 +89,14 @@ public class TransactionalApp {
|
||||||
return consumer;
|
return consumer;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static KafkaProducer<String, String> initProducer() {
|
private static KafkaProducer<String, String> createKafkaProducer() {
|
||||||
|
|
||||||
Properties props = new Properties();
|
Properties props = new Properties();
|
||||||
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
|
props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
|
||||||
props.put(ACKS_CONFIG, "all");
|
|
||||||
props.put(RETRIES_CONFIG, 3);
|
|
||||||
props.put(BATCH_SIZE_CONFIG, 16384);
|
|
||||||
props.put(LINGER_MS_CONFIG, 1);
|
|
||||||
props.put(BUFFER_MEMORY_CONFIG, 33554432);
|
|
||||||
props.put(ENABLE_IDEMPOTENCE_CONFIG, "true");
|
props.put(ENABLE_IDEMPOTENCE_CONFIG, "true");
|
||||||
props.put(TRANSACTIONAL_ID_CONFIG, "prod-1");
|
props.put(TRANSACTIONAL_ID_CONFIG, "prod-1");
|
||||||
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
|
props.put(KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
|
||||||
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
|
props.put(VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
|
||||||
|
|
||||||
return new KafkaProducer(props);
|
return new KafkaProducer(props);
|
||||||
|
|
|
@ -0,0 +1,24 @@
|
||||||
|
package com.baeldung.kafka;
|
||||||
|
|
||||||
|
public class Tuple {
|
||||||
|
|
||||||
|
private String key;
|
||||||
|
private Integer value;
|
||||||
|
|
||||||
|
private Tuple(String key, Integer value) {
|
||||||
|
this.key = key;
|
||||||
|
this.value = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Tuple of(String key, Integer value){
|
||||||
|
return new Tuple(key,value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getKey() {
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getValue() {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
13
pom.xml
13
pom.xml
|
@ -408,6 +408,7 @@
|
||||||
<!-- <module>jws</module> --><!-- POM jar version repo download failure -->
|
<!-- <module>jws</module> --><!-- POM jar version repo download failure -->
|
||||||
<module>libraries</module>
|
<module>libraries</module>
|
||||||
<module>libraries-data</module>
|
<module>libraries-data</module>
|
||||||
|
<module>libraries-security</module>
|
||||||
<module>libraries-server</module>
|
<module>libraries-server</module>
|
||||||
<module>linkrest</module>
|
<module>linkrest</module>
|
||||||
<module>logging-modules/log-mdc</module>
|
<module>logging-modules/log-mdc</module>
|
||||||
|
@ -606,7 +607,7 @@
|
||||||
<module>jta</module>
|
<module>jta</module>
|
||||||
<!--<module>java-dates</module> --> <!-- Commented because we have still not upgraded to java 9 -->
|
<!--<module>java-dates</module> --> <!-- Commented because we have still not upgraded to java 9 -->
|
||||||
<module>java-websocket</module>
|
<module>java-websocket</module>
|
||||||
<!-- <module>activejdbc</module> --><!-- PMD voilation -->
|
<module>activejdbc</module>
|
||||||
<!-- <module>animal-sniffer-mvn-plugin</module> --><!-- PMD voilation -->
|
<!-- <module>animal-sniffer-mvn-plugin</module> --><!-- PMD voilation -->
|
||||||
<!-- <module>apache-avro</module> --><!-- Malformed POM -->
|
<!-- <module>apache-avro</module> --><!-- Malformed POM -->
|
||||||
<module>apache-bval</module>
|
<module>apache-bval</module>
|
||||||
|
@ -634,7 +635,7 @@
|
||||||
<!-- <module>rest-with-spark-java</module> --><!-- PMD voilation -->
|
<!-- <module>rest-with-spark-java</module> --><!-- PMD voilation -->
|
||||||
<module>spring-boot-autoconfiguration</module>
|
<module>spring-boot-autoconfiguration</module>
|
||||||
<module>spring-boot-custom-starter</module>
|
<module>spring-boot-custom-starter</module>
|
||||||
<!-- <module>spring-boot-jasypt</module> --><!-- PMD voilation -->
|
<module>spring-boot-jasypt</module>
|
||||||
<!-- <module>spring-custom-aop</module> --><!-- Malformed POM -->
|
<!-- <module>spring-custom-aop</module> --><!-- Malformed POM -->
|
||||||
<module>spring-data-rest-querydsl</module>
|
<module>spring-data-rest-querydsl</module>
|
||||||
<!-- <module>spring-groovy</module> --><!-- PMD voilation -->
|
<!-- <module>spring-groovy</module> --><!-- PMD voilation -->
|
||||||
|
@ -651,11 +652,11 @@
|
||||||
<!-- <module>static-analysis</module> --><!-- PMD voilation -->
|
<!-- <module>static-analysis</module> --><!-- PMD voilation -->
|
||||||
<module>stripe</module>
|
<module>stripe</module>
|
||||||
<!-- <module>structurizr</module> --><!-- Artiifact not found -->
|
<!-- <module>structurizr</module> --><!-- Artiifact not found -->
|
||||||
<!-- <module>Twitter4J</module> --><!-- Test failure -->
|
<module>Twitter4J</module>
|
||||||
<module>wicket</module>
|
<module>wicket</module>
|
||||||
<module>xstream</module>
|
<module>xstream</module>
|
||||||
<module>cas/cas-secured-app</module>
|
<module>cas/cas-secured-app</module>
|
||||||
<!-- <module>cas/cas-server</module> --><!-- Takes too much time -->
|
<module>cas/cas-server</module>
|
||||||
<!-- <module>graphql/graphql-java</module> --><!-- Wrong parent -->
|
<!-- <module>graphql/graphql-java</module> --><!-- Wrong parent -->
|
||||||
<!-- <module>guest/deep-jsf</module> --><!-- guest post on different site -->
|
<!-- <module>guest/deep-jsf</module> --><!-- guest post on different site -->
|
||||||
<!-- <module>guest/junit5-example</module> --><!-- guest post on different site - Compilation failure -->
|
<!-- <module>guest/junit5-example</module> --><!-- guest post on different site - Compilation failure -->
|
||||||
|
@ -674,7 +675,7 @@
|
||||||
<!-- <module>rule-engines/rulebook</module> --><!-- Wrong Parent -->
|
<!-- <module>rule-engines/rulebook</module> --><!-- Wrong Parent -->
|
||||||
<module>spring-boot-custom-starter/greeter</module>
|
<module>spring-boot-custom-starter/greeter</module>
|
||||||
<module>spring-boot-h2/spring-boot-h2-database</module>
|
<module>spring-boot-h2/spring-boot-h2-database</module>
|
||||||
<module>spring-boot-h2/spring-boot-h2-remote-app</module>
|
<!--module>spring-boot-h2/spring-boot-h2-remote-app</module-->
|
||||||
<!-- <module>guest\webservices\rest-client</module> --><!-- guest post on different site -->
|
<!-- <module>guest\webservices\rest-client</module> --><!-- guest post on different site -->
|
||||||
<!-- <module>guest\webservices\rest-server</module> --><!-- PMD voilation -->
|
<!-- <module>guest\webservices\rest-server</module> --><!-- PMD voilation -->
|
||||||
<!-- <module>guest\webservices\spring-rest-service</module> --><!-- guest post on different site -->
|
<!-- <module>guest\webservices\spring-rest-service</module> --><!-- guest post on different site -->
|
||||||
|
@ -991,7 +992,7 @@
|
||||||
<!-- <module>rule-engines/rulebook</module> --><!-- Wrong Parent -->
|
<!-- <module>rule-engines/rulebook</module> --><!-- Wrong Parent -->
|
||||||
<module>spring-boot-custom-starter/greeter</module>
|
<module>spring-boot-custom-starter/greeter</module>
|
||||||
<module>spring-boot-h2/spring-boot-h2-database</module>
|
<module>spring-boot-h2/spring-boot-h2-database</module>
|
||||||
<module>spring-boot-h2/spring-boot-h2-remote-app</module>
|
<!--module>spring-boot-h2/spring-boot-h2-remote-app</module-->
|
||||||
<!-- <module>guest\webservices\rest-client</module> --><!-- guest post on different site -->
|
<!-- <module>guest\webservices\rest-client</module> --><!-- guest post on different site -->
|
||||||
<!-- <module>guest\webservices\rest-server</module> --><!-- PMD voilation -->
|
<!-- <module>guest\webservices\rest-server</module> --><!-- PMD voilation -->
|
||||||
<!-- <module>guest\webservices\spring-rest-service</module> --><!-- guest post on different site -->
|
<!-- <module>guest\webservices\spring-rest-service</module> --><!-- guest post on different site -->
|
||||||
|
|
|
@ -71,10 +71,8 @@
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<flips-web.version>1.0.1</flips-web.version>
|
<flips-web.version>1.0.1</flips-web.version>
|
||||||
<lombok.version>1.16.18</lombok.version>
|
<lombok.version>1.16.18</lombok.version>
|
||||||
<java.version>1.8</java.version>
|
|
||||||
<h2database.version>1.4.197</h2database.version>
|
<h2database.version>1.4.197</h2database.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
|
|
@ -39,7 +39,7 @@ public class EmployeeFunctionalConfig {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
RouterFunction<ServerResponse> updateEmployee() {
|
RouterFunction<ServerResponse> updateEmployeeRoute() {
|
||||||
return route(POST("/employees/update"),
|
return route(POST("/employees/update"),
|
||||||
req -> req.body(toMono(Employee.class))
|
req -> req.body(toMono(Employee.class))
|
||||||
.doOnNext(employeeRepository()::updateEmployee)
|
.doOnNext(employeeRepository()::updateEmployee)
|
||||||
|
|
|
@ -1,13 +1,37 @@
|
||||||
package com.baeldung.reactive.functional;
|
package com.baeldung.reactive.functional;
|
||||||
|
|
||||||
|
import static org.mockito.BDDMockito.given;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.FixMethodOrder;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.junit.runners.MethodSorters;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||||
|
|
||||||
import com.baeldung.webflux.Employee;
|
import com.baeldung.webflux.Employee;
|
||||||
|
import com.baeldung.webflux.EmployeeRepository;
|
||||||
|
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = EmployeeSpringFunctionalApplication.class)
|
||||||
|
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
|
||||||
public class EmployeeSpringFunctionalIntegrationTest {
|
public class EmployeeSpringFunctionalIntegrationTest {
|
||||||
|
|
||||||
private static EmployeeFunctionalConfig config = new EmployeeFunctionalConfig();
|
@Autowired
|
||||||
|
private EmployeeFunctionalConfig config;
|
||||||
|
|
||||||
|
@MockBean
|
||||||
|
private EmployeeRepository employeeRepository;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenEmployeeId_whenGetEmployeeById_thenCorrectEmployee() {
|
public void givenEmployeeId_whenGetEmployeeById_thenCorrectEmployee() {
|
||||||
|
@ -15,7 +39,9 @@ public class EmployeeSpringFunctionalIntegrationTest {
|
||||||
.bindToRouterFunction(config.getEmployeeByIdRoute())
|
.bindToRouterFunction(config.getEmployeeByIdRoute())
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
Employee expected = new Employee("1", "Employee 1");
|
Employee employee = new Employee("1", "Employee 1");
|
||||||
|
|
||||||
|
given(employeeRepository.findEmployeeById("1")).willReturn(Mono.just(employee));
|
||||||
|
|
||||||
client.get()
|
client.get()
|
||||||
.uri("/employees/1")
|
.uri("/employees/1")
|
||||||
|
@ -23,6 +49,50 @@ public class EmployeeSpringFunctionalIntegrationTest {
|
||||||
.expectStatus()
|
.expectStatus()
|
||||||
.isOk()
|
.isOk()
|
||||||
.expectBody(Employee.class)
|
.expectBody(Employee.class)
|
||||||
.isEqualTo(expected);
|
.isEqualTo(employee);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGetAllEmployees_thenCorrectEmployees() {
|
||||||
|
WebTestClient client = WebTestClient
|
||||||
|
.bindToRouterFunction(config.getAllEmployeesRoute())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
List<Employee> employeeList = new ArrayList<>();
|
||||||
|
|
||||||
|
Employee employee1 = new Employee("1", "Employee 1");
|
||||||
|
Employee employee2 = new Employee("2", "Employee 2");
|
||||||
|
|
||||||
|
employeeList.add(employee1);
|
||||||
|
employeeList.add(employee2);
|
||||||
|
|
||||||
|
Flux<Employee> employeeFlux = Flux.fromIterable(employeeList);
|
||||||
|
given(employeeRepository.findAllEmployees()).willReturn(employeeFlux);
|
||||||
|
|
||||||
|
client.get()
|
||||||
|
.uri("/employees")
|
||||||
|
.exchange()
|
||||||
|
.expectStatus()
|
||||||
|
.isOk()
|
||||||
|
.expectBodyList(Employee.class)
|
||||||
|
.isEqualTo(employeeList);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUpdateEmployee_thenEmployeeUpdated() {
|
||||||
|
WebTestClient client = WebTestClient
|
||||||
|
.bindToRouterFunction(config.updateEmployeeRoute())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
Employee employee = new Employee("1", "Employee 1 Updated");
|
||||||
|
|
||||||
|
client.post()
|
||||||
|
.uri("/employees/update")
|
||||||
|
.body(Mono.just(employee), Employee.class)
|
||||||
|
.exchange()
|
||||||
|
.expectStatus()
|
||||||
|
.isOk();
|
||||||
|
|
||||||
|
verify(employeeRepository).updateEmployee(employee);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -22,6 +22,8 @@
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||||
<java.version>1.8</java.version>
|
<java.version>1.8</java.version>
|
||||||
|
<!-- The main class to start by executing java -jar -->
|
||||||
|
<start-class>com.mycorp.starter.HelloWorldApplication</start-class>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.h2db.demo;
|
package com.baeldung.h2db.demo.client;
|
||||||
|
|
||||||
import java.sql.ResultSet;
|
import java.sql.ResultSet;
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
|
@ -7,16 +7,20 @@ import javax.annotation.PostConstruct;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
|
import org.springframework.context.annotation.PropertySource;
|
||||||
import org.springframework.jdbc.core.JdbcTemplate;
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
import org.springframework.jdbc.core.RowMapper;
|
import org.springframework.jdbc.core.RowMapper;
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
|
@ComponentScan("com.baeldung.h2db.demo.client")
|
||||||
public class ClientSpringBootApp {
|
public class ClientSpringBootApp {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private JdbcTemplate jdbcTemplate;
|
private JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
System.setProperty("spring.datasource.url","jdbc:h2:tcp://localhost:9091/mem:mydb");
|
||||||
SpringApplication.run(ClientSpringBootApp.class, args);
|
SpringApplication.run(ClientSpringBootApp.class, args);
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.h2db.demo;
|
package com.baeldung.h2db.demo.server;
|
||||||
|
|
||||||
import java.sql.ResultSet;
|
import java.sql.ResultSet;
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
|
@ -9,10 +9,12 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
import org.springframework.jdbc.core.JdbcTemplate;
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
import org.springframework.jdbc.core.RowMapper;
|
import org.springframework.jdbc.core.RowMapper;
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
|
@ComponentScan("com.baeldung.h2db.demo.server")
|
||||||
public class SpringBootApp {
|
public class SpringBootApp {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
|
@ -24,8 +26,7 @@ public class SpringBootApp {
|
||||||
|
|
||||||
@PostConstruct
|
@PostConstruct
|
||||||
private void initDb() {
|
private void initDb() {
|
||||||
System.out.println(String.format(
|
System.out.println(String.format("****** Creating table: %s, and Inserting test data ******", "Employees"));
|
||||||
"****** Creating table: %s, and Inserting test data ******", "Employees"));
|
|
||||||
|
|
||||||
String sqlStatements[] = {
|
String sqlStatements[] = {
|
||||||
"drop table employees if exists",
|
"drop table employees if exists",
|
|
@ -1,25 +0,0 @@
|
||||||
/target/
|
|
||||||
!.mvn/wrapper/maven-wrapper.jar
|
|
||||||
|
|
||||||
### STS ###
|
|
||||||
.apt_generated
|
|
||||||
.classpath
|
|
||||||
.factorypath
|
|
||||||
.project
|
|
||||||
.settings
|
|
||||||
.springBeans
|
|
||||||
.sts4-cache
|
|
||||||
|
|
||||||
### IntelliJ IDEA ###
|
|
||||||
.idea
|
|
||||||
*.iws
|
|
||||||
*.iml
|
|
||||||
*.ipr
|
|
||||||
|
|
||||||
### NetBeans ###
|
|
||||||
/nbproject/private/
|
|
||||||
/build/
|
|
||||||
/nbbuild/
|
|
||||||
/dist/
|
|
||||||
/nbdist/
|
|
||||||
/.nb-gradle/
|
|
|
@ -1,55 +0,0 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
|
||||||
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.h2db</groupId>
|
|
||||||
<artifactId>spring-boot-h2-remote-app</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<packaging>jar</packaging>
|
|
||||||
|
|
||||||
<description>Demo Spring Boot applications that access H2 in memory database created
|
|
||||||
in another Spring Boot application
|
|
||||||
</description>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-parent</artifactId>
|
|
||||||
<version>2.0.4.RELEASE</version>
|
|
||||||
<relativePath/> <!-- lookup parent from repository -->
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
|
||||||
<java.version>1.8</java.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.h2database</groupId>
|
|
||||||
<artifactId>h2</artifactId>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-test</artifactId>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
</project>
|
|
|
@ -1,5 +0,0 @@
|
||||||
spring.datasource.url=jdbc:h2:tcp://localhost:9091/mem:mydb
|
|
||||||
spring.datasource.driverClassName=org.h2.Driver
|
|
||||||
spring.datasource.username=sa
|
|
||||||
spring.datasource.password=
|
|
||||||
spring.jpa.hibernate.ddl-auto=create
|
|
|
@ -5,7 +5,6 @@
|
||||||
|
|
||||||
<groupId>com.example.jasypt</groupId>
|
<groupId>com.example.jasypt</groupId>
|
||||||
<artifactId>spring-boot-jasypt</artifactId>
|
<artifactId>spring-boot-jasypt</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
<name>spring-boot-jasypt</name>
|
<name>spring-boot-jasypt</name>
|
||||||
<description>Demo project for Spring Boot</description>
|
<description>Demo project for Spring Boot</description>
|
||||||
|
@ -52,9 +51,6 @@
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
|
||||||
<java.version>1.8</java.version>
|
|
||||||
<jasypt.version>2.0.0</jasypt.version>
|
<jasypt.version>2.0.0</jasypt.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
|
|
@ -14,7 +14,7 @@ import com.baeldung.jasypt.Main;
|
||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
@SpringBootTest(classes = {Main.class})
|
@SpringBootTest(classes = {Main.class})
|
||||||
public class CustomJasyptTest {
|
public class CustomJasyptIntegrationTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
ApplicationContext appCtx;
|
ApplicationContext appCtx;
|
|
@ -13,7 +13,7 @@ import com.baeldung.jasypt.simple.PropertyServiceForJasyptSimple;
|
||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
@SpringBootTest
|
@SpringBootTest
|
||||||
public class JasyptSimpleTest {
|
public class JasyptSimpleIntegrationTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
ApplicationContext appCtx;
|
ApplicationContext appCtx;
|
|
@ -14,7 +14,7 @@ import com.baeldung.jasypt.starter.PropertyServiceForJasyptStarter;
|
||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
@SpringBootTest
|
@SpringBootTest
|
||||||
public class JasyptWithStarterTest {
|
public class JasyptWithStarterIntegrationTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
ApplicationContext appCtx;
|
ApplicationContext appCtx;
|
|
@ -1,14 +1,12 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<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">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<artifactId>disabling-console-jul</artifactId>
|
<artifactId>disabling-console-jul</artifactId>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>spring-boot-starter-parent</artifactId>
|
<artifactId>disabling-console-logging</artifactId>
|
||||||
<version>2.0.4.RELEASE</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
@ -45,9 +43,4 @@
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
|
||||||
<java.version>1.8</java.version>
|
|
||||||
</properties>
|
|
||||||
</project>
|
</project>
|
|
@ -1,13 +1,12 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<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">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<artifactId>disabling-console-log4j2</artifactId>
|
<artifactId>disabling-console-log4j2</artifactId>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>spring-boot-starter-parent</artifactId>
|
<artifactId>disabling-console-logging</artifactId>
|
||||||
<version>2.0.4.RELEASE</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
@ -40,10 +39,4 @@
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
|
||||||
<java.version>1.8</java.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -1,8 +1,6 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<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">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>disabling-console-logging</artifactId>
|
<artifactId>disabling-console-logging</artifactId>
|
||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
<description>Projects for Disabling Spring Boot Console Logging tutorials</description>
|
<description>Projects for Disabling Spring Boot Console Logging tutorials</description>
|
||||||
|
|
|
@ -3,9 +3,7 @@
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>spring-boot-logging-log4j2</artifactId>
|
<artifactId>spring-boot-logging-log4j2</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
<description>Projects for Spring Boot Logging tutorials</description>
|
<description>Projects for Spring Boot Logging tutorials</description>
|
||||||
|
|
||||||
|
@ -43,10 +41,4 @@
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
|
||||||
<java.version>1.8</java.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -3,9 +3,7 @@
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>spring-boot-logging-log4j2-app</artifactId>
|
<artifactId>spring-boot-logging-log4j2-app</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
<description>Demo project for Spring Boot Logging with Log4J2</description>
|
<description>Demo project for Spring Boot Logging with Log4J2</description>
|
||||||
|
|
||||||
|
|
|
@ -2,12 +2,10 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<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">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>spring-boot-mvc</artifactId>
|
<artifactId>spring-boot-mvc</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
<name>spring-boot-mvc</name>
|
<name>spring-boot-mvc</name>
|
||||||
<description>Demo project for Spring Boot</description>
|
<description>Module For Spring Boot MVC</description>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<artifactId>parent-boot-2</artifactId>
|
<artifactId>parent-boot-2</artifactId>
|
||||||
|
@ -21,6 +19,32 @@
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<!--JSF-->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.sun.faces</groupId>
|
||||||
|
<artifactId>jsf-api</artifactId>
|
||||||
|
<version>2.2.9</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.tomcat.embed</groupId>
|
||||||
|
<artifactId>tomcat-embed-jasper</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.faces</groupId>
|
||||||
|
<artifactId>javax.faces-api</artifactId>
|
||||||
|
<version>2.1</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.servlet</groupId>
|
||||||
|
<artifactId>jstl</artifactId>
|
||||||
|
<version>1.2</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.sun.faces</groupId>
|
||||||
|
<artifactId>jsf-impl</artifactId>
|
||||||
|
<version>2.2.8-02</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
@ -55,9 +79,6 @@
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
|
||||||
<java.version>1.8</java.version>
|
|
||||||
<!-- ROME for RSS -->
|
<!-- ROME for RSS -->
|
||||||
<rome.version>1.10.0</rome.version>
|
<rome.version>1.10.0</rome.version>
|
||||||
<start-class>com.baeldung.springbootmvc.SpringBootMvcApplication</start-class>
|
<start-class>com.baeldung.springbootmvc.SpringBootMvcApplication</start-class>
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.springbootmvc.nosuchbeandefinitionexception;
|
package com.baeldung.nosuchbeandefinitionexception;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
|
@ -0,0 +1,5 @@
|
||||||
|
package com.baeldung.nosuchbeandefinitionexception;
|
||||||
|
|
||||||
|
public class BeanB {
|
||||||
|
|
||||||
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.springbootmvc.nosuchbeandefinitionexception;
|
package com.baeldung.nosuchbeandefinitionexception;
|
||||||
|
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
|
@ -0,0 +1,31 @@
|
||||||
|
package com.baeldung.springbootmvc.jsfapplication;
|
||||||
|
|
||||||
|
import javax.faces.webapp.FacesServlet;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.web.servlet.ServletRegistrationBean;
|
||||||
|
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
|
|
||||||
|
import com.baeldung.springbootmvc.jsfapplication.controller.JsfController;
|
||||||
|
import com.baeldung.springbootmvc.jsfapplication.model.TodoDao;
|
||||||
|
import com.baeldung.springbootmvc.jsfapplication.service.TodoService;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
@ComponentScan(basePackageClasses = { JsfController.class, TodoDao.class, TodoService.class })
|
||||||
|
public class JsfApplication extends SpringBootServletInitializer {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(JsfApplication.class, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public ServletRegistrationBean servletRegistrationBean() {
|
||||||
|
FacesServlet servlet = new FacesServlet();
|
||||||
|
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(servlet, "*.jsf");
|
||||||
|
return servletRegistrationBean;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,19 @@
|
||||||
|
package com.baeldung.springbootmvc.jsfapplication.controller;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Scope;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Scope(value = "session")
|
||||||
|
@Component(value = "jsfController")
|
||||||
|
public class JsfController {
|
||||||
|
|
||||||
|
public String loadTodoPage() {
|
||||||
|
checkPermission();
|
||||||
|
return "/todo.xhtml";
|
||||||
|
}
|
||||||
|
|
||||||
|
private void checkPermission() {
|
||||||
|
// Details omitted
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
package com.baeldung.springbootmvc.jsfapplication.model;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public interface Dao<T> {
|
||||||
|
|
||||||
|
Optional<T> get(int id);
|
||||||
|
|
||||||
|
Collection<T> getAll();
|
||||||
|
|
||||||
|
int save(T t);
|
||||||
|
|
||||||
|
void update(T t);
|
||||||
|
|
||||||
|
void delete(T t);
|
||||||
|
}
|
|
@ -0,0 +1,32 @@
|
||||||
|
package com.baeldung.springbootmvc.jsfapplication.model;
|
||||||
|
|
||||||
|
public class Todo {
|
||||||
|
|
||||||
|
private int id;
|
||||||
|
private String message;
|
||||||
|
private int priority;
|
||||||
|
|
||||||
|
public int getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(int id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getMessage() {
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMessage(String message) {
|
||||||
|
this.message = message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getPriority() {
|
||||||
|
return priority;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPriority(int priority) {
|
||||||
|
this.priority = priority;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,48 @@
|
||||||
|
package com.baeldung.springbootmvc.jsfapplication.model;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class TodoDao implements Dao<Todo> {
|
||||||
|
|
||||||
|
private List<Todo> todoList = new ArrayList<>();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<Todo> get(int id) {
|
||||||
|
return Optional.ofNullable(todoList.get(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Collection<Todo> getAll() {
|
||||||
|
return todoList.stream()
|
||||||
|
.filter(Objects::nonNull)
|
||||||
|
.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int save(Todo todo) {
|
||||||
|
todoList.add(todo);
|
||||||
|
int index = todoList.size() - 1;
|
||||||
|
todo.setId(index);
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void update(Todo todo) {
|
||||||
|
todoList.set(todo.getId(), todo);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void delete(Todo todo) {
|
||||||
|
todoList.set(todo.getId(), null);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,50 @@
|
||||||
|
package com.baeldung.springbootmvc.jsfapplication.service;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.context.annotation.Scope;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import com.baeldung.springbootmvc.jsfapplication.model.Dao;
|
||||||
|
import com.baeldung.springbootmvc.jsfapplication.model.Todo;
|
||||||
|
|
||||||
|
@Scope(value = "session")
|
||||||
|
@Component(value = "todoService")
|
||||||
|
public class TodoService {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private Dao<Todo> todoDao;
|
||||||
|
private Todo todo = new Todo();
|
||||||
|
|
||||||
|
public void save() {
|
||||||
|
todoDao.save(todo);
|
||||||
|
todo = new Todo();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Collection<Todo> getAllTodo() {
|
||||||
|
return todoDao.getAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Collection<Todo> getAllTodoSortedByPriority() {
|
||||||
|
return todoDao.getAll()
|
||||||
|
.stream()
|
||||||
|
.sorted(Comparator.comparingInt(Todo::getId))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
public int saveTodo(Todo todo) {
|
||||||
|
validate(todo);
|
||||||
|
return todoDao.save(todo);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validate(Todo todo) {
|
||||||
|
// Details omitted
|
||||||
|
}
|
||||||
|
|
||||||
|
public Todo getTodo() {
|
||||||
|
return todo;
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,5 +0,0 @@
|
||||||
package com.baeldung.springbootmvc.nosuchbeandefinitionexception;
|
|
||||||
|
|
||||||
public class BeanB {
|
|
||||||
|
|
||||||
}
|
|
|
@ -0,0 +1,9 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
|
||||||
|
version="2.2">
|
||||||
|
<application>
|
||||||
|
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
|
||||||
|
</application>
|
||||||
|
</faces-config>
|
|
@ -0,0 +1,21 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
|
||||||
|
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
|
||||||
|
version="3.0">
|
||||||
|
|
||||||
|
<servlet>
|
||||||
|
<servlet-name>Faces Servlet</servlet-name>
|
||||||
|
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
|
||||||
|
<load-on-startup>1</load-on-startup>
|
||||||
|
</servlet>
|
||||||
|
<servlet-mapping>
|
||||||
|
<servlet-name>Faces Servlet</servlet-name>
|
||||||
|
<url-pattern>*.jsf</url-pattern>
|
||||||
|
</servlet-mapping>
|
||||||
|
<context-param>
|
||||||
|
<param-name>com.sun.faces.forceLoadConfiguration</param-name>
|
||||||
|
<param-value>true</param-value>
|
||||||
|
</context-param>
|
||||||
|
</web-app>
|
|
@ -0,0 +1,20 @@
|
||||||
|
<f:view xmlns="http://www.w3c.org/1999/xhtml"
|
||||||
|
xmlns:f="http://java.sun.com/jsf/core"
|
||||||
|
xmlns:h="http://java.sun.com/jsf/html">
|
||||||
|
<h:head>
|
||||||
|
<meta charset="utf-8"/>
|
||||||
|
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
|
||||||
|
<title>TO-DO application</title>
|
||||||
|
</h:head>
|
||||||
|
<h:body>
|
||||||
|
<div>
|
||||||
|
<p>Welcome in the TO-DO application!</p>
|
||||||
|
<p style="height:50px">
|
||||||
|
This is a static message rendered from xhtml.
|
||||||
|
<h:form>
|
||||||
|
<h:commandButton value="Load To-do page!" action="#{jsfController.loadTodoPage}" />
|
||||||
|
</h:form>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</h:body>
|
||||||
|
</f:view>
|
|
@ -0,0 +1,38 @@
|
||||||
|
<f:view xmlns="http://www.w3c.org/1999/xhtml"
|
||||||
|
xmlns:f="http://java.sun.com/jsf/core"
|
||||||
|
xmlns:h="http://java.sun.com/jsf/html">
|
||||||
|
<h:head>
|
||||||
|
<meta charset="utf-8"/>
|
||||||
|
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
|
||||||
|
<title>TO-DO application</title>
|
||||||
|
</h:head>
|
||||||
|
<h:body>
|
||||||
|
<div>
|
||||||
|
<div>
|
||||||
|
List of TO-DO items
|
||||||
|
</div>
|
||||||
|
<h:dataTable value="#{todoService.allTodo}" var="item">
|
||||||
|
<h:column>
|
||||||
|
<f:facet name="header"> Message</f:facet>
|
||||||
|
#{item.message}
|
||||||
|
</h:column>
|
||||||
|
<h:column>
|
||||||
|
<f:facet name="header"> Priority</f:facet>
|
||||||
|
#{item.priority}
|
||||||
|
</h:column>
|
||||||
|
</h:dataTable>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div>
|
||||||
|
Add new to-do item:
|
||||||
|
</div>
|
||||||
|
<h:form>
|
||||||
|
<h:outputLabel for="message" value="Message: "/>
|
||||||
|
<h:inputText id="message" value="#{todoService.todo.message}"/>
|
||||||
|
<h:outputLabel for="priority" value="Priority: "/>
|
||||||
|
<h:inputText id="priority" value="#{todoService.todo.priority}" converterMessage="Please enter digits only."/>
|
||||||
|
<h:commandButton value="Save" action="#{todoService.save}"/>
|
||||||
|
</h:form>
|
||||||
|
</div>
|
||||||
|
</h:body>
|
||||||
|
</f:view>
|
|
@ -35,6 +35,7 @@
|
||||||
<module>spring-cloud-archaius</module>
|
<module>spring-cloud-archaius</module>
|
||||||
<module>spring-cloud-functions</module>
|
<module>spring-cloud-functions</module>
|
||||||
<module>spring-cloud-vault</module>
|
<module>spring-cloud-vault</module>
|
||||||
|
<module>spring-cloud-security</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue