Merge remote-tracking branch 'upstream/master'

This commit is contained in:
macroscopic64 2019-04-25 06:37:02 +05:30
commit e6fe47d6ac
154 changed files with 2377 additions and 155 deletions

View File

@ -0,0 +1,3 @@
### Revelant Articles
- [A Quick Guide To Using Cloud Foundry UAA](https://www.baeldung.com/cloud-foundry-uaa)

View File

@ -29,4 +29,11 @@ public class CalculatorUnitTest {
int result = calculator.calculate(new AddCommand(3, 7));
assertEquals(10, result);
}
@Test
public void whenCalculateUsingFactory_thenReturnCorrectResult() {
Calculator calculator = new Calculator();
int result = calculator.calculateUsingFactory(3, 4, "add");
assertEquals(7, result);
}
}

View File

@ -0,0 +1,6 @@
=========
## Core Java Sets Cookbooks and Examples
### Relevant Articles:
- [Set Operations in Java](http://www.baeldung.com/set-operations-in-java)

View File

@ -0,0 +1,33 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-set</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-set</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
</dependencies>
<properties>
<commons-collections4.version>4.3</commons-collections4.version>
<guava.version>27.1-jre</guava.version>
</properties>
</project>

View File

@ -0,0 +1,93 @@
package com.baeldung.set;
import static org.junit.Assert.*;
import org.apache.commons.collections4.SetUtils;
import org.junit.Test;
import com.google.common.collect.Sets;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class SetOperationsUnitTest {
private Set<Integer> setA = setOf(1,2,3,4);
private Set<Integer> setB = setOf(2,4,6,8);
private static Set<Integer> setOf(Integer... values) {
return new HashSet<Integer>(Arrays.asList(values));
}
@Test
public void givenTwoSets_WhenWeRetainAll_ThenWeIntersectThem() {
Set<Integer> intersectSet = new HashSet<>(setA);
intersectSet.retainAll(setB);
assertEquals(setOf(2,4), intersectSet);
}
@Test
public void givenTwoSets_WhenWeAddAll_ThenWeUnionThem() {
Set<Integer> unionSet = new HashSet<>(setA);
unionSet.addAll(setB);
assertEquals(setOf(1,2,3,4,6,8), unionSet);
}
@Test
public void givenTwoSets_WhenRemoveAll_ThenWeGetTheDifference() {
Set<Integer> differenceSet = new HashSet<>(setA);
differenceSet.removeAll(setB);
assertEquals(setOf(1,3), differenceSet);
}
@Test
public void givenTwoStreams_WhenWeFilterThem_ThenWeCanGetTheIntersect() {
Set<Integer> intersectSet = setA.stream()
.filter(setB::contains)
.collect(Collectors.toSet());
assertEquals(setOf(2,4), intersectSet);
}
@Test
public void givenTwoStreams_WhenWeConcatThem_ThenWeGetTheUnion() {
Set<Integer> unionSet = Stream.concat(setA.stream(), setB.stream())
.collect(Collectors.toSet());
assertEquals(setOf(1,2,3,4,6,8), unionSet);
}
@Test
public void givenTwoStreams_WhenWeFilterThem_ThenWeCanGetTheDifference() {
Set<Integer> differenceSet = setA.stream()
.filter(val -> !setB.contains(val))
.collect(Collectors.toSet());
assertEquals(setOf(1,3), differenceSet);
}
@Test
public void givenTwoSets_WhenWeUseApacheCommonsIntersect_ThenWeGetTheIntersect() {
Set<Integer> intersectSet = SetUtils.intersection(setA, setB);
assertEquals(setOf(2,4), intersectSet);
}
@Test
public void givenTwoSets_WhenWeUseApacheCommonsUnion_ThenWeGetTheUnion() {
Set<Integer> unionSet = SetUtils.union(setA, setB);
assertEquals(setOf(1,2,3,4,6,8), unionSet);
}
@Test
public void givenTwoSets_WhenWeUseGuavaIntersect_ThenWeGetTheIntersect() {
Set<Integer> intersectSet = Sets.intersection(setA, setB);
assertEquals(setOf(2,4), intersectSet);
}
@Test
public void givenTwoSets_WhenWeUseGuavaUnion_ThenWeGetTheUnion() {
Set<Integer> unionSet = Sets.union(setA, setB);
assertEquals(setOf(1,2,3,4,6,8), unionSet);
}
}

View File

@ -3,3 +3,4 @@
## Core Java Lang OOP 2 Cookbooks and Examples
### Relevant Articles:
- [Generic Constructors in Java](https://www.baeldung.com/java-generic-constructors)

View File

@ -17,8 +17,8 @@ public class ProxyAcceptCookiePolicy implements CookiePolicy {
host = uri.getHost();
}
if (!HttpCookie.domainMatches(acceptedProxy, host)) {
return false;
if (HttpCookie.domainMatches(acceptedProxy, host)) {
return true;
}
return CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(uri, cookie);

View File

@ -20,9 +20,21 @@
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>${byte-buddy.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -37,6 +49,12 @@
<version>${kotlin.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-test-junit5</artifactId>
<version>${kotlin.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -69,10 +87,11 @@
</build>
<properties>
<kotlin.version>1.2.71</kotlin.version>
<junit.platform.version>1.1.1</junit.platform.version>
<junit.vintage.version>5.2.0</junit.vintage.version>
<kotlin.version>1.3.30</kotlin.version>
<junit.jupiter.version>5.4.2</junit.jupiter.version>
<mockito.version>2.27.0</mockito.version>
<byte-buddy.version>1.9.12</byte-buddy.version>
<assertj.version>3.10.0</assertj.version>
</properties>
</project>
</project>

44
fastUtil/pom.xml Normal file
View File

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>fastUtil</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/it.unimi.dsi/fastutil -->
<dependency>
<groupId>it.unimi.dsi</groupId>
<artifactId>fastutil</artifactId>
<version>8.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core -->
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.19</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,23 @@
package com.baeldung;
import it.unimi.dsi.fastutil.ints.IntBigArrays;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
public class BigArraysUnitTest {
@Test
public void givenValidAray_whenWrapped_checkAccessFromIntBigArraysMethodsCorrect() {
int[] oneDArray = new int[] { 2, 1, 5, 2, 1, 7 };
int[][] twoDArray = IntBigArrays.wrap(oneDArray.clone());
int firstIndex = IntBigArrays.get(twoDArray, 0);
int lastIndex = IntBigArrays.get(twoDArray, IntBigArrays.length(twoDArray)-1);
assertEquals(2, firstIndex);
assertEquals(7, lastIndex);
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.*;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Benchmark)
public class FastUtilTypeSpecificBenchmarkUnitTest {
@Param({"100", "1000", "10000", "100000"})
public int setSize;
@Benchmark
public IntSet givenFastUtilsIntSetWithInitialSizeSet_whenPopulated_checkTimeTaken() {
IntSet intSet = new IntOpenHashSet(setSize);
for(int i = 0; i < setSize; i++){
intSet.add(i);
}
return intSet;
}
@Benchmark
public Set<Integer> givenCollectionsHashSetWithInitialSizeSet_whenPopulated_checkTimeTaken() {
Set<Integer> intSet = new HashSet<Integer>(setSize);
for(int i = 0; i < setSize; i++){
intSet.add(i);
}
return intSet;
}
public static void main(String... args) throws RunnerException {
Options opts = new OptionsBuilder()
.include(".*")
.warmupIterations(1)
.measurementIterations(2)
.jvmArgs("-Xms2g", "-Xmx2g")
.shouldDoGC(true)
.forks(1)
.build();
new Runner(opts).run();
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung;
import it.unimi.dsi.fastutil.doubles.Double2DoubleMap;
import it.unimi.dsi.fastutil.doubles.Double2DoubleOpenHashMap;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
public class FastUtilTypeSpecificUnitTest {
@Test
public void givenValidDouble2DoubleMap_whenContentsQueried_checkCorrect(){
Double2DoubleMap d2dMap = new Double2DoubleOpenHashMap();
d2dMap.put(2.0, 5.5);
d2dMap.put(3.0, 6.6);
assertEquals(5.5, d2dMap.get(2.0));
}
}

View File

@ -7,4 +7,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [HttpClient 4 Get the Status Code](http://www.baeldung.com/httpclient-status-code)
- [HttpClient 4 Get the Status Code](http://www.baeldung.com/httpclient-status-code)
- [HttpClient with SSL](http://www.baeldung.com/httpclient-ssl)
- [HttpClient Basic Authentication](http://www.baeldung.com/httpclient-4-basic-authentication)

View File

@ -5,15 +5,111 @@
<artifactId>httpclient-simple</artifactId>
<version>0.1-SNAPSHOT</version>
<name>httpclient-simple</name>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<artifactId>parent-spring-5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
<relativePath>../parent-spring-5</relativePath>
</parent>
<dependencies>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>${httpcore.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- utils -->
<dependency>
<groupId>org.apache.commons</groupId>
@ -70,16 +166,77 @@
<version>${wiremock.version}</version>
<scope>test</scope>
</dependency>
<!-- web -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
<scope>runtime</scope>
</dependency>
<!-- util -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>httpclient</finalName>
<finalName>httpclient-simple</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<wait>true</wait>
<container>
<containerId>jetty8x</containerId>
<type>embedded</type>
<systemProperties>
<!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
</systemProperties>
</container>
<configuration>
<properties>
<cargo.servlet.port>8082</cargo.servlet.port>
</properties>
</configuration>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
@ -87,6 +244,27 @@
<id>live</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<executions>
<execution>
<id>start-server</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>stop-server</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
@ -98,26 +276,28 @@
</goals>
<configuration>
<excludes>
<exclude>**/*ManualTest.java</exclude>
<exclude>none</exclude>
</excludes>
<includes>
<include>**/*LiveTest.java</include>
</includes>
<systemPropertyVariables>
<webTarget>cargo</webTarget>
</systemPropertyVariables>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- various -->
<jstl.version>1.2</jstl.version>
<javax.servlet.version>3.1.0</javax.servlet.version>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
@ -125,8 +305,10 @@
<httpasyncclient.version>4.1.4</httpasyncclient.version>
<!-- testing -->
<wiremock.version>2.5.1</wiremock.version>
<httpcore.version>4.4.11</httpcore.version>
<httpclient.version>4.5.8</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 -->
<!-- maven plugins -->
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
</properties>

View File

@ -0,0 +1,30 @@
package org.baeldung.basic;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@Component
public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
@Override
public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException {
response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\"");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
final PrintWriter writer = response.getWriter();
writer.println("HTTP Status " + HttpServletResponse.SC_UNAUTHORIZED + " - " + authException.getMessage());
}
@Override
public void afterPropertiesSet() throws Exception {
setRealmName("Baeldung");
super.afterPropertiesSet();
}
}

View File

@ -0,0 +1,39 @@
package org.baeldung.client;
import java.net.URI;
import org.apache.http.HttpHost;
import org.apache.http.client.AuthCache;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
public class HttpComponentsClientHttpRequestFactoryBasicAuth extends HttpComponentsClientHttpRequestFactory {
HttpHost host;
public HttpComponentsClientHttpRequestFactoryBasicAuth(HttpHost host) {
super();
this.host = host;
}
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
return createHttpContext();
}
private HttpContext createHttpContext() {
AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
authCache.put(host, basicAuth);
BasicHttpContext localcontext = new BasicHttpContext();
localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
return localcontext;
}
}

View File

@ -0,0 +1,44 @@
package org.baeldung.client;
import org.apache.http.HttpHost;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.support.BasicAuthenticationInterceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class RestTemplateFactory implements FactoryBean<RestTemplate>, InitializingBean {
private RestTemplate restTemplate;
public RestTemplateFactory() {
super();
}
// API
@Override
public RestTemplate getObject() {
return restTemplate;
}
@Override
public Class<RestTemplate> getObjectType() {
return RestTemplate.class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public void afterPropertiesSet() {
HttpHost host = new HttpHost("localhost", 8082, "http");
final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth(host);
restTemplate = new RestTemplate(requestFactory);
restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor("user1", "user1Pass"));
}
}

View File

@ -0,0 +1,16 @@
package org.baeldung.client.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("org.baeldung.client")
public class ClientConfig {
public ClientConfig() {
super();
}
// beans
}

View File

@ -0,0 +1,18 @@
package org.baeldung.filter;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
public class CustomFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, response);
}
}

View File

@ -0,0 +1,49 @@
package org.baeldung.filter;
import org.baeldung.security.RestAuthenticationEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Autowired private RestAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user1")
.password(passwordEncoder().encode("user1Pass"))
.authorities("ROLE_USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/securityNone")
.permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint);
http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -0,0 +1,48 @@
package org.baeldung.security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
public class MySavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private RequestCache requestCache = new HttpSessionRequestCache();
@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws ServletException, IOException {
final SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest == null) {
super.onAuthenticationSuccess(request, response, authentication);
return;
}
final String targetUrlParameter = getTargetUrlParameter();
if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
requestCache.removeRequest(request, response);
super.onAuthenticationSuccess(request, response, authentication);
return;
}
clearAuthenticationAttributes(request);
// Use the DefaultSavedRequest URL
// final String targetUrl = savedRequest.getRedirectUrl();
// logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
// getRedirectStrategy().sendRedirect(request, response, targetUrl);
}
public void setRequestCache(final RequestCache requestCache) {
this.requestCache = requestCache;
}
}

View File

@ -0,0 +1,23 @@
package org.baeldung.security;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
/**
* The Entry Point will not redirect to any sort of Login - it will return the 401
*/
@Component
public final class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}

View File

@ -0,0 +1,16 @@
package org.baeldung.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource({ "classpath:webSecurityConfig.xml" })
@ComponentScan("org.baeldung.security")
public class SecSecurityConfig {
public SecSecurityConfig() {
super();
}
}

View File

@ -0,0 +1,30 @@
package org.baeldung.spring;
import java.util.List;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
@ComponentScan("org.baeldung.web")
public class WebConfig implements WebMvcConfigurer {
public WebConfig() {
super();
}
// beans
@Override
public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
converters.add(new MappingJackson2HttpMessageConverter());
}
//
}

View File

@ -0,0 +1,31 @@
package org.baeldung.web.controller;
import org.baeldung.web.dto.Bar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/bars")
public class BarController {
@Autowired
private ApplicationEventPublisher eventPublisher;
public BarController() {
super();
}
// API
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public Bar findOne(@PathVariable("id") final Long id) {
return new Bar();
}
}

View File

@ -0,0 +1,33 @@
package org.baeldung.web.controller;
import org.baeldung.web.dto.Foo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/foos")
public class FooController {
@Autowired
private ApplicationEventPublisher eventPublisher;
public FooController() {
super();
}
// API
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
@PreAuthorize("hasRole('ROLE_USER')")
public Foo findOne(@PathVariable("id") final Long id) {
return new Foo();
}
}

View File

@ -0,0 +1,14 @@
package org.baeldung.web.dto;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Bar implements Serializable {
public Bar() {
super();
}
}

View File

@ -0,0 +1,14 @@
package org.baeldung.web.dto;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Foo implements Serializable {
public Foo() {
super();
}
}

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
>
<http create-session="stateless" use-expressions="true">
<http-basic entry-point-ref="myBasicAuthenticationEntryPoint"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user1" password="{noop}user1Pass" authorities="ROLE_USER"/>
</user-service>
</authentication-provider>
</authentication-manager>
<global-method-security pre-post-annotations="enabled"/>
<beans:bean id="myBasicAuthenticationEntryPoint" class="org.baeldung.basic.MyBasicAuthenticationEntryPoint" />
</beans:beans>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" >
</beans>

View File

@ -0,0 +1,43 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"
>
<display-name>Spring Security Custom Application</display-name>
<!-- Spring root -->
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>org.baeldung.spring</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring child -->
<servlet>
<servlet-name>api</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>api</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

View File

@ -33,13 +33,13 @@ public class ClientLiveTest {
@Test
public final void whenSecuredRestApiIsConsumed_then200OK() {
final ResponseEntity<Foo> responseEntity = secureRestTemplate.exchange("http://localhost:8082/spring-security-rest-basic-auth/api/foos/1", HttpMethod.GET, null, Foo.class);
final ResponseEntity<Foo> responseEntity = secureRestTemplate.exchange("http://localhost:8082/httpclient-simple/api/foos/1", HttpMethod.GET, null, Foo.class);
assertThat(responseEntity.getStatusCode().value(), is(200));
}
@Test(expected = ResourceAccessException.class)
public final void whenHttpsUrlIsConsumed_thenException() {
final String urlOverHttps = "https://localhost:8443/spring-security-rest-basic-auth/api/bars/1";
final String urlOverHttps = "https://localhost:8443/httpclient-simple/api/bars/1";
final ResponseEntity<String> response = new RestTemplate().exchange(urlOverHttps, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}

View File

@ -8,19 +8,24 @@ import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.http.HttpMethod;
@ -34,14 +39,14 @@ import org.springframework.web.client.RestTemplate;
* */
public class RestClientLiveManualTest {
final String urlOverHttps = "http://localhost:8082/spring-security-rest-basic-auth/api/bars/1";
final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1";
// tests
// old httpClient will throw UnsupportedOperationException
@Ignore
@Test
public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenException() throws GeneralSecurityException {
public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenException_1() throws GeneralSecurityException {
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
final CloseableHttpClient httpClient = (CloseableHttpClient) requestFactory.getHttpClient();
@ -57,6 +62,29 @@ public class RestClientLiveManualTest {
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}
// new httpClient : 4.4 and above
@Test
public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenException_2() throws GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("https", sslsf)
.register("http", new PlainConnectionSocketFactory())
.build();
final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setConnectionManager(connectionManager)
.build();
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}
@Test
public final void givenAcceptingAllCertificatesUsing4_4_whenHttpsUrlIsConsumed_thenCorrect() throws ClientProtocolException, IOException {

View File

@ -23,19 +23,18 @@ import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
/*
* NOTE : Need module spring-security-rest-basic-auth to be running
* NOTE : Need module httpclient-simple to be running
*/
public class HttpClientAuthLiveTest {
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://localhost:8081/spring-security-rest-basic-auth/api/foos/1";
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://localhost:8082/httpclient-simple/api/foos/1";
private static final String DEFAULT_USER = "user1";
private static final String DEFAULT_PASS = "user1Pass";
@ -111,7 +110,7 @@ public class HttpClientAuthLiveTest {
}
private HttpContext context() {
final HttpHost targetHost = new HttpHost("localhost", 8080, "http");
final HttpHost targetHost = new HttpHost("localhost", 8082, "http");
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS));

View File

@ -13,7 +13,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Unshorten URLs with HttpClient](http://www.baeldung.com/unshorten-url-httpclient)
- [HttpClient 4 Follow Redirects for POST](http://www.baeldung.com/httpclient-redirect-on-http-post)
- [Custom HTTP Header with the HttpClient](http://www.baeldung.com/httpclient-custom-http-header)
- [HttpClient Basic Authentication](http://www.baeldung.com/httpclient-4-basic-authentication)
- [Multipart Upload with HttpClient 4](http://www.baeldung.com/httpclient-multipart-upload)
- [HttpAsyncClient Tutorial](http://www.baeldung.com/httpasyncclient-tutorial)
- [HttpClient 4 Tutorial](http://www.baeldung.com/httpclient-guide)

View File

@ -29,6 +29,6 @@ public class CourseService {
}
public static void copyProperties(Course course, CourseEntity courseEntity) throws IllegalAccessException, InvocationTargetException {
BeanUtils.copyProperties(course, courseEntity);
BeanUtils.copyProperties(courseEntity, course);
}
}

View File

@ -44,6 +44,8 @@ public class CourseServiceUnitTest {
CourseEntity courseEntity = new CourseEntity();
CourseService.copyProperties(course, courseEntity);
Assert.assertNotNull(course.getName());
Assert.assertNotNull(courseEntity.getName());
Assert.assertEquals(course.getName(), courseEntity.getName());
Assert.assertEquals(course.getCodes(), courseEntity.getCodes());
Assert.assertNull(courseEntity.getStudent("ST-1"));

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.multimodule-maven-project</groupId>
<artifactId>multimodule-maven-project</artifactId>
<version>1.0</version>
</parent>
<groupId>com.baeldung.daomodule</groupId>
<artifactId>daomodule</artifactId>
<packaging>jar</packaging>
<version>1.0</version>
<name>daomodule</name>
</project>

View File

@ -0,0 +1,12 @@
package com.baeldung.dao;
import java.util.List;
import java.util.Optional;
public interface Dao<T> {
Optional<T> findById(int id);
List<T> findAll();
}

View File

@ -0,0 +1,3 @@
module com.baeldung.dao {
exports com.baeldung.dao;
}

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.multimodule-maven-project</groupId>
<artifactId>multimodule-maven-project</artifactId>
<version>1.0</version>
</parent>
<groupId>com.baeldung.entitymodule</groupId>
<artifactId>entitymodule</artifactId>
<packaging>jar</packaging>
<version>1.0</version>
<name>entitymodule</name>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,19 @@
package com.baeldung.entity;
public class User {
private final String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "User{" + "name=" + name + '}';
}
}

View File

@ -0,0 +1,3 @@
module com.baeldung.entity {
exports com.baeldung.entity;
}

View File

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.multimodule-maven-project</groupId>
<artifactId>multimodule-maven-project</artifactId>
<version>1.0</version>
</parent>
<groupId>com.baeldung.mainappmodule</groupId>
<artifactId>mainappmodule</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>mainappmodule</name>
<dependencies>
<dependency>
<groupId>com.baeldung.entitymodule</groupId>
<artifactId>entitymodule</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.baeldung.daomodule</groupId>
<artifactId>daomodule</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.baeldung.userdaomodule</groupId>
<artifactId>userdaomodule</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,19 @@
package com.baeldung.mainapp;
import com.baeldung.dao.Dao;
import com.baeldung.entity.User;
import com.baeldung.userdao.UserDao;
import java.util.HashMap;
import java.util.Map;
public class Application {
public static void main(String[] args) {
Map<Integer, User> users = new HashMap<>();
users.put(1, new User("Julie"));
users.put(2, new User("David"));
Dao userDao = new UserDao(users);
userDao.findAll().forEach(System.out::println);
}
}

View File

@ -0,0 +1,6 @@
module com.baeldung.mainapp {
requires com.baeldung.entity;
requires com.baeldung.userdao;
requires com.baeldung.dao;
uses com.baeldung.dao.Dao;
}

View File

@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.multimodule-maven-project</groupId>
<artifactId>multimodule-maven-project</artifactId>
<version>1.0</version>
<packaging>pom</packaging>
<name>multimodule-maven-project</name>
<parent>
<groupId>com.baeldung.maven-java-11</groupId>
<artifactId>maven-java-11</artifactId>
<version>1.0</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.12.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<modules>
<module>entitymodule</module>
<module>daomodule</module>
<module>userdaomodule</module>
<module>mainappmodule</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.multimodule-maven-project</groupId>
<artifactId>multimodule-maven-project</artifactId>
<version>1.0</version>
</parent>
<groupId>com.baeldung.userdaomodule</groupId>
<artifactId>userdaomodule</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>userdaomodule</name>
<dependencies>
<dependency>
<groupId>com.baeldung.entitymodule</groupId>
<artifactId>entitymodule</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.baeldung.daomodule</groupId>
<artifactId>daomodule</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,32 @@
package com.baeldung.userdao;
import com.baeldung.dao.Dao;
import com.baeldung.entity.User;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class UserDao implements Dao<User> {
private final Map<Integer, User> users;
public UserDao() {
users = new HashMap<>();
}
public UserDao(Map<Integer, User> users) {
this.users = users;
}
@Override
public List<User> findAll() {
return new ArrayList<>(users.values());
}
@Override
public Optional<User> findById(int id) {
return Optional.ofNullable(users.get(id));
}
}

View File

@ -0,0 +1,6 @@
module com.baeldung.userdao {
requires com.baeldung.entity;
requires com.baeldung.dao;
provides com.baeldung.dao.Dao with com.baeldung.userdao.UserDao;
exports com.baeldung.userdao;
}

View File

@ -0,0 +1,36 @@
package com.baeldung.userdao.test;
import com.baeldung.dao.Dao;
import com.baeldung.entity.User;
import com.baeldung.userdao.UserDao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.junit.Before;
import org.junit.Test;
public class UserDaoUnitTest {
private Dao userDao;
@Before
public void setUpUserDaoInstance() {
Map<Integer, User> users = new HashMap<>();
users.put(1, new User("Julie"));
users.put(2, new User("David"));
userDao = new UserDao(users);
}
@Test
public void givenUserDaoIntance_whenCalledFindById_thenCorrect() {
assertThat(userDao.findById(1), isA(Optional.class));
}
@Test
public void givenUserDaoIntance_whenCalledFindAll_thenCorrect() {
assertThat(userDao.findAll(), isA(List.class));
}
}

22
maven-java-11/pom.xml Normal file
View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.maven-java-11</groupId>
<artifactId>maven-java-11</artifactId>
<version>1.0</version>
<packaging>pom</packaging>
<name>maven-java-11</name>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modules>
<name>multimodule-maven-project</name>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,3 @@
### Relevant Articles
- [The Mediator Pattern in Java](https://www.baeldung.com/java-mediator-pattern)

View File

@ -35,8 +35,8 @@
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<mongo.version>3.4.1</mongo.version>
<mongo.version>3.10.1</mongo.version>
<flapdoodle.version>1.11</flapdoodle.version>
</properties>
</project>
</project>

View File

@ -0,0 +1,79 @@
package com.baeldung;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MongoBsonExample
{
public static void main(String[] args)
{
//
// 4.1 Connect to cluster (default is localhost:27017)
//
MongoClient mongoClient = MongoClients.create();
MongoDatabase database = mongoClient.getDatabase("myDB");
MongoCollection<Document> collection = database.getCollection("employees");
//
// 4.2 Insert new document
//
Document employee = new Document()
.append("first_name", "Joe")
.append("last_name", "Smith")
.append("title", "Java Developer")
.append("years_of_service", 3)
.append("skills", Arrays.asList("java", "spring", "mongodb"))
.append("manager", new Document()
.append("first_name", "Sally")
.append("last_name", "Johanson"));
collection.insertOne(employee);
//
// 4.3 Find documents
//
Document query = new Document("last_name", "Smith");
List results = new ArrayList<>();
collection.find(query).into(results);
query =
new Document("$or", Arrays.asList(
new Document("last_name", "Smith"),
new Document("first_name", "Joe")));
results = new ArrayList<>();
collection.find(query).into(results);
//
// 4.4 Update document
//
query = new Document(
"skills",
new Document(
"$elemMatch",
new Document("$eq", "spring")));
Document update = new Document(
"$push",
new Document("skills", "security"));
collection.updateMany(query, update);
//
// 4.5 Delete documents
//
query = new Document(
"years_of_service",
new Document("$lt", 0));
collection.deleteMany(query);
}
}

View File

@ -35,7 +35,7 @@
<module>querydsl</module>
<module>redis</module>
<module>solr</module>
<module>spring-boot-h2/spring-boot-h2-database</module>
<module>spring-boot-persistence-h2</module>
<module>spring-boot-persistence</module>
<module>spring-boot-persistence-mongodb</module>
<module>spring-data-cassandra</module>

View File

@ -1,2 +1,3 @@
### Relevant Articles:
- [Access the Same In-Memory H2 Database in Multiple Spring Boot Applications](https://www.baeldung.com/spring-boot-access-h2-database-multiple-apps)
- [Spring Boot With H2 Database](https://www.baeldung.com/spring-boot-h2-database)

View File

@ -14,7 +14,7 @@
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-2</relativePath>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>

10
pom.xml
View File

@ -389,6 +389,7 @@
<module>core-java-collections</module>
<module>core-java-collections-map</module>
<module>core-java-collections-list</module>
<module>core-java-collections-set</module>
<module>core-java-concurrency-basic</module>
<module>core-java-concurrency-collections</module>
<module>core-java-io</module>
@ -1060,6 +1061,7 @@
<module>core-java-collections</module>
<module>core-java-collections-map</module>
<module>core-java-collections-list</module>
<module>core-java-collections-set</module>
<module>core-java-concurrency-basic</module>
<module>core-java-concurrency-collections</module>
<module>core-java-io</module>
@ -1170,6 +1172,7 @@
<module>mapstruct</module>
<module>maven</module>
<module>maven-java-11</module>
<module>maven-archetype</module>
<!-- <module>maven-polyglot/maven-polyglot-json-app</module> --> <!-- Not a maven project -->
<module>maven-polyglot/maven-polyglot-json-extension</module>
@ -1497,8 +1500,9 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<gib.referenceBranch>refs/remotes/origin/master</gib.referenceBranch>
<gib.skipTestsForNotImpactedModules>true</gib.skipTestsForNotImpactedModules>
<gib.referenceBranch>refs/remotes/origin/master</gib.referenceBranch>
<gib.skipTestsForUpstreamModules>true</gib.skipTestsForUpstreamModules>
<gib.buildUpstream>false</gib.buildUpstream>
<gib.failOnMissingGitDir>false</gib.failOnMissingGitDir>
<gib.failOnError>false</gib.failOnError>
<gib.enabled>false</gib.enabled>
@ -1539,7 +1543,7 @@
<directory-maven-plugin.version>0.3.1</directory-maven-plugin.version>
<maven-install-plugin.version>2.5.1</maven-install-plugin.version>
<custom-pmd.version>0.0.1</custom-pmd.version>
<gitflow-incremental-builder.version>3.4</gitflow-incremental-builder.version>
<gitflow-incremental-builder.version>3.8</gitflow-incremental-builder.version>
<maven-jxr-plugin.version>2.3</maven-jxr-plugin.version>
<!-- <maven-pmd-plugin.version>3.9.0</maven-pmd-plugin.version> -->
<maven-pmd-plugin.version>3.8</maven-pmd-plugin.version>

View File

@ -0,0 +1,16 @@
package com.baeldung.cognito;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@PropertySource("cognito/application_cognito.yml")
public class CognitoWebConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.cognito;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
@SpringBootApplication
@PropertySource("cognito/application_cognito.yml")
public class SpringCognitoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCognitoApplication.class, args);
}
}

View File

@ -0,0 +1,15 @@
spring:
security:
oauth2:
client:
registration:
cognito:
client-id: clientId
client-secret: clientSecret
scope: openid
redirectUriTemplate: "http://localhost:8080/login/oauth2/code/cognito"
clientName: cognito-client-name
provider:
cognito:
issuerUri: https://cognito-idp.{region}.amazonaws.com/{poolId}
usernameAttribute: cognito:username

View File

@ -0,0 +1,32 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>OAuth2 Cognito Demo</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.4/css/bulma.min.css">
<link rel="stylesheet" th:href="@{/cognito/style.css}">
</head>
<body>
<section class="section">
<div class="container has-text-centered">
<div>
<h1 class="title">OAuth2 Spring Security Cognito Demo</h1>
<div sec:authorize="isAuthenticated()">
<div class="box">
Hello, <strong th:text="${#authentication.name}"></strong>!
</div>
</div>
<div sec:authorize="isAnonymous()">
<div class="box">
<a class="button login is-primary" th:href="@{/oauth2/authorization/cognito}">Log in with Amazon Cognito</a>
</div>
</div>
</div>
</div>
</section>
</body>
</html>

View File

@ -0,0 +1,9 @@
.login {
background-color: #7289da;
color: #fff;
}
.login:hover {
background-color: #697ec4;
color: #fff;
}

View File

@ -0,0 +1,29 @@
HELP.md
/target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
/build/
### VS Code ###
.vscode/

View File

@ -0,0 +1,43 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.baeldung</groupId>
<artifactId>pass-exception-to-client-json-spring-boot</artifactId>
<version>0.0.4-SNAPSHOT</version>
<name>pass-exception-to-client-json-spring-boot</name>
<description>Baeldung article code on how to pass exceptions to client in JSON format using Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,11 @@
package com.baeldung.passexceptiontoclientjsonspringboot;
public class CustomException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CustomException() {
super("Custom exception message.");
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.passexceptiontoclientjsonspringboot;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
@ResponseBody
public class ErrorHandler {
@ExceptionHandler(CustomException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public CustomException handleCustomException(CustomException ce) {
return ce;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.passexceptiontoclientjsonspringboot;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class MainController {
@GetMapping("/")
public void index() throws CustomException {
throw new CustomException();
}
}

View File

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

View File

@ -0,0 +1,4 @@
# Ignore everything in this directory
*
# Except this file
!.gitignore

View File

@ -0,0 +1,4 @@
# Ignore everything in this directory
*
# Except this file
!.gitignore

View File

@ -0,0 +1,16 @@
package com.baeldung.passexceptiontoclientjsonspringboot;
import org.junit.Test;
public class MainControllerIntegrationTest {
@Test(expected = CustomException.class)
public void givenIndex_thenCustomException() throws CustomException {
MainController mainController = new MainController();
mainController.index();
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.passexceptiontoclientjsonspringboot;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class PassExceptionToClientJsonSpringBootApplicationTests {
@Test
public void contextLoads() {
}
}

View File

@ -0,0 +1,3 @@
### Relevant Articles
- [BIRT Reporting with Spring Boot](https://www.baeldung.com/birt-reports-spring-boot)

View File

@ -7,10 +7,12 @@ Module for the articles that are part of the Spring REST E-book:
5. [Entity To DTO Conversion for a Spring REST API](https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application)
6. [Error Handling for REST with Spring](http://www.baeldung.com/exception-handling-for-rest-with-spring)
7. [REST API Discoverability and HATEOAS](http://www.baeldung.com/restful-web-service-discoverability)
8. [REST Pagination in Spring](http://www.baeldung.com/rest-api-pagination-in-spring)
9. [Test a REST API with Java](http://www.baeldung.com/integration-testing-a-rest-api)
10. [HATEOAS for a Spring REST Service](http://www.baeldung.com/rest-api-discoverability-with-spring)
11. [Versioning a REST API](http://www.baeldung.com/rest-versioning)
12. [ETags for REST with Spring](http://www.baeldung.com/etags-for-rest-with-spring)
13. [Testing REST with multiple MIME types](http://www.baeldung.com/testing-rest-api-with-multiple-media-types)
14. [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections)
8. [An Intro to Spring HATEOAS](http://www.baeldung.com/spring-hateoas-tutorial)
9. [REST Pagination in Spring](http://www.baeldung.com/rest-api-pagination-in-spring)
10. [Test a REST API with Java](http://www.baeldung.com/integration-testing-a-rest-api)
- [HATEOAS for a Spring REST Service](http://www.baeldung.com/rest-api-discoverability-with-spring)
- [Versioning a REST API](http://www.baeldung.com/rest-versioning)
- [ETags for REST with Spring](http://www.baeldung.com/etags-for-rest-with-spring)
- [Testing REST with multiple MIME types](http://www.baeldung.com/testing-rest-api-with-multiple-media-types)
- [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections)

View File

@ -44,6 +44,12 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Spring HATEOAS -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<!-- util -->

View File

@ -21,6 +21,7 @@ import com.baeldung.modelmapper.service.IPostService;
import com.baeldung.modelmapper.service.IUserService;
@Controller
@RequestMapping("/posts")
public class PostRestController {
@Autowired

View File

@ -1,4 +1,4 @@
package org.baeldung.persistence.model;
package com.baeldung.persistence.model;
import java.util.Map;

View File

@ -1,4 +1,4 @@
package org.baeldung.persistence.model;
package com.baeldung.persistence.model;
import org.springframework.hateoas.ResourceSupport;

View File

@ -1,8 +1,8 @@
package org.baeldung.web.service;
package com.baeldung.services;
import java.util.List;
import org.baeldung.persistence.model.Customer;
import com.baeldung.persistence.model.Customer;
public interface CustomerService {

View File

@ -1,12 +1,13 @@
package org.baeldung.web.service;
package com.baeldung.services;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.baeldung.persistence.model.Customer;
import org.springframework.stereotype.Service;
import com.baeldung.persistence.model.Customer;
@Service
public class CustomerServiceImpl implements CustomerService {

View File

@ -1,8 +1,8 @@
package org.baeldung.web.service;
package com.baeldung.services;
import java.util.List;
import org.baeldung.persistence.model.Order;
import com.baeldung.persistence.model.Order;
public interface OrderService {

View File

@ -1,14 +1,15 @@
package org.baeldung.web.service;
package com.baeldung.services;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.baeldung.persistence.model.Customer;
import org.baeldung.persistence.model.Order;
import org.springframework.stereotype.Service;
import com.baeldung.persistence.model.Customer;
import com.baeldung.persistence.model.Order;
@Service
public class OrderServiceImpl implements OrderService {

Some files were not shown because too many files have changed in this diff Show More