This commit is contained in:
Seun Matt 2018-01-14 06:11:35 +01:00
commit 510e19789d
45 changed files with 833 additions and 260 deletions

View File

@ -34,3 +34,6 @@
- [Copy a File with Java](http://www.baeldung.com/java-copy-file) - [Copy a File with Java](http://www.baeldung.com/java-copy-file)
- [Generating Prime Numbers in Java](http://www.baeldung.com/java-generate-prime-numbers) - [Generating Prime Numbers in Java](http://www.baeldung.com/java-generate-prime-numbers)
- [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods) - [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods)
- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream)
- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream)
- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices)

View File

@ -101,6 +101,23 @@
<version>1.19</version> <version>1.19</version>
</dependency> </dependency>
<dependency>
<groupId>com.codepoetics</groupId>
<artifactId>protonpack</artifactId>
<version>${protonpack.version}</version>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>${vavr.version}</version>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>${streamex.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -267,6 +284,9 @@
<collections-generic.version>4.01</collections-generic.version> <collections-generic.version>4.01</collections-generic.version>
<commons-codec.version>1.10</commons-codec.version> <commons-codec.version>1.10</commons-codec.version>
<lombok.version>1.16.12</lombok.version> <lombok.version>1.16.12</lombok.version>
<vavr.version>0.9.0</vavr.version>
<protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<!-- testing --> <!-- testing -->
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>

View File

@ -12,11 +12,8 @@
- [Java Directory Size](http://www.baeldung.com/java-folder-size) - [Java Directory Size](http://www.baeldung.com/java-folder-size)
- [Differences Between the Java WatchService API and the Apache Commons IO Monitor Library](http://www.baeldung.com/java-watchservice-vs-apache-commons-io-monitor-library) - [Differences Between the Java WatchService API and the Apache Commons IO Monitor Library](http://www.baeldung.com/java-watchservice-vs-apache-commons-io-monitor-library)
- [Calculate the Size of a File in Java](http://www.baeldung.com/java-file-size) - [Calculate the Size of a File in Java](http://www.baeldung.com/java-file-size)
- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream)
- [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](http://www.baeldung.com/java-path) - [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](http://www.baeldung.com/java-path)
- [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer) - [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer)
- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream)
- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices)
- [Copy a File with Java](http://www.baeldung.com/java-copy-file) - [Copy a File with Java](http://www.baeldung.com/java-copy-file)
- [Java Append Data to a File](http://www.baeldung.com/java-append-to-file) - [Java Append Data to a File](http://www.baeldung.com/java-append-to-file)
- [FileNotFoundException in Java](http://www.baeldung.com/java-filenotfound-exception) - [FileNotFoundException in Java](http://www.baeldung.com/java-filenotfound-exception)

View File

@ -0,0 +1,89 @@
<?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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>plugin</artifactId>
<version>2.33</version>
<relativePath />
</parent>
<artifactId>jenkins-hello-world</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>hpi</packaging>
<properties>
<!-- Baseline Jenkins version you use to build the plugin. Users must have this version or newer to run. -->
<jenkins.version>2.7.3</jenkins.version>
</properties>
<name>Hello World Plugin</name>
<description>A sample Jenkins Hello World plugin</description>
<url>https://wiki.jenkins-ci.org/display/JENKINS/TODO+Plugin</url>
<licenses>
<license>
<name>MIT License</name>
<url>http://opensource.org/licenses/MIT</url>
</license>
</licenses>
<dependencies>
<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>structs</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-step-api</artifactId>
<version>2.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-cps</artifactId>
<version>2.39</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-job</artifactId>
<version>2.11.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-basic-steps</artifactId>
<version>2.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-durable-task-step</artifactId>
<version>2.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-api</artifactId>
<version>2.20</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-support</artifactId>
<version>2.14</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>repo.jenkins-ci.org</id>
<url>https://repo.jenkins-ci.org/public/</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>repo.jenkins-ci.org</id>
<url>https://repo.jenkins-ci.org/public/</url>
</pluginRepository>
</pluginRepositories>
</project>

View File

@ -0,0 +1,20 @@
package com.baeldung.jenkins.helloworld;
public class ProjectStats {
private final int classesNumber;
private final int linesNumber;
public ProjectStats(int classesNumber, int linesNumber) {
this.classesNumber = classesNumber;
this.linesNumber = linesNumber;
}
public int getClassesNumber() {
return classesNumber;
}
public int getLinesNumber() {
return linesNumber;
}
}

View File

@ -0,0 +1,123 @@
package com.baeldung.jenkins.helloworld;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrapperDescriptor;
import org.kohsuke.stapler.DataBoundConstructor;
import javax.annotation.Nonnull;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Stack;
public class ProjectStatsBuildWrapper extends BuildWrapper {
private static final String REPORT_TEMPLATE_PATH = "/stats.html";
private static final String PROJECT_NAME_VAR = "$PROJECT_NAME$";
private static final String CLASSES_NUMBER_VAR = "$CLASSES_NUMBER$";
private static final String LINES_NUMBER_VAR = "$LINES_NUMBER$";
@DataBoundConstructor
public ProjectStatsBuildWrapper() {
}
@Override
public Environment setUp(AbstractBuild build, final Launcher launcher, BuildListener listener) {
return new Environment() {
@Override
public boolean tearDown(AbstractBuild build, BuildListener listener)
throws IOException, InterruptedException
{
ProjectStats stats = buildStats(build.getWorkspace());
String report = generateReport(build.getProject().getDisplayName(), stats);
File artifactsDir = build.getArtifactsDir();
if (!artifactsDir.isDirectory()) {
boolean success = artifactsDir.mkdirs();
if (!success) {
listener.getLogger().println("Can't create artifacts directory at "
+ artifactsDir.getAbsolutePath());
}
}
String path = artifactsDir.getCanonicalPath() + REPORT_TEMPLATE_PATH;
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path),
StandardCharsets.UTF_8))) {
writer.write(report);
}
return super.tearDown(build, listener);
}
};
}
private static ProjectStats buildStats(FilePath root) throws IOException, InterruptedException {
int classesNumber = 0;
int linesNumber = 0;
Stack<FilePath> toProcess = new Stack<>();
toProcess.push(root);
while (!toProcess.isEmpty()) {
FilePath path = toProcess.pop();
if (path.isDirectory()) {
toProcess.addAll(path.list());
} else if (path.getName().endsWith(".java")) {
classesNumber++;
linesNumber += countLines(path);
}
}
return new ProjectStats(classesNumber, linesNumber);
}
private static int countLines(FilePath path) throws IOException, InterruptedException {
byte[] buffer = new byte[1024];
int result = 1;
try (InputStream in = path.read()) {
while (true) {
int read = in.read(buffer);
if (read < 0) {
return result;
}
for (int i = 0; i < read; i++) {
if (buffer[i] == '\n') {
result++;
}
}
}
}
}
private static String generateReport(String projectName, ProjectStats stats) throws IOException {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try (InputStream in = ProjectStatsBuildWrapper.class.getResourceAsStream(REPORT_TEMPLATE_PATH)) {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) >= 0) {
bOut.write(buffer, 0, read);
}
}
String content = new String(bOut.toByteArray(), StandardCharsets.UTF_8);
content = content.replace(PROJECT_NAME_VAR, projectName);
content = content.replace(CLASSES_NUMBER_VAR, String.valueOf(stats.getClassesNumber()));
content = content.replace(LINES_NUMBER_VAR, String.valueOf(stats.getLinesNumber()));
return content;
}
@Extension
public static final class DescriptorImpl extends BuildWrapperDescriptor {
@Override
public boolean isApplicable(AbstractProject<?, ?> item) {
return true;
}
@Nonnull
@Override
public String getDisplayName() {
return "Construct project stats during build";
}
}
}

