diff --git a/core-java-8/README.md b/core-java-8/README.md index 862d8c2224..53e8e1a44a 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -34,3 +34,6 @@ - [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) - [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) diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index 17d330b3b8..75728ecd13 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -101,6 +101,23 @@ 1.19 + + com.codepoetics + protonpack + ${protonpack.version} + + + + io.vavr + vavr + ${vavr.version} + + + + one.util + streamex + ${streamex.version} + @@ -267,6 +284,9 @@ 4.01 1.10 1.16.12 + 0.9.0 + 1.13 + 0.6.5 3.6.1 diff --git a/core-java-io/src/main/java/com/baeldung/stream/StreamIndices.java b/core-java-8/src/main/java/com/baeldung/stream/StreamIndices.java similarity index 100% rename from core-java-io/src/main/java/com/baeldung/stream/StreamIndices.java rename to core-java-8/src/main/java/com/baeldung/stream/StreamIndices.java diff --git a/core-java-io/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java b/core-java-8/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java similarity index 100% rename from core-java-io/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java rename to core-java-8/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java diff --git a/core-java-io/src/test/java/com/baeldung/stream/StreamIndicesTest.java b/core-java-8/src/test/java/com/baeldung/stream/StreamIndicesTest.java similarity index 100% rename from core-java-io/src/test/java/com/baeldung/stream/StreamIndicesTest.java rename to core-java-8/src/test/java/com/baeldung/stream/StreamIndicesTest.java diff --git a/core-java-io/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java b/core-java-8/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java similarity index 100% rename from core-java-io/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java rename to core-java-8/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java diff --git a/core-java-io/README.md b/core-java-io/README.md index 79974ab523..52485acfd5 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -12,11 +12,8 @@ - [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) - [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) - [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) - [Java – Append Data to a File](http://www.baeldung.com/java-append-to-file) - [FileNotFoundException in Java](http://www.baeldung.com/java-filenotfound-exception) diff --git a/jenkins/hello-world/pom.xml b/jenkins/hello-world/pom.xml new file mode 100644 index 0000000000..15cf2f8e34 --- /dev/null +++ b/jenkins/hello-world/pom.xml @@ -0,0 +1,89 @@ + + + 4.0.0 + + org.jenkins-ci.plugins + plugin + 2.33 + + + jenkins-hello-world + 1.0-SNAPSHOT + hpi + + + 2.7.3 + + Hello World Plugin + A sample Jenkins Hello World plugin + https://wiki.jenkins-ci.org/display/JENKINS/TODO+Plugin + + + MIT License + http://opensource.org/licenses/MIT + + + + + org.jenkins-ci.plugins + structs + 1.7 + + + org.jenkins-ci.plugins.workflow + workflow-step-api + 2.12 + test + + + org.jenkins-ci.plugins.workflow + workflow-cps + 2.39 + test + + + org.jenkins-ci.plugins.workflow + workflow-job + 2.11.2 + test + + + org.jenkins-ci.plugins.workflow + workflow-basic-steps + 2.6 + test + + + org.jenkins-ci.plugins.workflow + workflow-durable-task-step + 2.13 + test + + + org.jenkins-ci.plugins.workflow + workflow-api + 2.20 + test + + + org.jenkins-ci.plugins.workflow + workflow-support + 2.14 + test + + + + + + repo.jenkins-ci.org + https://repo.jenkins-ci.org/public/ + + + + + + repo.jenkins-ci.org + https://repo.jenkins-ci.org/public/ + + + diff --git a/jenkins/hello-world/src/main/java/com/baeldung/jenkins/helloworld/ProjectStats.java b/jenkins/hello-world/src/main/java/com/baeldung/jenkins/helloworld/ProjectStats.java new file mode 100644 index 0000000000..67af636bb4 --- /dev/null +++ b/jenkins/hello-world/src/main/java/com/baeldung/jenkins/helloworld/ProjectStats.java @@ -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; + } +} diff --git a/jenkins/hello-world/src/main/java/com/baeldung/jenkins/helloworld/ProjectStatsBuildWrapper.java b/jenkins/hello-world/src/main/java/com/baeldung/jenkins/helloworld/ProjectStatsBuildWrapper.java new file mode 100644 index 0000000000..9a7213c76f --- /dev/null +++ b/jenkins/hello-world/src/main/java/com/baeldung/jenkins/helloworld/ProjectStatsBuildWrapper.java @@ -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 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"; + } + + } + +} diff --git a/jenkins/hello-world/src/main/resources/stats.html b/jenkins/hello-world/src/main/resources/stats.html new file mode 100644 index 0000000000..2a14b5de3f --- /dev/null +++ b/jenkins/hello-world/src/main/resources/stats.html @@ -0,0 +1,20 @@ + + + + + $PROJECT_NAME$ + + +Project $PROJECT_NAME$: + + + + + + + + + +
Classes numberLines number
$CLASSES_NUMBER$$LINES_NUMBER$
+ + \ No newline at end of file diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index e5b35de2f5..36eaaa1530 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -43,6 +43,10 @@ javax.json.bind javax.json.bind-api + + org.springframework.boot + spring-boot-starter-actuator + @@ -198,4 +202,5 @@ 1.0 + diff --git a/spring-5/src/main/java/com/baeldung/actuator/DownstreamServiceReactiveHealthIndicator.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java similarity index 94% rename from spring-5/src/main/java/com/baeldung/actuator/DownstreamServiceReactiveHealthIndicator.java rename to spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java index 5f36330ff6..7360def71e 100644 --- a/spring-5/src/main/java/com/baeldung/actuator/DownstreamServiceReactiveHealthIndicator.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java @@ -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.ReactiveHealthIndicator; diff --git a/spring-5/src/main/java/com/baeldung/actuator/FeaturesEndpoint.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/FeaturesEndpoint.java similarity index 96% rename from spring-5/src/main/java/com/baeldung/actuator/FeaturesEndpoint.java rename to spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/FeaturesEndpoint.java index 2ed32501ae..b2bc1e037f 100644 --- a/spring-5/src/main/java/com/baeldung/actuator/FeaturesEndpoint.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/FeaturesEndpoint.java @@ -1,4 +1,4 @@ -package com.baeldung.actuator; +package com.baeldung.reactive.actuator; import org.springframework.boot.actuate.endpoint.annotation.*; import org.springframework.stereotype.Component; diff --git a/spring-5/src/main/java/com/baeldung/actuator/InfoWebEndpointExtension.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/InfoWebEndpointExtension.java similarity index 95% rename from spring-5/src/main/java/com/baeldung/actuator/InfoWebEndpointExtension.java rename to spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/InfoWebEndpointExtension.java index acd92d1846..86502f0ab3 100644 --- a/spring-5/src/main/java/com/baeldung/actuator/InfoWebEndpointExtension.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/InfoWebEndpointExtension.java @@ -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.web.WebEndpointResponse; diff --git a/spring-5-reactive/src/main/resources/application.properties b/spring-5-reactive/src/main/resources/application.properties index 4b49e8e8a2..5b9a0ae1ce 100644 --- a/spring-5-reactive/src/main/resources/application.properties +++ b/spring-5-reactive/src/main/resources/application.properties @@ -1 +1,4 @@ -logging.level.root=INFO \ No newline at end of file +logging.level.root=INFO + +management.endpoints.web.expose=* +info.app.name=Spring Boot 2 actuator Application \ No newline at end of file diff --git a/spring-5/src/test/java/com/baeldung/actuator/ActuatorInfoIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java similarity index 88% rename from spring-5/src/test/java/com/baeldung/actuator/ActuatorInfoIntegrationTest.java rename to spring-5-reactive/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java index 964cf1a1ea..3020e86723 100644 --- a/spring-5/src/test/java/com/baeldung/actuator/ActuatorInfoIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java @@ -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.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -10,12 +9,14 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.reactive.Spring5ReactiveApplication; + import java.io.IOException; import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Spring5Application.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Spring5ReactiveApplication.class) public class ActuatorInfoIntegrationTest { @Autowired diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 4c2df68f1b..19dd65d78f 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -43,10 +43,6 @@ org.springframework.boot spring-boot-starter-hateoas - - org.springframework.boot - spring-boot-starter-actuator - org.projectreactor reactor-spring diff --git a/spring-5/src/main/java/com/baeldung/security/SecurityConfig.java b/spring-5/src/main/java/com/baeldung/security/SecurityConfig.java index d31f1552fc..a9e44a2eee 100644 --- a/spring-5/src/main/java/com/baeldung/security/SecurityConfig.java +++ b/spring-5/src/main/java/com/baeldung/security/SecurityConfig.java @@ -17,7 +17,6 @@ public class SecurityConfig { public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) { return http.authorizeExchange() .pathMatchers("/admin").hasAuthority("ROLE_ADMIN") - .pathMatchers("/actuator/**").permitAll() .anyExchange().authenticated() .and().formLogin() .and().build(); diff --git a/spring-5/src/main/resources/application.properties b/spring-5/src/main/resources/application.properties index a7e3ec0d5a..ccec014c2b 100644 --- a/spring-5/src/main/resources/application.properties +++ b/spring-5/src/main/resources/application.properties @@ -1,5 +1,3 @@ server.port=8081 -management.endpoints.web.expose=* -info.app.name=Spring Boot 2 actuator Application logging.level.root=INFO \ No newline at end of file diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index 2131609ff6..049a3fec82 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -110,7 +110,7 @@ - 4.3.4.RELEASE + 5.0.2.RELEASE 4.2.0.RELEASE @@ -142,4 +142,4 @@ - \ No newline at end of file + diff --git a/spring-mvc-xml/src/main/java/com/baeldung/jsp/ExampleOne.java b/spring-mvc-xml/src/main/java/com/baeldung/jsp/ExampleOne.java index 0b153bf8ec..6744570639 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/jsp/ExampleOne.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/jsp/ExampleOne.java @@ -8,24 +8,14 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ExampleOne extends HttpServlet { - - private static final long serialVersionUID = 1L; - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - response.setContentType("text/html"); - PrintWriter out = response.getWriter(); - out.println( - "" + - "" + - "" + - "HTML Rendered by Servlet" + - "" + - "" + - "

HTML Rendered by Servlet


" + - "

This page was rendered by the ExampleOne Servlet!

" + - "" + - "" - ); - } + + private static final long serialVersionUID = 1L; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.println("" + "" + "" + "HTML Rendered by Servlet" + "" + "" + "

HTML Rendered by Servlet


" + "

This page was rendered by the ExampleOne Servlet!

" + + "" + ""); + } } \ No newline at end of file diff --git a/spring-mvc-xml/src/main/java/com/baeldung/jsp/ExampleThree.java b/spring-mvc-xml/src/main/java/com/baeldung/jsp/ExampleThree.java index 49fefcffde..7269f917b4 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/jsp/ExampleThree.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/jsp/ExampleThree.java @@ -7,18 +7,14 @@ import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -@WebServlet( - name = "ExampleThree", - description = "JSP Servlet With Annotations", - urlPatterns = {"/ExampleThree"} -) +@WebServlet(name = "ExampleThree", description = "JSP Servlet With Annotations", urlPatterns = { "/ExampleThree" }) public class ExampleThree extends HttpServlet { - private static final long serialVersionUID = 1L; - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - String message = request.getParameter("message"); - request.setAttribute("text", message); - request.getRequestDispatcher("/jsp/ExampleThree.jsp").forward(request, response); - } + private static final long serialVersionUID = 1L; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + String message = request.getParameter("message"); + request.setAttribute("text", message); + request.getRequestDispatcher("/jsp/ExampleThree.jsp").forward(request, response); + } } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ErrorController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ErrorController.java index 96556bd5b1..6ae1023374 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ErrorController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ErrorController.java @@ -9,7 +9,7 @@ import org.springframework.web.servlet.ModelAndView; @Controller public class ErrorController { - + @RequestMapping(value = "500Error", method = RequestMethod.GET) public void throwRuntimeException() { throw new NullPointerException("Throwing a null pointer exception"); @@ -34,19 +34,18 @@ public class ErrorController { errorMsg = "Http Error Code : 404. Resource not found"; break; } - // Handle other 4xx error codes. + // Handle other 4xx error codes. case 500: { errorMsg = "Http Error Code : 500. Internal Server Error"; break; } - // Handle other 5xx error codes. + // Handle other 5xx error codes. } errorPage.addObject("errorMsg", errorMsg); return errorPage; } private int getErrorCode(HttpServletRequest httpRequest) { - return (Integer) httpRequest - .getAttribute("javax.servlet.error.status_code"); + return (Integer) httpRequest.getAttribute("javax.servlet.error.status_code"); } } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GeoIPTestController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GeoIPTestController.java index 16de4e56f5..eeaddcf8e0 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GeoIPTestController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GeoIPTestController.java @@ -14,15 +14,15 @@ import com.baeldung.spring.service.RawDBDemoGeoIPLocationService; @Controller public class GeoIPTestController { private RawDBDemoGeoIPLocationService locationService; + public GeoIPTestController() throws IOException { - locationService - = new RawDBDemoGeoIPLocationService(); + locationService = new RawDBDemoGeoIPLocationService(); } - @RequestMapping(value="/GeoIPTest", method = RequestMethod.POST) + + @RequestMapping(value = "/GeoIPTest", method = RequestMethod.POST) @ResponseBody - public GeoIP getLocation( - @RequestParam(value="ipAddress", required=true) String ipAddress) throws Exception { - + public GeoIP getLocation(@RequestParam(value = "ipAddress", required = true) String ipAddress) throws Exception { + return locationService.getLocation(ipAddress); } } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ImageController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ImageController.java index ef8d1214df..fc46c07e06 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ImageController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ImageController.java @@ -12,7 +12,6 @@ import org.springframework.web.context.support.ServletContextResource; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletResponse; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/form/GeoIP.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/form/GeoIP.java index 19f56867a1..4373303107 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/form/GeoIP.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/form/GeoIP.java @@ -5,15 +5,15 @@ public class GeoIP { private String city; private String latitude; private String longitude; - + public GeoIP() { - + } - + public GeoIP(String ipAddress) { this.ipAddress = ipAddress; } - + public GeoIP(String ipAddress, String city, String latitude, String longitude) { this.ipAddress = ipAddress; this.city = city; @@ -52,5 +52,5 @@ public class GeoIP { public void setLongitude(String longitude) { this.longitude = longitude; } - + } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/service/RawDBDemoGeoIPLocationService.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/service/RawDBDemoGeoIPLocationService.java index af3ce8cfb3..04443466c9 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/service/RawDBDemoGeoIPLocationService.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/service/RawDBDemoGeoIPLocationService.java @@ -9,18 +9,18 @@ import com.maxmind.geoip2.DatabaseReader; import com.maxmind.geoip2.exception.GeoIp2Exception; import com.maxmind.geoip2.model.CityResponse; -public class RawDBDemoGeoIPLocationService{ +public class RawDBDemoGeoIPLocationService { private DatabaseReader dbReader; - + public RawDBDemoGeoIPLocationService() throws IOException { File database = new File("your-path-to-db-file"); dbReader = new DatabaseReader.Builder(database).build(); } - + public GeoIP getLocation(String ip) throws IOException, GeoIp2Exception { InetAddress ipAddress = InetAddress.getByName(ip); CityResponse response = dbReader.city(ipAddress); - + String cityName = response.getCity().getName(); String latitude = response.getLocation().getLatitude().toString(); String longitude = response.getLocation().getLongitude().toString(); diff --git a/spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java b/spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java index 2edaa125b7..0e957f3400 100644 --- a/spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java +++ b/spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java @@ -10,22 +10,21 @@ import com.maxmind.geoip2.DatabaseReader; import com.maxmind.geoip2.exception.GeoIp2Exception; import com.maxmind.geoip2.model.CityResponse; - public class GeoIpIntegrationTest { - + @Test public void givenIP_whenFetchingCity_thenReturnsCityData() throws IOException, GeoIp2Exception { File database = new File("your-path-to-db-file"); DatabaseReader dbReader = new DatabaseReader.Builder(database).build(); - + InetAddress ipAddress = InetAddress.getByName("your-public-ip"); CityResponse response = dbReader.city(ipAddress); - + String countryName = response.getCountry().getName(); String cityName = response.getCity().getName(); String postal = response.getPostal().getCode(); String state = response.getLeastSpecificSubdivision().getName(); - + } - + } diff --git a/spring-security-core/src/main/java/org/baeldung/methodsecurity/annotation/IsViewer.java b/spring-security-core/src/main/java/org/baeldung/methodsecurity/annotation/IsViewer.java new file mode 100644 index 0000000000..711784adbb --- /dev/null +++ b/spring-security-core/src/main/java/org/baeldung/methodsecurity/annotation/IsViewer.java @@ -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 { +} \ No newline at end of file diff --git a/spring-security-core/src/main/java/org/baeldung/testmethodsecurity/config/MethodSecurityConfig.java b/spring-security-core/src/main/java/org/baeldung/methodsecurity/config/MethodSecurityConfig.java similarity index 85% rename from spring-security-core/src/main/java/org/baeldung/testmethodsecurity/config/MethodSecurityConfig.java rename to spring-security-core/src/main/java/org/baeldung/methodsecurity/config/MethodSecurityConfig.java index 1b2227f9be..4749c730dc 100644 --- a/spring-security-core/src/main/java/org/baeldung/testmethodsecurity/config/MethodSecurityConfig.java +++ b/spring-security-core/src/main/java/org/baeldung/methodsecurity/config/MethodSecurityConfig.java @@ -1,11 +1,11 @@ -package org.baeldung.testmethodsecurity.config; +package org.baeldung.methodsecurity.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; @Configuration -@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) +@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true) public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { } diff --git a/spring-security-core/src/main/java/org/baeldung/testmethodsecurity/entity/CustomUser.java b/spring-security-core/src/main/java/org/baeldung/methodsecurity/entity/CustomUser.java similarity index 78% rename from spring-security-core/src/main/java/org/baeldung/testmethodsecurity/entity/CustomUser.java rename to spring-security-core/src/main/java/org/baeldung/methodsecurity/entity/CustomUser.java index b145a82c80..fb9174befa 100644 --- a/spring-security-core/src/main/java/org/baeldung/testmethodsecurity/entity/CustomUser.java +++ b/spring-security-core/src/main/java/org/baeldung/methodsecurity/entity/CustomUser.java @@ -1,4 +1,4 @@ -package org.baeldung.testmethodsecurity.entity; +package org.baeldung.methodsecurity.entity; import java.util.Collection; @@ -6,15 +6,15 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.User; @SuppressWarnings("serial") -public class CustomUser extends User{ - +public class CustomUser extends User { + private String nickName; public CustomUser(String username, String password, Collection authorities) { super(username, password, authorities); } - - public CustomUser(String username, String password, Collection authorities,String nickName) { + + public CustomUser(String username, String password, Collection authorities, String nickName) { super(username, password, authorities); this.nickName = nickName; } diff --git a/spring-security-core/src/main/java/org/baeldung/methodsecurity/repository/UserRoleRepository.java b/spring-security-core/src/main/java/org/baeldung/methodsecurity/repository/UserRoleRepository.java new file mode 100644 index 0000000000..fc1a32289d --- /dev/null +++ b/spring-security-core/src/main/java/org/baeldung/methodsecurity/repository/UserRoleRepository.java @@ -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 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 getGrantedAuthorities(String... roles) { + ArrayList 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 getAllUsernames() { + List usernames = new ArrayList<>(); + usernames.add("jane"); + usernames.add("john"); + usernames.add("jack"); + return usernames; + } + +} diff --git a/spring-security-core/src/main/java/org/baeldung/testmethodsecurity/service/CustomUserDetailsService.java b/spring-security-core/src/main/java/org/baeldung/methodsecurity/service/CustomUserDetailsService.java similarity index 79% rename from spring-security-core/src/main/java/org/baeldung/testmethodsecurity/service/CustomUserDetailsService.java rename to spring-security-core/src/main/java/org/baeldung/methodsecurity/service/CustomUserDetailsService.java index a5adcd3408..91171468bb 100644 --- a/spring-security-core/src/main/java/org/baeldung/testmethodsecurity/service/CustomUserDetailsService.java +++ b/spring-security-core/src/main/java/org/baeldung/methodsecurity/service/CustomUserDetailsService.java @@ -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.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; diff --git a/spring-security-core/src/main/java/org/baeldung/methodsecurity/service/SystemService.java b/spring-security-core/src/main/java/org/baeldung/methodsecurity/service/SystemService.java new file mode 100644 index 0000000000..5f29d7dee6 --- /dev/null +++ b/spring-security-core/src/main/java/org/baeldung/methodsecurity/service/SystemService.java @@ -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"; + } + +} diff --git a/spring-security-core/src/main/java/org/baeldung/methodsecurity/service/UserRoleService.java b/spring-security-core/src/main/java/org/baeldung/methodsecurity/service/UserRoleService.java new file mode 100644 index 0000000000..30bbdbc10f --- /dev/null +++ b/spring-security-core/src/main/java/org/baeldung/methodsecurity/service/UserRoleService.java @@ -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 usernames) { + return usernames.stream().collect(Collectors.joining(";")); + } + + @PreFilter(value = "filterObject != authentication.principal.username", filterTarget = "usernames") + public String joinUsernamesAndRoles(List usernames, List roles) { + return usernames.stream().collect(Collectors.joining(";")) + ":" + roles.stream().collect(Collectors.joining(";")); + } + + @PostFilter("filterObject != authentication.principal.username") + public List 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); + } + +} diff --git a/spring-security-core/src/main/java/org/baeldung/testmethodsecurity/repository/UserRoleRepository.java b/spring-security-core/src/main/java/org/baeldung/testmethodsecurity/repository/UserRoleRepository.java deleted file mode 100644 index 565b46262d..0000000000 --- a/spring-security-core/src/main/java/org/baeldung/testmethodsecurity/repository/UserRoleRepository.java +++ /dev/null @@ -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 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 getGrantedAuthorities(String...roles){ - ArrayList 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"); - } - -} diff --git a/spring-security-core/src/main/java/org/baeldung/testmethodsecurity/service/UserRoleService.java b/spring-security-core/src/main/java/org/baeldung/testmethodsecurity/service/UserRoleService.java deleted file mode 100644 index f4dc6cf335..0000000000 --- a/spring-security-core/src/main/java/org/baeldung/testmethodsecurity/service/UserRoleService.java +++ /dev/null @@ -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); - } - -} diff --git a/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestClassLevelSecurity.java b/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestClassLevelSecurity.java new file mode 100644 index 0000000000..502fd50c46 --- /dev/null +++ b/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestClassLevelSecurity.java @@ -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); + } +} diff --git a/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestMethodSecurity.java b/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestMethodSecurity.java new file mode 100644 index 0000000000..309ee3076d --- /dev/null +++ b/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestMethodSecurity.java @@ -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 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 usernames = new ArrayList<>(); + usernames.add("jane"); + usernames.add("john"); + usernames.add("jack"); + + List 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 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(); + } + +} \ No newline at end of file diff --git a/spring-security-core/src/test/java/org/baeldung/testmethodsecurity/TestWithMockUserAtClassLevel.java b/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestWithMockUserAtClassLevel.java similarity index 72% rename from spring-security-core/src/test/java/org/baeldung/testmethodsecurity/TestWithMockUserAtClassLevel.java rename to spring-security-core/src/test/java/org/baeldung/methodsecurity/TestWithMockUserAtClassLevel.java index a348a7799d..4df1af8ca9 100644 --- a/spring-security-core/src/test/java/org/baeldung/testmethodsecurity/TestWithMockUserAtClassLevel.java +++ b/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestWithMockUserAtClassLevel.java @@ -1,8 +1,8 @@ -package org.baeldung.testmethodsecurity; +package org.baeldung.methodsecurity; 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.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -14,20 +14,20 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @ContextConfiguration -@WithMockUser(username="john",roles={"VIEWER"}) +@WithMockUser(username = "john", roles = { "VIEWER" }) public class TestWithMockUserAtClassLevel { - + @Test - public void givenRoleViewer_whenCallGetUsername_thenReturnUsername(){ + public void givenRoleViewer_whenCallGetUsername_thenReturnUsername() { String currentUserName = userService.getUsername(); - assertEquals("john",currentUserName); + assertEquals("john", currentUserName); } - + @Autowired UserRoleService userService; - + @Configuration - @ComponentScan("org.baeldung.testmethodsecurity.*") + @ComponentScan("org.baeldung.methodsecurity.*") public static class SpringConfig { } diff --git a/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestWithUserDetails.java b/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestWithUserDetails.java new file mode 100644 index 0000000000..3ef5996554 --- /dev/null +++ b/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestWithUserDetails.java @@ -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"); + } +} diff --git a/spring-security-core/src/test/java/org/baeldung/testmethodsecurity/WithMockJohnViewer.java b/spring-security-core/src/test/java/org/baeldung/methodsecurity/WithMockJohnViewer.java similarity index 72% rename from spring-security-core/src/test/java/org/baeldung/testmethodsecurity/WithMockJohnViewer.java rename to spring-security-core/src/test/java/org/baeldung/methodsecurity/WithMockJohnViewer.java index 994fe2e69b..5e1e882f3d 100644 --- a/spring-security-core/src/test/java/org/baeldung/testmethodsecurity/WithMockJohnViewer.java +++ b/spring-security-core/src/test/java/org/baeldung/methodsecurity/WithMockJohnViewer.java @@ -1,4 +1,4 @@ -package org.baeldung.testmethodsecurity; +package org.baeldung.methodsecurity; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; diff --git a/spring-security-core/src/test/java/org/baeldung/testmethodsecurity/TestMethodSecurity.java b/spring-security-core/src/test/java/org/baeldung/testmethodsecurity/TestMethodSecurity.java deleted file mode 100644 index 671229c726..0000000000 --- a/spring-security-core/src/test/java/org/baeldung/testmethodsecurity/TestMethodSecurity.java +++ /dev/null @@ -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); - } - -} \ No newline at end of file diff --git a/spring-security-core/src/test/java/org/baeldung/testmethodsecurity/TestWithUserDetails.java b/spring-security-core/src/test/java/org/baeldung/testmethodsecurity/TestWithUserDetails.java deleted file mode 100644 index ed8ed8cc85..0000000000 --- a/spring-security-core/src/test/java/org/baeldung/testmethodsecurity/TestWithUserDetails.java +++ /dev/null @@ -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()); - } -}