diff --git a/cdi/pom.xml b/cdi/pom.xml index 2a9d32188b..b771857938 100644 --- a/cdi/pom.xml +++ b/cdi/pom.xml @@ -1,52 +1,52 @@ - + 4.0.0 com.baeldung cdi 1.0-SNAPSHOT - - 4.3.1.RELEASE - + - - - junit - junit - 4.12 - - org.springframework spring-core ${spring.version} - org.springframework spring-context ${spring.version} - + + + org.aspectj + aspectjweaver + 1.8.9 + + + org.jboss.weld.se + weld-se-core + 2.3.5.Final + + + + junit + junit + 4.12 + test + org.springframework spring-test ${spring.version} test - - - org.aspectj - aspectjweaver - 1.8.9 - - - - org.jboss.weld.se - weld-se-core - 2.3.5.Final - + + + + 4.3.1.RELEASE + + \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/interceptor/Audited.java b/cdi/src/main/java/com/baeldung/interceptor/Audited.java index 4065450b09..3df4bef95e 100644 --- a/cdi/src/main/java/com/baeldung/interceptor/Audited.java +++ b/cdi/src/main/java/com/baeldung/interceptor/Audited.java @@ -1,12 +1,14 @@ package com.baeldung.interceptor; -import javax.interceptor.InterceptorBinding; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import javax.interceptor.InterceptorBinding; + @InterceptorBinding -@Target( {ElementType.METHOD, ElementType.TYPE } ) -@Retention(RetentionPolicy.RUNTIME ) -public @interface Audited {} +@Target({ ElementType.METHOD, ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +public @interface Audited { +} diff --git a/cdi/src/main/java/com/baeldung/interceptor/AuditedInterceptor.java b/cdi/src/main/java/com/baeldung/interceptor/AuditedInterceptor.java index 46ab9b33c8..c62d9a4127 100644 --- a/cdi/src/main/java/com/baeldung/interceptor/AuditedInterceptor.java +++ b/cdi/src/main/java/com/baeldung/interceptor/AuditedInterceptor.java @@ -3,12 +3,13 @@ package com.baeldung.interceptor; import javax.interceptor.AroundInvoke; import javax.interceptor.Interceptor; import javax.interceptor.InvocationContext; -import java.lang.reflect.Method; -@Audited @Interceptor +@Audited +@Interceptor public class AuditedInterceptor { public static boolean calledBefore = false; public static boolean calledAfter = false; + @AroundInvoke public Object auditMethod(InvocationContext ctx) throws Exception { calledBefore = true; diff --git a/cdi/src/main/java/com/baeldung/service/SuperService.java b/cdi/src/main/java/com/baeldung/service/SuperService.java index e1e57a4e0d..e15f049342 100644 --- a/cdi/src/main/java/com/baeldung/service/SuperService.java +++ b/cdi/src/main/java/com/baeldung/service/SuperService.java @@ -5,6 +5,6 @@ import com.baeldung.interceptor.Audited; public class SuperService { @Audited public String deliverService(String uid) { - return uid; + return uid; } } diff --git a/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java b/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java index 8c2ff2600b..e48039706d 100644 --- a/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java +++ b/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java @@ -1,26 +1,23 @@ package com.baeldung.spring.aspect; -import org.aspectj.lang.JoinPoint; +import java.util.List; + import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.annotation.Before; import org.springframework.beans.factory.annotation.Autowired; -import javax.inject.Inject; -import java.util.List; - @Aspect public class SpringTestAspect { @Autowired private List accumulator; @Around("execution(* com.baeldung.spring.service.SpringSuperService.*(..))") - public Object advice(ProceedingJoinPoint jp) throws Throwable { + public Object auditMethod(ProceedingJoinPoint jp) throws Throwable { String methodName = jp.getSignature().getName(); - accumulator.add("Call to "+methodName); + accumulator.add("Call to " + methodName); Object obj = jp.proceed(); - accumulator.add("Method called successfully: "+methodName); + accumulator.add("Method called successfully: " + methodName); return obj; } } diff --git a/cdi/src/main/java/com/baeldung/spring/configuration/AppConfig.java b/cdi/src/main/java/com/baeldung/spring/configuration/AppConfig.java index 6cfc8f8743..b30c4a1326 100644 --- a/cdi/src/main/java/com/baeldung/spring/configuration/AppConfig.java +++ b/cdi/src/main/java/com/baeldung/spring/configuration/AppConfig.java @@ -1,13 +1,14 @@ package com.baeldung.spring.configuration; -import com.baeldung.spring.aspect.SpringTestAspect; -import com.baeldung.spring.service.SpringSuperService; +import java.util.ArrayList; +import java.util.List; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; -import java.util.ArrayList; -import java.util.List; +import com.baeldung.spring.aspect.SpringTestAspect; +import com.baeldung.spring.service.SpringSuperService; @Configuration @EnableAspectJAutoProxy @@ -18,12 +19,12 @@ public class AppConfig { } @Bean - public SpringTestAspect springTestAspect(){ + public SpringTestAspect springTestAspect() { return new SpringTestAspect(); } @Bean - public List getAccumulator(){ + public List getAccumulator() { return new ArrayList(); } } diff --git a/cdi/src/main/java/com/baeldung/spring/service/SpringSuperService.java b/cdi/src/main/java/com/baeldung/spring/service/SpringSuperService.java index 72dbd1c006..082eb2e0f8 100644 --- a/cdi/src/main/java/com/baeldung/spring/service/SpringSuperService.java +++ b/cdi/src/main/java/com/baeldung/spring/service/SpringSuperService.java @@ -1,7 +1,7 @@ package com.baeldung.spring.service; public class SpringSuperService { - public String getInfoFromService(String code){ + public String getInfoFromService(String code) { return code; } } diff --git a/cdi/src/test/java/com/baeldung/test/TestInterceptor.java b/cdi/src/test/java/com/baeldung/test/TestInterceptor.java index d1b851c94f..3529a796d2 100644 --- a/cdi/src/test/java/com/baeldung/test/TestInterceptor.java +++ b/cdi/src/test/java/com/baeldung/test/TestInterceptor.java @@ -1,8 +1,5 @@ package com.baeldung.test; -import com.baeldung.interceptor.Audited; -import com.baeldung.interceptor.AuditedInterceptor; -import com.baeldung.service.SuperService; import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; import org.junit.After; @@ -10,24 +7,21 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import javax.enterprise.inject.spi.BeanManager; -import javax.enterprise.inject.spi.InterceptionType; -import javax.enterprise.inject.spi.Interceptor; -import javax.enterprise.util.AnnotationLiteral; - -import static javafx.beans.binding.Bindings.select; +import com.baeldung.interceptor.AuditedInterceptor; +import com.baeldung.service.SuperService; public class TestInterceptor { Weld weld; WeldContainer container; + @Before - public void init(){ + public void init() { weld = new Weld(); container = weld.initialize(); } @After - public void shutdown(){ + public void shutdown() { weld.shutdown(); } @@ -36,7 +30,9 @@ public class TestInterceptor { SuperService superService = container.select(SuperService.class).get(); String code = "123456"; superService.deliverService(code); + Assert.assertTrue(AuditedInterceptor.calledBefore); Assert.assertTrue(AuditedInterceptor.calledAfter); } + } diff --git a/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java b/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java index b5aedd4b76..1f3a8d83e3 100644 --- a/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java +++ b/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java @@ -1,25 +1,21 @@ package com.baeldung.test; -import com.baeldung.spring.configuration.AppConfig; -import com.baeldung.spring.service.SpringSuperService; +import static org.hamcrest.CoreMatchers.is; + +import java.util.List; + import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; -import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import org.springframework.test.context.transaction.TransactionalTestExecutionListener; -import javax.inject.Inject; -import java.util.List; - -import static org.hamcrest.CoreMatchers.is; +import com.baeldung.spring.configuration.AppConfig; +import com.baeldung.spring.service.SpringSuperService; @RunWith(SpringRunner.class) -@ContextConfiguration(classes = {AppConfig.class}) +@ContextConfiguration(classes = { AppConfig.class }) public class TestSpringInterceptor { @Autowired SpringSuperService springSuperService; @@ -28,11 +24,11 @@ public class TestSpringInterceptor { private List accumulator; @Test - public void givenService_whenServiceAndAspectExecuted_thenOk(){ + public void givenService_whenServiceAndAspectExecuted_thenOk() { String code = "123456"; String result = springSuperService.getInfoFromService(code); Assert.assertThat(accumulator.size(), is(2)); - Assert.assertThat(accumulator.get(0),is("Call to getInfoFromService")); - Assert.assertThat(accumulator.get(1),is("Method called successfully: getInfoFromService")); + Assert.assertThat(accumulator.get(0), is("Call to getInfoFromService")); + Assert.assertThat(accumulator.get(1), is("Method called successfully: getInfoFromService")); } } diff --git a/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java b/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java index 806bca5461..5363a73afa 100644 --- a/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java +++ b/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java @@ -1,14 +1,11 @@ package com.baeldung.completablefuture; -import org.junit.Test; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; +import java.util.concurrent.*; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.junit.Test; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -46,6 +43,28 @@ public class CompletableFutureTest { } + + public Future calculateAsyncWithCancellation() throws InterruptedException { + CompletableFuture completableFuture = new CompletableFuture<>(); + + Executors.newCachedThreadPool().submit(() -> { + Thread.sleep(500); + completableFuture.cancel(false); + return null; + }); + + return completableFuture; + } + + + @Test(expected = CancellationException.class) + public void whenCancelingTheFuture_thenThrowsCancellationException() throws ExecutionException, InterruptedException { + + Future future = calculateAsyncWithCancellation(); + future.get(); + + } + @Test public void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() throws ExecutionException, InterruptedException { @@ -187,4 +206,4 @@ public class CompletableFutureTest { } -} +} \ No newline at end of file diff --git a/hystrix/src/main/java/com/baeldung/hystrix/HystrixController.java b/hystrix/src/main/java/com/baeldung/hystrix/HystrixController.java index a8ca0adef2..69d9e30ff8 100644 --- a/hystrix/src/main/java/com/baeldung/hystrix/HystrixController.java +++ b/hystrix/src/main/java/com/baeldung/hystrix/HystrixController.java @@ -10,8 +10,13 @@ public class HystrixController { @Autowired private SpringExistingClient client; - @RequestMapping("/") - public String index() throws InterruptedException{ - return client.invokeRemoteService(); + @RequestMapping("/withHystrix") + public String withHystrix() throws InterruptedException{ + return client.invokeRemoteServiceWithHystrix(); + } + + @RequestMapping("/withOutHystrix") + public String withOutHystrix() throws InterruptedException{ + return client.invokeRemoteServiceWithOutHystrix(); } } diff --git a/hystrix/src/main/java/com/baeldung/hystrix/SpringExistingClient.java b/hystrix/src/main/java/com/baeldung/hystrix/SpringExistingClient.java index fab8e611d4..525c7b4785 100644 --- a/hystrix/src/main/java/com/baeldung/hystrix/SpringExistingClient.java +++ b/hystrix/src/main/java/com/baeldung/hystrix/SpringExistingClient.java @@ -10,8 +10,11 @@ public class SpringExistingClient { private int remoteServiceDelay; @HystrixCircuitBreaker - public String invokeRemoteService() throws InterruptedException{ + public String invokeRemoteServiceWithHystrix() throws InterruptedException{ return new RemoteServiceTestSimulator(remoteServiceDelay).execute(); } + public String invokeRemoteServiceWithOutHystrix() throws InterruptedException{ + return new RemoteServiceTestSimulator(remoteServiceDelay).execute(); + } } diff --git a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java index bea89248e4..a193904976 100644 --- a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java +++ b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java @@ -5,10 +5,9 @@ import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixThreadPoolProperties; import com.netflix.hystrix.exception.HystrixRuntimeException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.*; import org.junit.rules.ExpectedException; +import org.junit.runners.MethodSorters; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -130,5 +129,4 @@ public class HystrixTimeoutTest { } return response; } - } diff --git a/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java b/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java index 8f443fc5a4..004314b0ed 100644 --- a/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java +++ b/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java @@ -23,10 +23,14 @@ public class SpringAndHystrixIntegrationTest { public final ExpectedException exception = ExpectedException.none(); @Test - public void givenTimeOutOf15000_whenExistingClientCalled_thenExpectHystrixRuntimeException() throws InterruptedException { + public void givenTimeOutOf15000_whenClientCalledWithHystrix_thenExpectHystrixRuntimeException() throws InterruptedException { exception.expect(HystrixRuntimeException.class); - assertThat(hystrixController.index(), equalTo("Success")); + hystrixController.withHystrix(); } + @Test + public void givenTimeOutOf15000_whenClientCalledWithOutHystrix_thenExpectSuccess() throws InterruptedException { + assertThat(hystrixController.withOutHystrix(), equalTo("Success")); + } } diff --git a/pom.xml b/pom.xml index 3f4489fc4c..8b2d0b3ff1 100644 --- a/pom.xml +++ b/pom.xml @@ -17,6 +17,7 @@ apache-cxf apache-fop autovalue-tutorial + cdi core-java core-java-8 couchbase-sdk-intro diff --git a/spring-all/src/main/java/org/baeldung/startup/EventListenerExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/EventListenerExampleBean.java new file mode 100644 index 0000000000..e9cd1a159d --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/EventListenerExampleBean.java @@ -0,0 +1,19 @@ +package org.baeldung.startup; + +import org.apache.log4j.Logger; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +@Component +public class EventListenerExampleBean { + private static final Logger LOG = Logger.getLogger(EventListenerExampleBean.class); + + public static int counter; + + @EventListener + public void onApplicationEvent(ContextRefreshedEvent event) { + LOG.info("Increment counter"); + counter++; + } +} diff --git a/spring-cloud-config/docker/Dockerfile b/spring-cloud-config/docker/Dockerfile new file mode 100644 index 0000000000..bdb37abf80 --- /dev/null +++ b/spring-cloud-config/docker/Dockerfile @@ -0,0 +1,4 @@ +FROM alpine:edge +MAINTAINER baeldung.com +RUN apk add --no-cache openjdk8 +COPY files/UnlimitedJCEPolicyJDK8/* /usr/lib/jvm/java-1.8-openjdk/jre/lib/security/ diff --git a/spring-cloud-config/docker/Dockerfile.client b/spring-cloud-config/docker/Dockerfile.client new file mode 100644 index 0000000000..5fbc0b98c0 --- /dev/null +++ b/spring-cloud-config/docker/Dockerfile.client @@ -0,0 +1,6 @@ +FROM alpine-java:base +MAINTAINER baeldung.com +RUN apk --no-cache add netcat-openbsd +COPY files/config-client.jar /opt/spring-cloud/lib/ +COPY files/config-client-entrypoint.sh /opt/spring-cloud/bin/ +RUN chmod 755 /opt/spring-cloud/bin/config-client-entrypoint.sh diff --git a/spring-cloud-config/docker/Dockerfile.server b/spring-cloud-config/docker/Dockerfile.server new file mode 100644 index 0000000000..4f7bd751e8 --- /dev/null +++ b/spring-cloud-config/docker/Dockerfile.server @@ -0,0 +1,9 @@ +FROM alpine-java:base +MAINTAINER baeldung.com +COPY files/config-server.jar /opt/spring-cloud/lib/ +ENV SPRING_APPLICATION_JSON='{"spring": {"cloud": {"config": {"server": \ + {"git": {"uri": "/var/lib/spring-cloud/config-repo", "clone-on-start": true}}}}}}' +ENTRYPOINT ["/usr/bin/java"] +CMD ["-jar", "/opt/spring-cloud/lib/config-server.jar"] +VOLUME /var/lib/spring-cloud/config-repo +EXPOSE 8888 diff --git a/spring-cloud-config/docker/config-client-entrypoint.sh b/spring-cloud-config/docker/config-client-entrypoint.sh new file mode 100644 index 0000000000..12352119fa --- /dev/null +++ b/spring-cloud-config/docker/config-client-entrypoint.sh @@ -0,0 +1,8 @@ +#!/bin/sh + +while ! nc -z config-server 8888 ; do + echo "Waiting for upcoming Config Server" + sleep 2 +done + +java -jar /opt/spring-cloud/lib/config-client.jar diff --git a/spring-cloud-config/docker/docker-compose.scale.yml b/spring-cloud-config/docker/docker-compose.scale.yml new file mode 100644 index 0000000000..f74153bea3 --- /dev/null +++ b/spring-cloud-config/docker/docker-compose.scale.yml @@ -0,0 +1,41 @@ +version: '2' +services: + config-server: + build: + context: . + dockerfile: Dockerfile.server + image: config-server:latest + expose: + - 8888 + networks: + - spring-cloud-network + volumes: + - spring-cloud-config-repo:/var/lib/spring-cloud/config-repo + logging: + driver: json-file + config-client: + build: + context: . + dockerfile: Dockerfile.client + image: config-client:latest + entrypoint: /opt/spring-cloud/bin/config-client-entrypoint.sh + environment: + SPRING_APPLICATION_JSON: '{"spring": {"cloud": {"config": {"uri": "http://config-server:8888"}}}}' + expose: + - 8080 + ports: + - 8080 + networks: + - spring-cloud-network + links: + - config-server:config-server + depends_on: + - config-server + logging: + driver: json-file +networks: + spring-cloud-network: + driver: bridge +volumes: + spring-cloud-config-repo: + external: true diff --git a/spring-cloud-config/docker/docker-compose.yml b/spring-cloud-config/docker/docker-compose.yml new file mode 100644 index 0000000000..74c71b651c --- /dev/null +++ b/spring-cloud-config/docker/docker-compose.yml @@ -0,0 +1,43 @@ +version: '2' +services: + config-server: + container_name: config-server + build: + context: . + dockerfile: Dockerfile.server + image: config-server:latest + expose: + - 8888 + networks: + - spring-cloud-network + volumes: + - spring-cloud-config-repo:/var/lib/spring-cloud/config-repo + logging: + driver: json-file + config-client: + container_name: config-client + build: + context: . + dockerfile: Dockerfile.client + image: config-client:latest + entrypoint: /opt/spring-cloud/bin/config-client-entrypoint.sh + environment: + SPRING_APPLICATION_JSON: '{"spring": {"cloud": {"config": {"uri": "http://config-server:8888"}}}}' + expose: + - 8080 + ports: + - 8080:8080 + networks: + - spring-cloud-network + links: + - config-server:config-server + depends_on: + - config-server + logging: + driver: json-file +networks: + spring-cloud-network: + driver: bridge +volumes: + spring-cloud-config-repo: + external: true diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java index 91388b107b..ec8dc32200 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java @@ -1,82 +1,58 @@ package com.baeldung.hibernate.fetching.model; +import javax.persistence.*; import java.io.Serializable; import java.sql.Date; -public class OrderDetail implements Serializable { +@Entity +@Table (name = "USER_ORDER") +public class OrderDetail implements Serializable{ - private static final long serialVersionUID = 1L; - private Long orderId; - private Date orderDate; - private String orderDesc; - private User user; - - public OrderDetail() { - - } - - public OrderDetail(Date orderDate, String orderDesc) { - super(); - this.orderDate = orderDate; - this.orderDesc = orderDesc; - } - - public Date getOrderDate() { - return orderDate; - } - - public void setOrderDate(Date orderDate) { - this.orderDate = orderDate; - } - - public String getOrderDesc() { - return orderDesc; - } - - public void setOrderDesc(String orderDesc) { - this.orderDesc = orderDesc; - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((orderId == null) ? 0 : orderId.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - OrderDetail other = (OrderDetail) obj; - if (orderId == null) { - if (other.orderId != null) - return false; - } else if (!orderId.equals(other.orderId)) - return false; - - return true; - } - - public Long getOrderId() { - return orderId; - } - - public void setOrderId(Long orderId) { - this.orderId = orderId; - } + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue + @Column(name="ORDER_ID") + private Long orderId; + + public OrderDetail(){ + } + + public OrderDetail(Date orderDate, String orderDesc) { + super(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((orderId == null) ? 0 : orderId.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + OrderDetail other = (OrderDetail) obj; + if (orderId == null) { + if (other.orderId != null) + return false; + } else if (!orderId.equals(other.orderId)) + return false; + + return true; + } + public Long getOrderId() { + return orderId; + } + public void setOrderId(Long orderId) { + this.orderId = orderId; + } } + + diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.java deleted file mode 100644 index 158855f93e..0000000000 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.baeldung.hibernate.fetching.model; - -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; - -public class User implements Serializable { - - private static final long serialVersionUID = 1L; - private Long userId; - private String userName; - private String firstName; - private String lastName; - private Set orderDetail = new HashSet(); - - public User() { - } - - public User(final Long userId, final String userName, final String firstName, final String lastName) { - super(); - this.userId = userId; - this.userName = userName; - this.firstName = firstName; - this.lastName = lastName; - - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((userId == null) ? 0 : userId.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final User other = (User) obj; - if (userId == null) { - if (other.userId != null) - return false; - } else if (!userId.equals(other.userId)) - return false; - return true; - } - - public Long getUserId() { - return userId; - } - - public void setUserId(final Long userId) { - this.userId = userId; - } - - public String getUserName() { - return userName; - } - - public void setUserName(final String userName) { - this.userName = userName; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(final String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(final String lastName) { - this.lastName = lastName; - } - - public Set getOrderDetail() { - return orderDetail; - } - - public void setOrderDetail(Set orderDetail) { - this.orderDetail = orderDetail; - } - - -} diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java new file mode 100644 index 0000000000..22b4fdc76c --- /dev/null +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java @@ -0,0 +1,71 @@ +package com.baeldung.hibernate.fetching.model; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +@Entity +@Table (name = "USER") +public class UserEager implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue + @Column(name="USER_ID") + private Long userId; + + @OneToMany(fetch = FetchType.EAGER, mappedBy = "user") + private Set orderDetail = new HashSet(); + + public UserEager() { + } + + public UserEager(final Long userId) { + super(); + this.userId = userId; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final UserEager other = (UserEager) obj; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + return true; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(final Long userId) { + this.userId = userId; + } + + public Set getOrderDetail() { + return orderDetail; + } + + public void setOrderDetail(Set orderDetail) { + this.orderDetail = orderDetail; + } + +} diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java new file mode 100644 index 0000000000..5038fb90ef --- /dev/null +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java @@ -0,0 +1,72 @@ +package com.baeldung.hibernate.fetching.model; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +@Entity +@Table (name = "USER") +public class UserLazy implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue + @Column(name="USER_ID") + private Long userId; + + @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") + private Set orderDetail = new HashSet(); + + public UserLazy() { + } + + public UserLazy(final Long userId) { + super(); + this.userId = userId; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final UserLazy other = (UserLazy) obj; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + return true; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(final Long userId) { + this.userId = userId; + } + + + public Set getOrderDetail() { + return orderDetail; + } + + public void setOrderDetail(Set orderDetail) { + this.orderDetail = orderDetail; + } + +} diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java index 65ecea2fa4..bbd7729232 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java @@ -1,24 +1,26 @@ package com.baeldung.hibernate.fetching.util; import org.hibernate.Session; +import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { - @SuppressWarnings("deprecation") - public static Session getHibernateSession(String fetchMethod) { - //two config files are there - //one with lazy loading enabled - //another lazy = false - - final String configFileName = "lazy".equals(fetchMethod) ? - "fetchingLazy.cfg.xml" : - "fetching.cfg.xml"; - - return new Configuration() - .configure(configFileName) - .buildSessionFactory().openSession(); - } + @SuppressWarnings("deprecation") + public static Session getHibernateSession(String fetchMethod) { + //two config files are there + //one with lazy loading enabled + //another lazy = false + SessionFactory sf; + if ("lazy".equals(fetchMethod)) { + sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory(); + } else { + sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); + } + + // fetching.cfg.xml is used for this example + return sf.openSession(); + } public static Session getHibernateSession() { return new Configuration() diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java index 90fd302968..1a5142c5c2 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java @@ -1,20 +1,14 @@ package com.baeldung.hibernate.fetching.view; -import java.sql.Date; -import java.util.List; -import java.util.Set; - -import org.hibernate.Hibernate; +import com.baeldung.hibernate.fetching.model.OrderDetail; +import com.baeldung.hibernate.fetching.model.UserEager; +import com.baeldung.hibernate.fetching.model.UserLazy; +import com.baeldung.hibernate.fetching.util.HibernateUtil; import org.hibernate.Session; import org.hibernate.Transaction; - -import com.baeldung.hibernate.fetching.util.HibernateUtil; - -import com.baeldung.hibernate.fetching.model.OrderDetail; - -import com.baeldung.hibernate.fetching.model.User; - +import java.util.List; +import java.util.Set; public class FetchingAppView { @@ -22,52 +16,37 @@ public class FetchingAppView { } - public boolean lazyLoaded() { + // lazily loaded + public Set lazyLoaded() { final Session sessionLazy = HibernateUtil.getHibernateSession("lazy"); - List users = sessionLazy.createQuery("From User").list(); - User userLazyLoaded = users.get(3); - //since data is lazyloaded so data won't be initialized - Set orderDetailSet = userLazyLoaded.getOrderDetail(); - - return (Hibernate.isInitialized(orderDetailSet)); + List users = sessionLazy.createQuery("From UserLazy").list(); + UserLazy userLazyLoaded = users.get(3); + // since data is lazyloaded so data won't be initialized + return (userLazyLoaded.getOrderDetail()); } - public boolean eagerLoaded() { + // eagerly loaded + public Set eagerLoaded() { final Session sessionEager = HibernateUtil.getHibernateSession(); - //data should be loaded in the following line - //also note the queries generated - List users = sessionEager.createQuery("From User").list(); - User userEagerLoaded = users.get(3); - Set orderDetailSet = userEagerLoaded.getOrderDetail(); - - return (Hibernate.isInitialized(orderDetailSet)); + // data should be loaded in the following line + // also note the queries generated + List user = sessionEager.createQuery("From UserEager").list(); + UserEager userEagerLoaded = user.get(3); + return userEagerLoaded.getOrderDetail(); } - - //creates test data - //call this method to create the data in the database + // creates test data + // call this method to create the data in the database public void createTestData() { - final Session session = HibernateUtil.getHibernateSession(); + final Session session = HibernateUtil.getHibernateSession("lazy"); Transaction tx = session.beginTransaction(); + final UserLazy user1 = new UserLazy(); + final UserLazy user2 = new UserLazy(); + final UserLazy user3 = new UserLazy(); - final User user1 = new User(); - final User user2 = new User(); - final User user3 = new User(); - - user1.setFirstName("Priyam"); - user1.setLastName("Banerjee"); - user1.setUserName("priyambanerjee"); session.save(user1); - - user2.setFirstName("Navneeta"); - user2.setLastName("Mukherjee"); - user2.setUserName("nmukh"); session.save(user2); - - user3.setFirstName("Molly"); - user3.setLastName("Banerjee"); - user3.setUserName("mollyb"); session.save(user3); final OrderDetail order1 = new OrderDetail(); @@ -76,35 +55,14 @@ public class FetchingAppView { final OrderDetail order4 = new OrderDetail(); final OrderDetail order5 = new OrderDetail(); - order1.setOrderDesc("First Order"); - order1.setOrderDate(new Date(2014, 10, 12)); - order1.setUser(user1); - - order2.setOrderDesc("Second Order"); - order2.setOrderDate(new Date(2016, 10, 25)); - order2.setUser(user1); - - order3.setOrderDesc("Third Order"); - order3.setOrderDate(new Date(2015, 2, 17)); - order3.setUser(user2); - - order4.setOrderDesc("Fourth Order"); - order4.setOrderDate(new Date(2014, 10, 1)); - order4.setUser(user2); - - order5.setOrderDesc("Fifth Order"); - order5.setOrderDate(new Date(2014, 9, 11)); - order5.setUser(user3); - - session.saveOrUpdate(order1); session.saveOrUpdate(order2); session.saveOrUpdate(order3); session.saveOrUpdate(order4); session.saveOrUpdate(order5); - // session.saveOrUpdate(user1); tx.commit(); session.close(); + } } diff --git a/spring-hibernate4/src/main/resources/fetching.cfg.xml b/spring-hibernate4/src/main/resources/fetching.cfg.xml index 4a7e574dda..1b9a4a191c 100644 --- a/spring-hibernate4/src/main/resources/fetching.cfg.xml +++ b/spring-hibernate4/src/main/resources/fetching.cfg.xml @@ -11,7 +11,10 @@ iamtheking org.hibernate.dialect.MySQLDialect true - - + validate + + + + \ No newline at end of file diff --git a/spring-hibernate4/src/main/resources/fetchingLazy.cfg.xml b/spring-hibernate4/src/main/resources/fetchingLazy.cfg.xml index 1f9a7df94e..c5f608e1a7 100644 --- a/spring-hibernate4/src/main/resources/fetchingLazy.cfg.xml +++ b/spring-hibernate4/src/main/resources/fetchingLazy.cfg.xml @@ -11,7 +11,7 @@ iamtheking org.hibernate.dialect.MySQLDialect true - - + + \ No newline at end of file diff --git a/spring-hibernate4/src/main/resources/fetching_create_queries.sql b/spring-hibernate4/src/main/resources/fetching_create_queries.sql index 11a4239e0d..b36d9828f1 100644 --- a/spring-hibernate4/src/main/resources/fetching_create_queries.sql +++ b/spring-hibernate4/src/main/resources/fetching_create_queries.sql @@ -1,17 +1,12 @@ CREATE TABLE `user` ( `user_id` int(10) NOT NULL AUTO_INCREMENT, - `USERNAME` varchar(100) DEFAULT NULL, - `FIRST_NAME` varchar(255) NOT NULL, - `LAST_NAME` varchar(255) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1 ; CREATE TABLE `user_order` ( `ORDER_ID` int(10) NOT NULL AUTO_INCREMENT, - `ORDER_DATE` date DEFAULT NULL, `USER_ID` int(10) NOT NULL DEFAULT '0', - `ORDER_DESC` varchar(1024) DEFAULT NULL, PRIMARY KEY (`ORDER_ID`,`USER_ID`), KEY `USER_ID` (`USER_ID`), CONSTRAINT `user_order_ibfk_1` FOREIGN KEY (`USER_ID`) REFERENCES `USER` (`user_id`) diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java index 94ee8a3c79..a650f8eb37 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java @@ -1,24 +1,43 @@ package com.baeldung.hibernate.fetching; -import static org.junit.Assert.*; - +import com.baeldung.hibernate.fetching.model.OrderDetail; +import com.baeldung.hibernate.fetching.view.FetchingAppView; +import org.hibernate.Hibernate; +import org.junit.Before; import org.junit.Test; -import com.baeldung.hibernate.fetching.view.FetchingAppView; +import java.util.Set; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; public class HibernateFetchingTest { + + //this loads sample data in the database + @Before + public void addFecthingTestData(){ + FetchingAppView fav = new FetchingAppView(); + fav.createTestData(); + } + + //testLazyFetching() tests the lazy loading + //Since it lazily loaded so orderDetalSetLazy won't + //be initialized @Test public void testLazyFetching() { FetchingAppView fav = new FetchingAppView(); - fav.createTestData(); - assertFalse(fav.lazyLoaded()); + Set orderDetalSetLazy = fav.lazyLoaded(); + assertFalse(Hibernate.isInitialized(orderDetalSetLazy)); } - + + //testEagerFetching() tests the eager loading + //Since it eagerly loaded so orderDetalSetLazy would + //be initialized @Test public void testEagerFetching() { FetchingAppView fav = new FetchingAppView(); - assertTrue(fav.eagerLoaded()); + Set orderDetalSetEager = fav.eagerLoaded(); + assertTrue(Hibernate.isInitialized(orderDetalSetEager)); } - } diff --git a/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml b/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml deleted file mode 100644 index e0b6516b47..0000000000 --- a/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/User.hbm.xml b/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/User.hbm.xml deleted file mode 100644 index 88882b973e..0000000000 --- a/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/User.hbm.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml b/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml deleted file mode 100644 index 2f941fe8b0..0000000000 --- a/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-hibernate4/src/test/resources/fetching.cfg.xml b/spring-hibernate4/src/test/resources/fetching.cfg.xml index 4a7e574dda..acee7008ba 100644 --- a/spring-hibernate4/src/test/resources/fetching.cfg.xml +++ b/spring-hibernate4/src/test/resources/fetching.cfg.xml @@ -11,7 +11,8 @@ iamtheking org.hibernate.dialect.MySQLDialect true - - + + + \ No newline at end of file diff --git a/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml b/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml index 1f9a7df94e..1dc37d0cf8 100644 --- a/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml +++ b/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml @@ -11,7 +11,8 @@ iamtheking org.hibernate.dialect.MySQLDialect true - - + + + \ No newline at end of file diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTest.java new file mode 100644 index 0000000000..c1e79a2a63 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTest.java @@ -0,0 +1,42 @@ +package com.baeldung.web.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.spring.web.config.WebConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = WebConfig.class) +public class EmployeeTest { + + @Autowired + private WebApplicationContext webAppContext; + private MockMvc mockMvc; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build(); + } + + @Test + public void whenEmployeeGETisPerformed_thenRetrievedStatusAndViewNameAndAttributeAreCorrect() throws Exception { + mockMvc.perform(get("/employee")).andExpect(status().isOk()).andExpect(view().name("employeeHome")).andExpect(model().attributeExists("employee")).andDo(print()); + } +} diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index bc415d0455..77b11f1cb1 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -248,11 +248,11 @@ test - - org.hamcrest - hamcrest-core - test - + + + + + org.hamcrest hamcrest-library diff --git a/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java b/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java index af1c103739..d4616dd5a6 100644 --- a/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java +++ b/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java @@ -1,5 +1,7 @@ package com.baeldung.spring.security.x509; +import java.security.Principal; + import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetails; @@ -7,8 +9,6 @@ import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; -import java.security.Principal; - @Controller public class UserController { @PreAuthorize("hasAuthority('ROLE_USER')") diff --git a/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java b/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java index edcacfda15..b99c242408 100644 --- a/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java +++ b/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java @@ -2,21 +2,15 @@ package com.baeldung.spring.security.x509; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -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.core.authority.AuthorityUtils; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; @SpringBootApplication @EnableWebSecurity public class X509AuthenticationServer extends WebSecurityConfigurerAdapter { + public static void main(String[] args) { SpringApplication.run(X509AuthenticationServer.class, args); } + } diff --git a/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java b/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java index af1c103739..d4616dd5a6 100644 --- a/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java +++ b/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java @@ -1,5 +1,7 @@ package com.baeldung.spring.security.x509; +import java.security.Principal; + import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetails; @@ -7,8 +9,6 @@ import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; -import java.security.Principal; - @Controller public class UserController { @PreAuthorize("hasAuthority('ROLE_USER')") diff --git a/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java b/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java index 7d8413589e..050423238e 100644 --- a/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java +++ b/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java @@ -23,9 +23,7 @@ public class X509AuthenticationServer extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().anyRequest().authenticated() - .and() - .x509().subjectPrincipalRegex("CN=(.*?)(?:,|$)").userDetailsService(userDetailsService()); + http.authorizeRequests().anyRequest().authenticated().and().x509().subjectPrincipalRegex("CN=(.*?)(?:,|$)").userDetailsService(userDetailsService()); } @Bean