View File

@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>$PROJECT_NAME$</title>
</head>
<body>
Project $PROJECT_NAME$:
<table border="1">
<tr>
<th>Classes number</th>
<th>Lines number</th>
</tr>
<tr>
<td>$CLASSES_NUMBER$</td>
<td>$LINES_NUMBER$</td>
</tr>
</table>
</body>
</html>

View File

@ -43,6 +43,10 @@
<groupId>javax.json.bind</groupId> <groupId>javax.json.bind</groupId>
<artifactId>javax.json.bind-api</artifactId> <artifactId>javax.json.bind-api</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Dependencies for Yasson --> <!-- Dependencies for Yasson -->
<!-- <dependency> --> <!-- <dependency> -->
@ -198,4 +202,5 @@
<geronimo-json_1.1_spec.version>1.0</geronimo-json_1.1_spec.version> <geronimo-json_1.1_spec.version>1.0</geronimo-json_1.1_spec.version>
</properties> </properties>
</project> </project>

View File

@ -1,4 +1,4 @@
package com.baeldung.actuator; package com.baeldung.reactive.actuator;
import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.ReactiveHealthIndicator; import org.springframework.boot.actuate.health.ReactiveHealthIndicator;

View File

@ -1,4 +1,4 @@
package com.baeldung.actuator; package com.baeldung.reactive.actuator;
import org.springframework.boot.actuate.endpoint.annotation.*; import org.springframework.boot.actuate.endpoint.annotation.*;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;

