Merge remote-tracking branch 'origin/master'

This commit is contained in:
slavisa-baeldung 2017-04-02 08:07:48 +01:00
commit 6d8e3fa960
48 changed files with 470 additions and 415 deletions

View File

@ -10,9 +10,15 @@
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>

View File

@ -1,4 +1,4 @@
package com.baeldung.primechecker;
package com.baeldung.algorithms.primechecker;
import java.math.BigInteger;

View File

@ -1,4 +1,4 @@
package com.baeldung.primechecker;
package com.baeldung.algorithms.primechecker;
import java.util.stream.IntStream;
@ -6,7 +6,7 @@ public class BruteForcePrimeChecker implements PrimeChecker{
@Override
public boolean isPrime(int number) {
return IntStream.range(2, number).filter(n -> (number % n == 0)).count() == 0;
return IntStream.range(2, number).noneMatch(n -> (number % n == 0));
}

View File

@ -1,4 +1,4 @@
package com.baeldung.primechecker;
package com.baeldung.algorithms.primechecker;
import java.util.stream.IntStream;
@ -7,8 +7,7 @@ public class OptimisedPrimeChecker implements PrimeChecker{
@Override
public boolean isPrime(int number) {
return IntStream.range(2, (int)Math.sqrt(number) + 1)
.filter(n -> (number % n == 0))
.count() == 0;
.noneMatch(n -> (number % n == 0));
}

View File

@ -1,4 +1,4 @@
package com.baeldung.primechecker;
package com.baeldung.algorithms.primechecker;
public interface PrimeChecker {

View File

@ -1,4 +1,4 @@
package com.baeldung.primechecker;
package com.baeldung.algorithms.primechecker;
import org.apache.commons.math3.primes.Primes;

View File

@ -1,9 +1,12 @@
package com.baeldung.primechecker;
package com.baeldung.algorithms.primechecker;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.baeldung.algorithms.primechecker.BigIntegerPrimeChecker;
import com.baeldung.algorithms.primechecker.PrimeChecker;
public class BigIntegerPrimeCheckerTest {
PrimeChecker primeChecker = new BigIntegerPrimeChecker();

View File

@ -1,6 +1,9 @@
package com.baeldung.primechecker;
package com.baeldung.algorithms.primechecker;
import org.junit.Test;
import com.baeldung.algorithms.primechecker.BruteForcePrimeChecker;
import static org.junit.Assert.*;
public class BruteForcePrimeCheckerTest {

View File

@ -1,9 +1,12 @@
package com.baeldung.primechecker;
package com.baeldung.algorithms.primechecker;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.baeldung.algorithms.primechecker.OptimisedPrimeChecker;
import com.baeldung.algorithms.primechecker.PrimeChecker;
public class OptimisedPrimeCheckerTest {
PrimeChecker primeChecker = new OptimisedPrimeChecker();

View File

@ -1,9 +1,12 @@
package com.baeldung.primechecker;
package com.baeldung.algorithms.primechecker;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.baeldung.algorithms.primechecker.PrimeChecker;
import com.baeldung.algorithms.primechecker.PrimesPrimeChecker;
public class PrimesPrimeCheckerTest {
PrimeChecker primeChecker = new PrimesPrimeChecker();

View File

@ -18,13 +18,13 @@ public class JacksonMapDeserializeTest {
private Map<MyPair, String> map;
private Map<MyPair, MyPair> cmap;
final ObjectMapper mapper = new ObjectMapper();
@Test
public void whenSimpleMapDeserialize_thenCorrect()
throws JsonParseException, JsonMappingException, IOException {
final String jsonInput = "{\"key\": \"value\"}";
final ObjectMapper mapper = new ObjectMapper();
TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {
};
@ -38,7 +38,6 @@ public class JacksonMapDeserializeTest {
throws JsonParseException, JsonMappingException, IOException {
final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}";
final ObjectMapper mapper = new ObjectMapper();
TypeReference<HashMap<MyPair, String>> typeRef = new TypeReference<HashMap<MyPair, String>>() {
};
@ -59,7 +58,6 @@ public class JacksonMapDeserializeTest {
throws JsonParseException, JsonMappingException, IOException {
final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}";
final ObjectMapper mapper = new ObjectMapper();
TypeReference<HashMap<MyPair, MyPair>> typeRef = new TypeReference<HashMap<MyPair, MyPair>>() {
};

View File

@ -26,6 +26,8 @@ public class JacksonMapSerializeTest {
@JsonSerialize(keyUsing = MyPairSerializer.class)
private MyPair mapValue;
final ObjectMapper mapper = new ObjectMapper();
@Test
public void whenSimpleMapSerialize_thenCorrect()
throws JsonProcessingException {
@ -33,7 +35,6 @@ public class JacksonMapSerializeTest {
Map<String, String> map = new HashMap<>();
map.put("key", "value");
final ObjectMapper mapper = new ObjectMapper();
final String jsonResult = mapper.writeValueAsString(map);
Assert.assertEquals("{\"key\":\"value\"}", jsonResult);
@ -47,7 +48,6 @@ public class JacksonMapSerializeTest {
MyPair key = new MyPair("Abbott", "Costello");
map.put(key, "Comedy");
final ObjectMapper mapper = new ObjectMapper();
final String jsonResult = mapper.writeValueAsString(map);
Assert.assertEquals("{\"Abbott and Costello\":\"Comedy\"}", jsonResult);
@ -62,7 +62,6 @@ public class JacksonMapSerializeTest {
mapValue = new MyPair("Comedy", "1940's");
cmap.put(mapKey, mapValue);
final ObjectMapper mapper = new ObjectMapper();
final String jsonResult = mapper.writeValueAsString(cmap);
Assert.assertEquals("{\"Abbott and Costello\":\"Comedy and 1940's\"}",

View File

@ -2,6 +2,7 @@ package com.baeldung.guice;
import com.baeldung.guice.config.DependencyModule;
import com.baeldung.guice.service.DataPumpService;
import com.baeldung.guice.service.ServiceFactory;
import com.baeldung.guice.service.impl.DataPumpServiceImpl;
import ratpack.guice.Guice;
@ -15,8 +16,8 @@ public class Application {
.start(server -> server.registry(Guice.registry(bindings -> bindings.module(DependencyModule.class)))
.handlers(chain -> chain.get("randomString", ctx -> {
DataPumpService dataPumpService = ctx.get(DataPumpService.class);
ctx.render(dataPumpService.generate().length());
})));
ctx.render(dataPumpService.generate());
}).get("factory", ctx -> ctx.render(ServiceFactory.getInstance().generate()))));
// RatpackServer.start(server -> server
// .registry(Guice
@ -24,8 +25,8 @@ public class Application {
// .handlers(chain -> chain.get("randomString", ctx -> {
// DataPumpService dataPumpService = ctx.get(DataPumpService.class);
// ctx.render(dataPumpService.generate());
// })));
// }).get("factory", ctx -> ctx.render(ServiceFactory.getInstance().generate()))));
}
}
}

View File

@ -1,9 +1,5 @@
package com.baeldung.guice.service;
import com.baeldung.guice.service.impl.DataPumpServiceImpl;
import com.google.inject.ImplementedBy;
@ImplementedBy(DataPumpServiceImpl.class)
public interface DataPumpService {
String generate();

View File

@ -0,0 +1,20 @@
package com.baeldung.guice.service;
import com.baeldung.guice.service.impl.DataPumpServiceImpl;
public class ServiceFactory {
private static DataPumpService instance;
public static void setInstance(DataPumpService dataPumpService) {
instance = dataPumpService;
}
public static DataPumpService getInstance() {
if (instance == null) {
return new DataPumpServiceImpl();
}
return instance;
}
}

View File

@ -43,6 +43,12 @@
<artifactId>spring-retry</artifactId>
<version>${springretry.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.shell</groupId>
<artifactId>spring-shell</artifactId>
<version>${org.springframework.shell.version}</version>
</dependency>
<!-- aspectj -->
@ -280,6 +286,7 @@
<org.springframework.version>4.3.4.RELEASE</org.springframework.version>
<org.springframework.security.version>4.2.0.RELEASE</org.springframework.security.version>
<springretry.version>1.1.5.RELEASE</springretry.version>
<org.springframework.shell.version>1.2.0.RELEASE</org.springframework.shell.version>
<!-- persistence -->
<hibernate.version>5.2.5.Final</hibernate.version>

View File

@ -0,0 +1,10 @@
package org.baeldung.shell;
import java.io.IOException;
import org.springframework.shell.Bootstrap;
public class Main {
public static void main(String[] args) throws IOException {
Bootstrap.main(args);
}
}

View File

@ -0,0 +1,34 @@
package org.baeldung.shell.simple;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.shell.plugin.support.DefaultBannerProvider;
import org.springframework.shell.support.util.OsUtils;
import org.springframework.stereotype.Component;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleBannerProvider extends DefaultBannerProvider {
public String getBanner() {
StringBuffer buf = new StringBuffer();
buf.append("=======================================").append(OsUtils.LINE_SEPARATOR);
buf.append("* Baeldung Shell *").append(OsUtils.LINE_SEPARATOR);
buf.append("=======================================").append(OsUtils.LINE_SEPARATOR);
buf.append("Version:").append(this.getVersion());
return buf.toString();
}
public String getVersion() {
return "1.0.1";
}
public String getWelcomeMessage() {
return "Welcome to Baeldung CLI";
}
@Override
public String getProviderName() {
return "Baeldung Banner";
}
}

View File

@ -0,0 +1,81 @@
package org.baeldung.shell.simple;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.shell.Bootstrap;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.stereotype.Component;
@Component
public class SimpleCLI implements CommandMarker {
private String getContentsOfUrlAsString(URL url) {
StringBuilder sb = new StringBuilder();
try {
try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
}
} catch (IOException ex) {
sb.append("ERROR");
}
return sb.toString();
}
@CliCommand(
value = {"web-get", "wg"},
help = "Displays the contents of a URL."
)
public String webGet(
@CliOption(
key = {"", "url"},
help = "URL whose contents will be displayed."
) URL url) {
return getContentsOfUrlAsString(url);
}
@CliCommand(
value = {"web-save", "ws"},
help = "Saves the contents of a URL.")
public String webSave(
@CliOption(key = {"", "url"}, help = "URL whose contents will be saved.") URL url,
@CliOption(key = {"out", "file"}, mandatory = true, help = "The name of the file.") String file) {
String contents = getContentsOfUrlAsString(url);
try (PrintWriter out = new PrintWriter(file)) {
out.write(contents);
} catch (FileNotFoundException ex) {
//Ignore
}
return "Done.";
}
private boolean adminEnableExecuted = false;
@CliAvailabilityIndicator(value = {"web-save"})
public boolean isAdminEnabled() {
return adminEnableExecuted;
}
@CliCommand(value = "admin-enable")
public String adminEnable() {
adminEnableExecuted = true;
return "Admin commands enabled.";
}
@CliCommand(value = "admin-disable")
public String adminDisable() {
adminEnableExecuted = false;
return "Admin commands disabled.";
}
}

View File

@ -0,0 +1,22 @@
package org.baeldung.shell.simple;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.shell.plugin.support.DefaultHistoryFileNameProvider;
import org.springframework.stereotype.Component;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleHistoryFileNameProvider extends DefaultHistoryFileNameProvider {
@Override
public String getHistoryFileName() {
return "baeldung-shell.log";
}
@Override
public String getProviderName() {
return "Baeldung History";
}
}

View File

@ -0,0 +1,21 @@
package org.baeldung.shell.simple;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.shell.plugin.support.DefaultPromptProvider;
import org.springframework.stereotype.Component;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimplePromptProvider extends DefaultPromptProvider {
@Override
public String getPrompt() {
return "baeldung-shell>";
}
@Override
public String getProviderName() {
return "Baeldung Prompt";
}
}

View File

@ -0,0 +1,35 @@
package org.baeldung.shell.simple;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.springframework.shell.core.Completion;
import org.springframework.shell.core.Converter;
import org.springframework.shell.core.MethodTarget;
import org.springframework.stereotype.Component;
@Component
public class SimpleURLConverter implements Converter<URL> {
@Override
public URL convertFromText(String value, Class<?> requiredType, String optionContext) {
try {
return new URL(value);
} catch (MalformedURLException ex) {
//Ignore
}
return null;
}
@Override
public boolean getAllPossibleValues(List<Completion> completions, Class<?> requiredType,
String existingData, String optionContext, MethodTarget target) {
return false;
}
@Override
public boolean supports(Class<?> requiredType, String optionContext) {
return URL.class.isAssignableFrom(requiredType);
}
}

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<context:component-scan base-package="org.baeldung.shell.simple" />
</beans>

View File

@ -0,0 +1,86 @@
package org.baeldung.shell.simple;
import java.io.File;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.shell.Bootstrap;
import org.springframework.shell.core.CommandResult;
import org.springframework.shell.core.JLineShellComponent;
public class SimpleCLIUnitTest {
static JLineShellComponent shell;
@BeforeClass
public static void startUp() throws InterruptedException {
Bootstrap bootstrap = new Bootstrap();
shell = bootstrap.getJLineShellComponent();
}
@AfterClass
public static void shutdown() {
shell.stop();
}
public static JLineShellComponent getShell() {
return shell;
}
@Test
public void givenCommandConfig_whenExecutingWebGetCommand_thenCorrectResult() {
CommandResult resultWebSave = shell.executeCommand("web-get --url https://www.google.com");
Assert.assertTrue(resultWebSave.isSuccess());
}
@Test
public void givenCommandConfig_whenExecutingWebSaveCommand_thenCorrectResult() {
shell.executeCommand("admin-enable");
CommandResult result = shell.executeCommand("web-save --url https://www.google.com --out contents.txt");
Assert.assertArrayEquals(
new boolean[]{
result.isSuccess(),
new File("contents.txt").exists()},
new boolean[]{true, true});
}
@Test
public void givenCommandConfig_whenAdminEnableCommandExecuted_thenCorrectAvailability() {
CommandResult resultAdminDisable = shell.executeCommand("admin-disable");
CommandResult resultWebSaveUnavailable = shell.executeCommand("web-save --url https://www.google.com --out contents.txt");
CommandResult resultAdminEnable = shell.executeCommand("admin-enable");
CommandResult resultWebSaveAvailable = shell.executeCommand("web-save --url https://www.google.com --out contents.txt");
Assert.assertArrayEquals(
new boolean[]{
resultAdminDisable.isSuccess(),
resultWebSaveUnavailable.isSuccess(),
resultAdminEnable.isSuccess(),
resultWebSaveAvailable.isSuccess()},
new boolean[]{true, false, true, true});
}
@Test
public void givenCommandConfig_whenWebSaveCommandExecutedNoOutArgument_thenError() {
shell.executeCommand("admin-enable");
CommandResult resultWebSave = shell.executeCommand("web-save --url https://www.google.com");
Assert.assertEquals(resultWebSave.isSuccess(), false);
}
@Test
public void givenCommandConfig_whenExecutingWebGetCommandWithDefaultArgument_thenCorrectResult() {
CommandResult result = shell.executeCommand("web-get https://www.google.com");
Assert.assertEquals(result.isSuccess(), true);
}
}

View File

@ -1,6 +0,0 @@
/target/
.settings/
.classpath
.project
*.iml
.idea

View File

@ -1,198 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-boot-auditing</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>spring-boot-auditing</name>
<description>This is simple boot application for Spring boot auditing test</description>
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-core</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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.subethamail</groupId>
<artifactId>subethasmtp</artifactId>
<version>${subethasmtp.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>${bootstrap.version}</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>${jquery.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>${tomee-servlet-api.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-boot</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
</plugin>
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
<version>${git-commit-id-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<spring.version>4.3.7.RELEASE</spring.version>
<git-commit-id-plugin.version>2.2.1</git-commit-id-plugin.version>
<jquery.version>3.1.1</jquery.version>
<bootstrap.version>3.3.7-1</bootstrap.version>
<subethasmtp.version>3.1.7</subethasmtp.version>
<tomee-servlet-api.version>8.5.11</tomee-servlet-api.version>
</properties>
</project>

View File

@ -1,13 +0,0 @@
package org.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Throwable {
SpringApplication.run(Application.class, args);
}
}

View File

@ -1,18 +0,0 @@
package org.baeldung;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}
}

View File

@ -1,34 +0,0 @@
package org.baeldung;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER", "ACTUATOR");
}
}

View File

@ -1 +0,0 @@
logging.level.org.springframework=INFO

View File

@ -1,14 +0,0 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -1,13 +0,0 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
<input type="submit" value="Sign Out"/>
</form>
</body>
</html>

View File

@ -1,11 +0,0 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example</title>
</head>
<body>
<h1>Welcome!</h1>
<p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
</body>
</html>

View File

@ -1,20 +0,0 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="@{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>

View File

@ -32,6 +32,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>

View File

@ -15,11 +15,11 @@ public class LoginAttemptsLogger {
@EventListener
public void auditEventHappened(AuditApplicationEvent auditApplicationEvent) {
AuditEvent auditEvent = auditApplicationEvent.getAuditEvent();
LOGGER.debug("Principal " + auditEvent.getPrincipal() + " - " + auditEvent.getType());
LOGGER.info("Principal " + auditEvent.getPrincipal() + " - " + auditEvent.getType());
WebAuthenticationDetails details = (WebAuthenticationDetails) auditEvent.getData().get("details");
LOGGER.debug(" Remote IP address: " + details.getRemoteAddress());
LOGGER.debug(" Session Id: " + details.getSessionId());
LOGGER.debug(" Request URL: " + auditEvent.getData().get("requestUrl"));
LOGGER.info(" Remote IP address: " + details.getRemoteAddress());
LOGGER.info(" Session Id: " + details.getSessionId());
LOGGER.info(" Request URL: " + auditEvent.getData().get("requestUrl"));
}
}

View File

@ -20,6 +20,9 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("jim").password("jim").roles("USER").and().withUser("pam").password("pam").roles("USER").and().withUser("michael").password("michael").roles("MANAGER");
auth.inMemoryAuthentication()
.withUser("jim").password("jim").roles("USER", "ACTUATOR")
.and().withUser("pam").password("pam").roles("USER")
.and().withUser("michael").password("michael").roles("MANAGER");
}
}

View File

@ -1,9 +1,5 @@
package com.baeldung.spring.statemachine.config;
import java.util.Arrays;
import java.util.HashSet;
import java.util.logging.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.action.Action;
@ -14,6 +10,10 @@ import org.springframework.statemachine.config.builders.StateMachineStateConfigu
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import org.springframework.statemachine.guard.Guard;
import java.util.Arrays;
import java.util.HashSet;
import java.util.logging.Logger;
@Configuration
@EnableStateMachine
public class SimpleStateMachineConfiguration extends StateMachineConfigurerAdapter<String, String> {
@ -21,94 +21,126 @@ public class SimpleStateMachineConfiguration extends StateMachineConfigurerAdapt
public static final Logger LOGGER = Logger.getLogger(SimpleStateMachineConfiguration.class.getName());
@Override
public void configure(StateMachineConfigurationConfigurer<String, String> config)
throws Exception {
public void configure(StateMachineConfigurationConfigurer<String, String> config) throws Exception {
config
.withConfiguration()
.autoStartup(true)
.listener(new StateMachineListener());
.withConfiguration()
.autoStartup(true)
.listener(new StateMachineListener());
}
@Override
public void configure(StateMachineStateConfigurer<String, String> states) throws Exception {
states
.withStates()
.initial("SI")
.end("SF")
.states(new HashSet<>(Arrays.asList("S1", "S2")))
.stateEntry("S3", entryAction())
.stateExit("S3", exitAction())
.state("S4", executeAction(), errorAction())
.stateDo("S5", executeAction());
.withStates()
.initial("SI")
.end("SF")
.states(new HashSet<>(Arrays.asList("S1", "S2")))
.stateEntry("S3", entryAction())
.stateExit("S3", exitAction())
.state("S4", executeAction(), errorAction())
.stateDo("S5", executeAction());
}
@Override
public void configure(StateMachineTransitionConfigurer<String, String> transitions) throws Exception {
transitions.withExternal()
.source("SI").target("S1").event("E1").action(initAction())
.and().withExternal()
.source("S1").target("S2").event("E2")
.and().withExternal()
.source("SI").target("S3").event("E3")
.and().withExternal()
.source("S3").target("S4").event("E4")
.and().withExternal()
.source("S4").target("S5").event("E5")
.and().withExternal()
.source("S5").target("SF").event("end").guard(simpleGuard());
transitions
.withExternal()
.source("SI")
.target("S1")
.event("E1")
.action(initAction())
.and()
.withExternal()
.source("S1")
.target("S2")
.event("E2")
.and()
.withExternal()
.source("SI")
.target("S3")
.event("E3")
.and()
.withExternal()
.source("S3")
.target("S4")
.event("E4")
.and()
.withExternal()
.source("S4")
.target("S5")
.event("E5")
.and()
.withExternal()
.source("S5")
.target("SF")
.event("end")
.guard(simpleGuard());
}
@Bean
public Guard<String, String> simpleGuard() {
return (ctx) -> {
int approvalCount = (int) ctx.getExtendedState().getVariables().getOrDefault("approvalCount", 0);
int approvalCount = (int) ctx
.getExtendedState()
.getVariables()
.getOrDefault("approvalCount", 0);
return approvalCount > 0;
};
}
@Bean
public Action<String, String> entryAction() {
return (ctx) -> {
LOGGER.info("Entry " + ctx.getTarget().getId());
};
return ctx -> LOGGER.info("Entry " + ctx
.getTarget()
.getId());
}
@Bean
public Action<String, String> doAction() {
return (ctx) -> {
LOGGER.info("Do " + ctx.getTarget().getId());
};
return ctx -> LOGGER.info("Do " + ctx
.getTarget()
.getId());
}
@Bean
public Action<String, String> executeAction() {
return (ctx) -> {
LOGGER.info("Execute " + ctx.getTarget().getId());
int approvals = (int) ctx.getExtendedState().getVariables().getOrDefault("approvalCount", 0);
return ctx -> {
LOGGER.info("Execute " + ctx
.getTarget()
.getId());
int approvals = (int) ctx
.getExtendedState()
.getVariables()
.getOrDefault("approvalCount", 0);
approvals++;
ctx.getExtendedState().getVariables().put("approvalCount", approvals);
ctx
.getExtendedState()
.getVariables()
.put("approvalCount", approvals);
};
}
@Bean
public Action<String, String> exitAction() {
return (ctx) -> {
LOGGER.info("Exit " + ctx.getSource().getId() + " -> " + ctx.getTarget().getId());
};
return ctx -> LOGGER.info("Exit " + ctx
.getSource()
.getId() + " -> " + ctx
.getTarget()
.getId());
}
@Bean
public Action<String, String> errorAction() {
return (ctx) -> {
LOGGER.info("Error " + ctx.getSource().getId() + ctx.getException());
};
return ctx -> LOGGER.info("Error " + ctx
.getSource()
.getId() + ctx.getException());
}
@Bean
public Action<String, String> initAction() {
return (ctx) -> {
LOGGER.info(ctx.getTarget().getId());
};
return ctx -> LOGGER.info(ctx
.getTarget()
.getId());
}
}

View File

@ -6,6 +6,7 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.statemachine.StateMachine;
import org.springframework.test.context.ContextConfiguration;
@ -21,7 +22,7 @@ import static org.junit.Assert.assertTrue;
@ContextConfiguration(classes = ForkJoinStateMachineConfiguration.class)
public class ForkJoinStateMachineTest {
@Resource
@Autowired
private StateMachine<String, String> stateMachine;
@Before

View File

@ -6,6 +6,7 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.statemachine.StateMachine;
import org.springframework.test.context.ContextConfiguration;
@ -20,7 +21,7 @@ import static org.junit.Assert.assertEquals;
@ContextConfiguration(classes = HierarchicalStateMachineConfiguration.class)
public class HierarchicalStateMachineTest {
@Resource
@Autowired
private StateMachine<String, String> stateMachine;
@Before

View File

@ -7,6 +7,7 @@ import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.statemachine.StateMachine;
import org.springframework.test.context.ContextConfiguration;
@ -18,7 +19,7 @@ import javax.annotation.Resource;
@ContextConfiguration(classes = JunctionStateMachineConfiguration.class)
public class JunctionStateMachineTest {
@Resource
@Autowired
private StateMachine<String, String> stateMachine;
@Before

View File

@ -8,6 +8,7 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.statemachine.StateMachine;
import org.springframework.test.context.ContextConfiguration;
@ -22,7 +23,7 @@ import static org.junit.Assert.assertTrue;
@ContextConfiguration(classes = SimpleEnumStateMachineConfiguration.class)
public class StateEnumMachineTest {
@Resource
@Autowired
private StateMachine<ApplicationReviewStates, ApplicationReviewEvents> stateMachine;
@Before

View File

@ -7,6 +7,7 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.statemachine.StateMachine;
@ -21,7 +22,7 @@ import javax.annotation.Resource;
@ContextConfiguration(classes = SimpleStateMachineConfiguration.class)
public class StateMachineIntegrationTest {
@Resource
@Autowired
private StateMachine<String, String> stateMachine;
@Before

View File

@ -1,4 +1,4 @@
package com.baledung.rest;
package com.baeldung.rest;
import com.baeldung.model.Article;

View File

@ -5,7 +5,7 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.baledung.rest.RestServiceVerticle;
import com.baeldung.rest.RestServiceVerticle;
import io.vertx.core.Vertx;
import io.vertx.ext.unit.Async;