View File

@ -1,4 +1,4 @@
package com.baeldung.actuator; package com.baeldung.reactive.actuator;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.web.WebEndpointResponse; import org.springframework.boot.actuate.endpoint.web.WebEndpointResponse;

View File

@ -1 +1,4 @@
logging.level.root=INFO logging.level.root=INFO
management.endpoints.web.expose=*
info.app.name=Spring Boot 2 actuator Application

View File

@ -1,6 +1,5 @@
package com.baeldung.actuator; package com.baeldung.reactive.actuator;
import com.baeldung.jsonb.Spring5Application;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -10,12 +9,14 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.reactive.Spring5ReactiveApplication;
import java.io.IOException; import java.io.IOException;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Spring5Application.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Spring5ReactiveApplication.class)
public class ActuatorInfoIntegrationTest { public class ActuatorInfoIntegrationTest {
@Autowired @Autowired

View File

@ -43,10 +43,6 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId> <artifactId>spring-boot-starter-hateoas</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.projectreactor</groupId> <groupId>org.projectreactor</groupId>
<artifactId>reactor-spring</artifactId> <artifactId>reactor-spring</artifactId>

View File

@ -17,7 +17,6 @@ public class SecurityConfig {
public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) { public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
return http.authorizeExchange() return http.authorizeExchange()
.pathMatchers("/admin").hasAuthority("ROLE_ADMIN") .pathMatchers("/admin").hasAuthority("ROLE_ADMIN")
.pathMatchers("/actuator/**").permitAll()
.anyExchange().authenticated() .anyExchange().authenticated()
.and().formLogin() .and().formLogin()
.and().build(); .and().build();

View File

@ -1,5 +1,3 @@
server.port=8081 server.port=8081
management.endpoints.web.expose=*
info.app.name=Spring Boot 2 actuator Application
logging.level.root=INFO logging.level.root=INFO

View File

@ -110,7 +110,7 @@
<properties> <properties>
<!-- Spring --> <!-- Spring -->
<org.springframework.version>4.3.4.RELEASE</org.springframework.version> <org.springframework.version>5.0.2.RELEASE</org.springframework.version>
<org.springframework.security.version>4.2.0.RELEASE</org.springframework.security.version> <org.springframework.security.version>4.2.0.RELEASE</org.springframework.security.version>
<!-- persistence --> <!-- persistence -->

View File

@ -15,17 +15,7 @@ public class ExampleOne extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html"); response.setContentType("text/html");
PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter();
out.println( out.println("<!DOCTYPE html><html>" + "<head>" + "<meta charset=\"UTF-8\" />" + "<title>HTML Rendered by Servlet</title>" + "</head>" + "<body>" + "<h1>HTML Rendered by Servlet</h1></br>" + "<p>This page was rendered by the ExampleOne Servlet!</p>"
"<!DOCTYPE html><html>" + + "</body>" + "</html>");
"<head>" +
"<meta charset=\"UTF-8\" />" +
"<title>HTML Rendered by Servlet</title>" +
"</head>" +
"<body>" +
"<h1>HTML Rendered by Servlet</h1></br>" +
"<p>This page was rendered by the ExampleOne Servlet!</p>" +
"</body>" +
"</html>"
);
} }
} }

View File

@ -7,11 +7,7 @@ import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
@WebServlet( @WebServlet(name = "ExampleThree", description = "JSP Servlet With Annotations", urlPatterns = { "/ExampleThree" })
name = "ExampleThree",
description = "JSP Servlet With Annotations",
urlPatterns = {"/ExampleThree"}
)
public class ExampleThree extends HttpServlet { public class ExampleThree extends HttpServlet {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;

View File

@ -46,7 +46,6 @@ public class ErrorController {
} }
private int getErrorCode(HttpServletRequest httpRequest) { private int getErrorCode(HttpServletRequest httpRequest) {
return (Integer) httpRequest return (Integer) httpRequest.getAttribute("javax.servlet.error.status_code");
.getAttribute("javax.servlet.error.status_code");
} }
} }

View File

@ -14,14 +14,14 @@ import com.baeldung.spring.service.RawDBDemoGeoIPLocationService;
@Controller @Controller
public class GeoIPTestController { public class GeoIPTestController {
private RawDBDemoGeoIPLocationService locationService; private RawDBDemoGeoIPLocationService locationService;
public GeoIPTestController() throws IOException { public GeoIPTestController() throws IOException {
locationService locationService = new RawDBDemoGeoIPLocationService();
= new RawDBDemoGeoIPLocationService();
} }
@RequestMapping(value="/GeoIPTest", method = RequestMethod.POST)
@RequestMapping(value = "/GeoIPTest", method = RequestMethod.POST)
@ResponseBody @ResponseBody
public GeoIP getLocation( public GeoIP getLocation(@RequestParam(value = "ipAddress", required = true) String ipAddress) throws Exception {
@RequestParam(value="ipAddress", required=true) String ipAddress) throws Exception {
return locationService.getLocation(ipAddress); return locationService.getLocation(ipAddress);
} }

View File

@ -12,7 +12,6 @@ import org.springframework.web.context.support.ServletContextResource;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;

View File

@ -9,7 +9,7 @@ import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception; import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse; import com.maxmind.geoip2.model.CityResponse;
public class RawDBDemoGeoIPLocationService{ public class RawDBDemoGeoIPLocationService {
private DatabaseReader dbReader; private DatabaseReader dbReader;
public RawDBDemoGeoIPLocationService() throws IOException { public RawDBDemoGeoIPLocationService() throws IOException {

View File

@ -10,7 +10,6 @@ import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception; import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse; import com.maxmind.geoip2.model.CityResponse;
public class GeoIpIntegrationTest { public class GeoIpIntegrationTest {
@Test @Test

View File

@ -0,0 +1,14 @@
package org.baeldung.methodsecurity.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.security.access.prepost.PreAuthorize;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize("hasRole('VIEWER')")
public @interface IsViewer {
}

View File

@ -1,11 +1,11 @@
package org.baeldung.testmethodsecurity.config; package org.baeldung.methodsecurity.config;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
@Configuration @Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
} }

View File

@ -1,4 +1,4 @@
package org.baeldung.testmethodsecurity.entity; package org.baeldung.methodsecurity.entity;
import java.util.Collection; import java.util.Collection;
@ -6,7 +6,7 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.User;
@SuppressWarnings("serial") @SuppressWarnings("serial")
public class CustomUser extends User{ public class CustomUser extends User {
private String nickName; private String nickName;
@ -14,7 +14,7 @@ public class CustomUser extends User{
super(username, password, authorities); super(username, password, authorities);
} }
public CustomUser(String username, String password, Collection<? extends GrantedAuthority> authorities,String nickName) { public CustomUser(String username, String password, Collection<? extends GrantedAuthority> authorities, String nickName) {
super(username, password, authorities); super(username, password, authorities);
this.nickName = nickName; this.nickName = nickName;
} }

View File

@ -0,0 +1,57 @@
package org.baeldung.methodsecurity.repository;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.baeldung.methodsecurity.entity.CustomUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class UserRoleRepository {
static Map<String, CustomUser> DB_BASED_USER_MAPPING;
static {
DB_BASED_USER_MAPPING = new LinkedHashMap<>();
DB_BASED_USER_MAPPING.put("jane", new CustomUser("jane", "1234", getGrantedAuthorities("ROLE_USER", "ROLE_VIEWER"), "jane"));
DB_BASED_USER_MAPPING.put("john", new CustomUser("john", "1234", getGrantedAuthorities("ROLE_EDITOR", "ROLE_ADMIN"), "jane"));
DB_BASED_USER_MAPPING.put("jack", new CustomUser("jack", "1234", getGrantedAuthorities("ROLE_USER", "ROLE_REVIEWER"), "jane"));
}
private static List<GrantedAuthority> getGrantedAuthorities(String... roles) {
ArrayList<GrantedAuthority> authorities = new ArrayList<>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
public CustomUser loadUserByUserName(String username) {
if (DB_BASED_USER_MAPPING.containsKey(username)) {
return DB_BASED_USER_MAPPING.get(username);
}
throw new UsernameNotFoundException("User " + username + " cannot be found");
}
public boolean isValidUsername(String username) {
return DB_BASED_USER_MAPPING.containsKey(username);
}
public boolean isValidRole(String roleName) {
return roleName.startsWith("ROLE_");
}
public List<String> getAllUsernames() {
List<String> usernames = new ArrayList<>();
usernames.add("jane");
usernames.add("john");
usernames.add("jack");
return usernames;
}
}

View File

@ -1,6 +1,6 @@
package org.baeldung.testmethodsecurity.service; package org.baeldung.methodsecurity.service;
import org.baeldung.testmethodsecurity.repository.UserRoleRepository; import org.baeldung.methodsecurity.repository.UserRoleRepository;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetailsService;

View File

@ -0,0 +1,18 @@
package org.baeldung.methodsecurity.service;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
@Service
@PreAuthorize("hasRole('ROLE_ADMIN')")
public class SystemService {
public String getSystemYear(){
return "2017";
}
public String getSystemDate(){
return "31-12-2017";
}
}

View File

@ -0,0 +1,108 @@
package org.baeldung.methodsecurity.service;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.security.RolesAllowed;
import org.baeldung.methodsecurity.annotation.IsViewer;
import org.baeldung.methodsecurity.entity.CustomUser;
import org.baeldung.methodsecurity.repository.UserRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
@Service
public class UserRoleService {
@Autowired
UserRoleRepository userRoleRepository;
@Secured("ROLE_VIEWER")
public String getUsername() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getName();
}
@Secured({ "ROLE_VIEWER", "ROLE_EDITOR" })
public boolean isValidUsername(String username) {
return userRoleRepository.isValidUsername(username);
}
@RolesAllowed("ROLE_VIEWER")
public String getUsername2() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getName();
}
@RolesAllowed({ "ROLE_VIEWER", "ROLE_EDITOR" })
public boolean isValidUsername2(String username) {
return userRoleRepository.isValidUsername(username);
}
@PreAuthorize("hasRole('ROLE_VIEWER')")
public String getUsernameInUpperCase() {
return getUsername().toUpperCase();
}
@PreAuthorize("hasAuthority('SYS_ADMIN')")
public String getUsernameLC() {
return getUsername().toLowerCase();
}
@PreAuthorize("hasRole('ROLE_VIEWER') or hasRole('ROLE_EDITOR')")
public boolean isValidUsername3(String username) {
return userRoleRepository.isValidUsername(username);
}
@PreAuthorize("#username == authentication.principal.username")
public String getMyRoles(String username) {
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(","));
}
@PostAuthorize("#username == authentication.principal.username")
public String getMyRoles2(String username) {
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(","));
}
@PostAuthorize("returnObject.username == authentication.principal.nickName")
public CustomUser loadUserDetail(String username) {
return userRoleRepository.loadUserByUserName(username);
}
@PreFilter("filterObject != authentication.principal.username")
public String joinUsernames(List<String> usernames) {
return usernames.stream().collect(Collectors.joining(";"));
}
@PreFilter(value = "filterObject != authentication.principal.username", filterTarget = "usernames")
public String joinUsernamesAndRoles(List<String> usernames, List<String> roles) {
return usernames.stream().collect(Collectors.joining(";")) + ":" + roles.stream().collect(Collectors.joining(";"));
}
@PostFilter("filterObject != authentication.principal.username")
public List<String> getAllUsernamesExceptCurrent() {
return userRoleRepository.getAllUsernames();
}
@IsViewer
public String getUsername4() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getName();
}
@PreAuthorize("#username == authentication.principal.username")
@PostAuthorize("returnObject.username == authentication.principal.nickName")
public CustomUser securedLoadUserDetail(String username) {
return userRoleRepository.loadUserByUserName(username);
}
}

View File

@ -1,41 +0,0 @@
package org.baeldung.testmethodsecurity.repository;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.baeldung.testmethodsecurity.entity.CustomUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class UserRoleRepository {
static Map<String,CustomUser> DB_BASED_USER_MAPPING;
static{
DB_BASED_USER_MAPPING = new LinkedHashMap<>();
DB_BASED_USER_MAPPING.put("jane", new CustomUser("jane","1234", getGrantedAuthorities("ROLE_USER","ROLE_VIEWER"),"jane"));
DB_BASED_USER_MAPPING.put("john", new CustomUser("john","1234", getGrantedAuthorities("ROLE_EDITOR","ROLE_ADMIN"),"jane"));
DB_BASED_USER_MAPPING.put("jack", new CustomUser("jack","1234", getGrantedAuthorities("ROLE_USER","ROLE_REVIEWER"),"jane"));
}
private static List<GrantedAuthority> getGrantedAuthorities(String...roles){
ArrayList<GrantedAuthority> authorities = new ArrayList<>();
for (String role : roles){
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
public CustomUser loadUserByUserName(String username){
if (DB_BASED_USER_MAPPING.containsKey(username)){
return DB_BASED_USER_MAPPING.get(username);
}
throw new UsernameNotFoundException("User "+username+" cannot be found");
}
}

View File

@ -1,29 +0,0 @@
package org.baeldung.testmethodsecurity.service;
import org.baeldung.testmethodsecurity.entity.CustomUser;
import org.baeldung.testmethodsecurity.repository.UserRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
@Service
public class UserRoleService {
@Autowired
UserRoleRepository userRoleRepository;
@PreAuthorize("hasRole('ROLE_VIEWER') or hasAuthority('SYS_ADMIN')")
public String getUsername(){
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getName();
}
@PostAuthorize("returnObject.username == authentication.principal.nickName")
public CustomUser loadUserDetail(String username){
return userRoleRepository.loadUserByUserName(username);
}
}

View File

@ -0,0 +1,49 @@
package org.baeldung.methodsecurity;
import static org.junit.Assert.*;
import org.baeldung.methodsecurity.service.SystemService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@ContextConfiguration
public class TestClassLevelSecurity {
@Autowired
SystemService systemService;
@Configuration
@ComponentScan("org.baeldung.methodsecurity.*")
public static class SpringConfig {
}
@Test
@WithMockUser(username="john",roles={"ADMIN"})
public void givenRoleAdmin_whenCallGetSystemYear_return2017(){
String systemYear = systemService.getSystemYear();
assertEquals("2017",systemYear);
}
@Test(expected=AccessDeniedException.class)
@WithMockUser(username="john",roles={"VIEWER"})
public void givenRoleViewer_whenCallGetSystemYear_returnAccessDenied(){
String systemYear = systemService.getSystemYear();
assertEquals("2017",systemYear);
}
@Test
@WithMockUser(username="john",roles={"ADMIN"})
public void givenRoleAdmin_whenCallGetSystemDate_returnDate(){
String systemYear = systemService.getSystemDate();
assertEquals("31-12-2017",systemYear);
}
}

View File

@ -0,0 +1,176 @@
package org.baeldung.methodsecurity;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.baeldung.methodsecurity.service.UserRoleService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.test.context.support.WithAnonymousUser;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@ContextConfiguration
public class TestMethodSecurity {
@Autowired
UserRoleService userRoleService;
@Configuration
@ComponentScan("org.baeldung.methodsecurity.*")
public static class SpringConfig {
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void givenNoSecurity_whenCallGetUsername_thenReturnException() {
String userName = userRoleService.getUsername();
assertEquals("john", userName);
}
@Test
@WithMockUser(username = "john", roles = { "VIEWER" })
public void givenRoleViewer_whenCallGetUsername_thenReturnUsername() {
String userName = userRoleService.getUsername();
assertEquals("john", userName);
}
@Test
@WithMockUser(username = "john", roles = { "EDITOR" })
public void givenUsernameJohn_whenCallIsValidUsername_thenReturnTrue() {
boolean isValid = userRoleService.isValidUsername("john");
assertEquals(true, isValid);
}
@Test(expected = AccessDeniedException.class)
@WithMockUser(username = "john", roles = { "ADMIN" })
public void givenRoleAdmin_whenCallGetUsername_thenReturnAccessDenied() {
userRoleService.getUsername();
}
@Test(expected = AccessDeniedException.class)
@WithMockUser(username = "john", roles = { "USER" })
public void givenRoleUser_whenCallGetUsername2_thenReturnAccessDenied() {
userRoleService.getUsername2();
}
@Test
@WithMockUser(username = "john", roles = { "VIEWER", "EDITOR" })
public void givenRoleViewer_whenCallGetUsername2_thenReturnUsername() {
String userName = userRoleService.getUsername2();
assertEquals("john", userName);
}
@Test
@WithMockUser(username = "john", roles = { "VIEWER" })
public void givenUsernameJerry_whenCallIsValidUsername2_thenReturnFalse() {
boolean isValid = userRoleService.isValidUsername2("jerry");
assertEquals(false, isValid);
}
@Test
@WithMockUser(username = "JOHN", authorities = { "SYS_ADMIN" })
public void givenAuthoritySysAdmin_whenCallGetUsernameInLowerCase_thenReturnUsername() {
String username = userRoleService.getUsernameLC();
assertEquals("john", username);
}
@Test
@WithMockUser(username = "john", roles = { "ADMIN", "USER", "VIEWER" })
public void givenUserJohn_whenCallGetMyRolesWithJohn_thenReturnRoles() {
String roles = userRoleService.getMyRoles("john");
assertEquals("ROLE_ADMIN,ROLE_USER,ROLE_VIEWER", roles);
}
@Test(expected = AccessDeniedException.class)
@WithMockUser(username = "john", roles = { "ADMIN", "USER", "VIEWER" })
public void givenUserJane_whenCallGetMyRolesWithJane_thenAccessDenied() {
userRoleService.getMyRoles("jane");
}
@Test
@WithMockUser(username = "john", roles = { "ADMIN", "USER", "VIEWER" })
public void givenUserJohn_whenCallGetMyRoles2WithJohn_thenReturnRoles() {
String roles = userRoleService.getMyRoles2("john");
assertEquals("ROLE_ADMIN,ROLE_USER,ROLE_VIEWER", roles);
}
@Test(expected = AccessDeniedException.class)
@WithMockUser(username = "john", roles = { "ADMIN", "USER", "VIEWER" })
public void givenUserJane_whenCallGetMyRoles2WithJane_thenAccessDenied() {
userRoleService.getMyRoles2("jane");
}
@Test(expected = AccessDeniedException.class)
@WithAnonymousUser
public void givenAnomynousUser_whenCallGetUsername_thenAccessDenied() {
userRoleService.getUsername();
}
@Test
@WithMockJohnViewer
public void givenMockedJohnViewer_whenCallGetUsername_thenReturnUsername() {
String userName = userRoleService.getUsername();
assertEquals("john", userName);
}
@Test
@WithMockUser(username = "jane")
public void givenListContainCurrentUsername_whenJoinUsernames_thenReturnUsernames() {
List<String> usernames = new ArrayList<>();
usernames.add("jane");
usernames.add("john");
usernames.add("jack");
String containCurrentUser = userRoleService.joinUsernames(usernames);
assertEquals("john;jack", containCurrentUser);
}
@Test
@WithMockUser(username = "john")
public void givenListContainCurrentUsername_whenCallJoinUsernamesAndRoles_thenReturnUsernameAndRoles() {
List<String> usernames = new ArrayList<>();
usernames.add("jane");
usernames.add("john");
usernames.add("jack");
List<String> roles = new ArrayList<>();
roles.add("ROLE_ADMIN");
roles.add("ROLE_TEST");
String containCurrentUser = userRoleService.joinUsernamesAndRoles(usernames, roles);
assertEquals("jane;jack:ROLE_ADMIN;ROLE_TEST", containCurrentUser);
}
@Test
@WithMockUser(username = "john")
public void givenUserJohn_whenCallGetAllUsernamesExceptCurrent_thenReturnOtherusernames() {
List<String> others = userRoleService.getAllUsernamesExceptCurrent();
assertEquals(2, others.size());
assertTrue(others.contains("jane"));
assertTrue(others.contains("jack"));
}
@Test
@WithMockUser(username = "john", roles = { "VIEWER" })
public void givenRoleViewer_whenCallGetUsername4_thenReturnUsername() {
String userName = userRoleService.getUsername4();
assertEquals("john", userName);
}
@Test(expected = AccessDeniedException.class)
@WithMockUser(username = "john")
public void givenDefaultRole_whenCallGetUsername4_thenAccessDenied() {
userRoleService.getUsername4();
}
}

View File

@ -1,8 +1,8 @@
package org.baeldung.testmethodsecurity; package org.baeldung.methodsecurity;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import org.baeldung.testmethodsecurity.service.UserRoleService; import org.baeldung.methodsecurity.service.UserRoleService;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -14,20 +14,20 @@ import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@ContextConfiguration @ContextConfiguration
@WithMockUser(username="john",roles={"VIEWER"}) @WithMockUser(username = "john", roles = { "VIEWER" })
public class TestWithMockUserAtClassLevel { public class TestWithMockUserAtClassLevel {
@Test @Test
public void givenRoleViewer_whenCallGetUsername_thenReturnUsername(){ public void givenRoleViewer_whenCallGetUsername_thenReturnUsername() {
String currentUserName = userService.getUsername(); String currentUserName = userService.getUsername();
assertEquals("john",currentUserName); assertEquals("john", currentUserName);
} }
@Autowired @Autowired
UserRoleService userService; UserRoleService userService;
@Configuration @Configuration
@ComponentScan("org.baeldung.testmethodsecurity.*") @ComponentScan("org.baeldung.methodsecurity.*")
public static class SpringConfig { public static class SpringConfig {
} }

View File

@ -0,0 +1,56 @@
package org.baeldung.methodsecurity;
import static org.junit.Assert.assertEquals;
import org.baeldung.methodsecurity.entity.CustomUser;
import org.baeldung.methodsecurity.service.UserRoleService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@ContextConfiguration
public class TestWithUserDetails {
@Autowired
UserRoleService userService;
@Configuration
@ComponentScan("org.baeldung.methodsecurity.*")
public static class SpringConfig {
}
@Test
@WithUserDetails(value = "john", userDetailsServiceBeanName = "userDetailService")
public void whenJohn_callLoadUserDetail_thenOK() {
CustomUser user = userService.loadUserDetail("jane");
assertEquals("jane", user.getNickName());
}
@Test
@WithUserDetails(value = "jane", userDetailsServiceBeanName = "userDetailService")
public void givenJane_callSecuredLoadUserDetailWithJane_thenOK() {
CustomUser user = userService.securedLoadUserDetail("jane");
assertEquals("jane", user.getNickName());
assertEquals("jane", user.getUsername());
}
@Test(expected = AccessDeniedException.class)
@WithUserDetails(value = "john", userDetailsServiceBeanName = "userDetailService")
public void givenJohn_callSecuredLoadUserDetailWithJane_thenAccessDenied() {
userService.securedLoadUserDetail("jane");
}
@Test(expected = AccessDeniedException.class)
@WithUserDetails(value = "john", userDetailsServiceBeanName = "userDetailService")
public void givenJohn_callSecuredLoadUserDetailWithJohn_thenAccessDenied() {
userService.securedLoadUserDetail("john");
}
}

View File

@ -1,4 +1,4 @@
package org.baeldung.testmethodsecurity; package org.baeldung.methodsecurity;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;

View File

@ -1,57 +0,0 @@
package org.baeldung.testmethodsecurity;
import static org.junit.Assert.assertEquals;
import org.baeldung.testmethodsecurity.service.UserRoleService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.test.context.support.WithAnonymousUser;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@ContextConfiguration
public class TestMethodSecurity{
@Autowired
UserRoleService userRoleService;
@Configuration
@ComponentScan("org.baeldung.testmethodsecurity.*")
public static class SpringConfig {
}
@Test
@WithMockUser(username="john",roles={"VIEWER"})
public void givenRoleViewer_whenCallGetUsername_thenReturnUsername(){
String userName = userRoleService.getUsername();
assertEquals("john", userName);
}
@Test
@WithMockUser(username="john",authorities={"SYS_ADMIN"})
public void givenAuthoritySysAdmin_whenCallGetUsername_thenReturnUsername(){
String userName = userRoleService.getUsername();
assertEquals("john", userName);
}
@Test(expected=AccessDeniedException.class)
@WithAnonymousUser
public void givenAnomynousUser_whenCallGetUsername_thenAccessDenied(){
userRoleService.getUsername();
}
@Test
@WithMockJohnViewer
public void givenMockedJohnViewer_whenCallGetUsername_thenReturnUsername(){
String userName = userRoleService.getUsername();
assertEquals("john", userName);
}
}

View File

@ -1,35 +0,0 @@
package org.baeldung.testmethodsecurity;
import static org.junit.Assert.assertEquals;
import org.baeldung.testmethodsecurity.entity.CustomUser;
import org.baeldung.testmethodsecurity.service.UserRoleService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@ContextConfiguration
public class TestWithUserDetails {
@Autowired
UserRoleService userService;
@Configuration
@ComponentScan("org.baeldung.testmethodsecurity.*")
public static class SpringConfig {
}
@Test
@WithUserDetails(value="john",userDetailsServiceBeanName="userDetailService")
public void whenJohn_callLoadUserDetail_thenOK(){
CustomUser user = userService.loadUserDetail("jane");
assertEquals("jane",user.getNickName());
}
}