Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
+13
@@ -1,11 +1,18 @@
|
||||
package com.baeldung.concurrent.executorservice;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
public class DelayedCallable implements Callable<String> {
|
||||
|
||||
private String name;
|
||||
private long period;
|
||||
private CountDownLatch latch;
|
||||
|
||||
public DelayedCallable(String name, long period, CountDownLatch latch) {
|
||||
this(name, period);
|
||||
this.latch = latch;
|
||||
}
|
||||
|
||||
public DelayedCallable(String name, long period) {
|
||||
this.name = name;
|
||||
@@ -16,9 +23,15 @@ public class DelayedCallable implements Callable<String> {
|
||||
|
||||
try {
|
||||
Thread.sleep(period);
|
||||
|
||||
if (latch != null) {
|
||||
latch.countDown();
|
||||
}
|
||||
|
||||
} catch (InterruptedException ex) {
|
||||
// handle exception
|
||||
ex.printStackTrace();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
|
||||
return name;
|
||||
|
||||
+78
-10
@@ -9,22 +9,91 @@ import java.util.List;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
import static junit.framework.TestCase.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class WaitingForThreadsToFinishTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(WaitingForThreadsToFinishTest.class);
|
||||
private final static ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
|
||||
|
||||
public void awaitTerminationAfterShutdown(ExecutorService threadPool) {
|
||||
threadPool.shutdown();
|
||||
try {
|
||||
if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {
|
||||
threadPool.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException ex) {
|
||||
threadPool.shutdownNow();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleThreads_whenUsingCountDownLatch_thenMainShoudWaitForAllToFinish() {
|
||||
|
||||
ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
|
||||
|
||||
try {
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
// create a CountDownLatch that waits for the 2 threads to finish
|
||||
CountDownLatch latch = new CountDownLatch(2);
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
WORKER_THREAD_POOL.submit(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
latch.countDown();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// wait for the latch to be decremented by the two threads
|
||||
latch.await();
|
||||
|
||||
long processingTime = System.currentTimeMillis() - startTime;
|
||||
assertTrue(processingTime >= 1000);
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleThreads_whenInvokeAll_thenMainThreadShouldWaitForAllToFinish() {
|
||||
|
||||
ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
|
||||
|
||||
List<Callable<String>> callables = Arrays.asList(new DelayedCallable("fast thread", 100), new DelayedCallable("slow thread", 3000));
|
||||
|
||||
List<Callable<String>> callables = Arrays.asList(
|
||||
new DelayedCallable("fast thread", 100),
|
||||
new DelayedCallable("slow thread", 3000));
|
||||
|
||||
try {
|
||||
long startProcessingTime = System.currentTimeMillis();
|
||||
List<Future<String>> futures = WORKER_THREAD_POOL.invokeAll(callables);
|
||||
|
||||
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
||||
|
||||
try {
|
||||
WORKER_THREAD_POOL.submit(new Callable<String>() {
|
||||
@Override
|
||||
public String call() throws Exception {
|
||||
fail("This thread should have been rejected !");
|
||||
Thread.sleep(1000000);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
} catch (RejectedExecutionException ex) {
|
||||
//
|
||||
}
|
||||
|
||||
long totalProcessingTime = System.currentTimeMillis() - startProcessingTime;
|
||||
assertTrue(totalProcessingTime >= 3000);
|
||||
@@ -39,9 +108,7 @@ public class WaitingForThreadsToFinishTest {
|
||||
|
||||
} catch (ExecutionException | InterruptedException ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
|
||||
WORKER_THREAD_POOL.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -49,14 +116,14 @@ public class WaitingForThreadsToFinishTest {
|
||||
|
||||
CompletionService<String> service = new ExecutorCompletionService<>(WORKER_THREAD_POOL);
|
||||
|
||||
List<Callable<String>> callables = Arrays.asList(new DelayedCallable("fast thread", 100), new DelayedCallable("slow thread", 3000));
|
||||
List<Callable<String>> callables = Arrays.asList(
|
||||
new DelayedCallable("fast thread", 100),
|
||||
new DelayedCallable("slow thread", 3000));
|
||||
|
||||
for (Callable<String> callable : callables) {
|
||||
service.submit(callable);
|
||||
}
|
||||
|
||||
WORKER_THREAD_POOL.shutdown();
|
||||
|
||||
try {
|
||||
|
||||
long startProcessingTime = System.currentTimeMillis();
|
||||
@@ -79,8 +146,9 @@ public class WaitingForThreadsToFinishTest {
|
||||
|
||||
} catch (ExecutionException | InterruptedException ex) {
|
||||
ex.printStackTrace();
|
||||
} finally {
|
||||
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -142,6 +210,6 @@ public class WaitingForThreadsToFinishTest {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
WORKER_THREAD_POOL.shutdown();
|
||||
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -249,7 +249,7 @@
|
||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
<testFailureIgnore>true</testFailureIgnore>
|
||||
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
|
||||
@@ -15,5 +15,6 @@
|
||||
- [Data Classes in Kotlin](http://www.baeldung.com/kotlin-data-classes)
|
||||
- [Delegated Properties in Kotlin](http://www.baeldung.com/kotlin-delegated-properties)
|
||||
- [Sealed Classes in Kotlin](http://www.baeldung.com/kotlin-sealed-classes)
|
||||
- [JUnit 5 for Kotlin Developers](http://www.baeldung.com/junit-5-kotlin)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
## Building
|
||||
|
||||
To build the module, use Maven's `package` goal:
|
||||
|
||||
```
|
||||
mvn clean package
|
||||
```
|
||||
|
||||
## Running
|
||||
|
||||
To run the application, use Spring Boot's `run` goal:
|
||||
|
||||
```
|
||||
mvn spring-boot:run
|
||||
```
|
||||
|
||||
The application will be accessible at [http://localhost:8080/](http://localhost:8080/)
|
||||
@@ -3,6 +3,7 @@ package com.baeldung.hibernate;
|
||||
import com.baeldung.hibernate.pojo.Employee;
|
||||
import com.baeldung.hibernate.pojo.EntityDescription;
|
||||
import com.baeldung.hibernate.pojo.Phone;
|
||||
import com.baeldung.hibernate.pojo.TemporalValues;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.Metadata;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
@@ -31,6 +32,7 @@ public class HibernateUtil {
|
||||
metadataSources.addAnnotatedClass(Employee.class);
|
||||
metadataSources.addAnnotatedClass(Phone.class);
|
||||
metadataSources.addAnnotatedClass(EntityDescription.class);
|
||||
metadataSources.addAnnotatedClass(TemporalValues.class);
|
||||
|
||||
Metadata metadata = metadataSources.buildMetadata();
|
||||
return metadata.getSessionFactoryBuilder()
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
import java.sql.Date;
|
||||
import java.sql.Time;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.*;
|
||||
import java.util.Calendar;
|
||||
|
||||
@Entity
|
||||
public class TemporalValues implements Serializable {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private long id;
|
||||
|
||||
@Basic
|
||||
private java.sql.Date sqlDate;
|
||||
|
||||
@Basic
|
||||
private java.sql.Time sqlTime;
|
||||
|
||||
@Basic
|
||||
private java.sql.Timestamp sqlTimestamp;
|
||||
|
||||
@Basic
|
||||
@Temporal(TemporalType.DATE)
|
||||
private java.util.Date utilDate;
|
||||
|
||||
@Basic
|
||||
@Temporal(TemporalType.TIME)
|
||||
private java.util.Date utilTime;
|
||||
|
||||
@Basic
|
||||
@Temporal(TemporalType.TIMESTAMP)
|
||||
private java.util.Date utilTimestamp;
|
||||
|
||||
@Basic
|
||||
@Temporal(TemporalType.DATE)
|
||||
private java.util.Calendar calendarDate;
|
||||
|
||||
@Basic
|
||||
@Temporal(TemporalType.TIMESTAMP)
|
||||
private java.util.Calendar calendarTimestamp;
|
||||
|
||||
@Basic
|
||||
private java.time.LocalDate localDate;
|
||||
|
||||
@Basic
|
||||
private java.time.LocalTime localTime;
|
||||
|
||||
@Basic
|
||||
private java.time.OffsetTime offsetTime;
|
||||
|
||||
@Basic
|
||||
private java.time.Instant instant;
|
||||
|
||||
@Basic
|
||||
private java.time.LocalDateTime localDateTime;
|
||||
|
||||
@Basic
|
||||
private java.time.OffsetDateTime offsetDateTime;
|
||||
|
||||
@Basic
|
||||
private java.time.ZonedDateTime zonedDateTime;
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Date getSqlDate() {
|
||||
return sqlDate;
|
||||
}
|
||||
|
||||
public void setSqlDate(Date sqlDate) {
|
||||
this.sqlDate = sqlDate;
|
||||
}
|
||||
|
||||
public Time getSqlTime() {
|
||||
return sqlTime;
|
||||
}
|
||||
|
||||
public void setSqlTime(Time sqlTime) {
|
||||
this.sqlTime = sqlTime;
|
||||
}
|
||||
|
||||
public Timestamp getSqlTimestamp() {
|
||||
return sqlTimestamp;
|
||||
}
|
||||
|
||||
public void setSqlTimestamp(Timestamp sqlTimestamp) {
|
||||
this.sqlTimestamp = sqlTimestamp;
|
||||
}
|
||||
|
||||
public java.util.Date getUtilDate() {
|
||||
return utilDate;
|
||||
}
|
||||
|
||||
public void setUtilDate(java.util.Date utilDate) {
|
||||
this.utilDate = utilDate;
|
||||
}
|
||||
|
||||
public java.util.Date getUtilTime() {
|
||||
return utilTime;
|
||||
}
|
||||
|
||||
public void setUtilTime(java.util.Date utilTime) {
|
||||
this.utilTime = utilTime;
|
||||
}
|
||||
|
||||
public java.util.Date getUtilTimestamp() {
|
||||
return utilTimestamp;
|
||||
}
|
||||
|
||||
public void setUtilTimestamp(java.util.Date utilTimestamp) {
|
||||
this.utilTimestamp = utilTimestamp;
|
||||
}
|
||||
|
||||
public Calendar getCalendarDate() {
|
||||
return calendarDate;
|
||||
}
|
||||
|
||||
public void setCalendarDate(Calendar calendarDate) {
|
||||
this.calendarDate = calendarDate;
|
||||
}
|
||||
|
||||
public Calendar getCalendarTimestamp() {
|
||||
return calendarTimestamp;
|
||||
}
|
||||
|
||||
public void setCalendarTimestamp(Calendar calendarTimestamp) {
|
||||
this.calendarTimestamp = calendarTimestamp;
|
||||
}
|
||||
|
||||
public LocalDate getLocalDate() {
|
||||
return localDate;
|
||||
}
|
||||
|
||||
public void setLocalDate(LocalDate localDate) {
|
||||
this.localDate = localDate;
|
||||
}
|
||||
|
||||
public LocalTime getLocalTime() {
|
||||
return localTime;
|
||||
}
|
||||
|
||||
public void setLocalTime(LocalTime localTime) {
|
||||
this.localTime = localTime;
|
||||
}
|
||||
|
||||
public OffsetTime getOffsetTime() {
|
||||
return offsetTime;
|
||||
}
|
||||
|
||||
public void setOffsetTime(OffsetTime offsetTime) {
|
||||
this.offsetTime = offsetTime;
|
||||
}
|
||||
|
||||
public Instant getInstant() {
|
||||
return instant;
|
||||
}
|
||||
|
||||
public void setInstant(Instant instant) {
|
||||
this.instant = instant;
|
||||
}
|
||||
|
||||
public LocalDateTime getLocalDateTime() {
|
||||
return localDateTime;
|
||||
}
|
||||
|
||||
public void setLocalDateTime(LocalDateTime localDateTime) {
|
||||
this.localDateTime = localDateTime;
|
||||
}
|
||||
|
||||
public OffsetDateTime getOffsetDateTime() {
|
||||
return offsetDateTime;
|
||||
}
|
||||
|
||||
public void setOffsetDateTime(OffsetDateTime offsetDateTime) {
|
||||
this.offsetDateTime = offsetDateTime;
|
||||
}
|
||||
|
||||
public ZonedDateTime getZonedDateTime() {
|
||||
return zonedDateTime;
|
||||
}
|
||||
|
||||
public void setZonedDateTime(ZonedDateTime zonedDateTime) {
|
||||
this.zonedDateTime = zonedDateTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package com.baeldung.hibernate;
|
||||
|
||||
import com.baeldung.hibernate.pojo.TemporalValues;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.Transaction;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.*;
|
||||
import java.util.Calendar;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TemporalValuesTest {
|
||||
|
||||
private Session session;
|
||||
|
||||
private Transaction transaction;
|
||||
|
||||
@Before
|
||||
public void setUp() throws IOException {
|
||||
session = HibernateUtil.getSessionFactory().withOptions()
|
||||
.jdbcTimeZone(TimeZone.getTimeZone("UTC"))
|
||||
.openSession();
|
||||
transaction = session.beginTransaction();
|
||||
session.createNativeQuery("delete from temporalvalues").executeUpdate();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
transaction.rollback();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEntity_whenMappingSqlTypes_thenTemporalIsSelectedAutomatically() {
|
||||
TemporalValues temporalValues = new TemporalValues();
|
||||
temporalValues.setSqlDate(java.sql.Date.valueOf("2017-11-15"));
|
||||
temporalValues.setSqlTime(java.sql.Time.valueOf("15:30:14"));
|
||||
temporalValues.setSqlTimestamp(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332"));
|
||||
|
||||
session.save(temporalValues);
|
||||
session.flush();
|
||||
session.clear();
|
||||
|
||||
temporalValues = session.get(TemporalValues.class, temporalValues.getId());
|
||||
assertThat(temporalValues.getSqlDate()).isEqualTo(java.sql.Date.valueOf("2017-11-15"));
|
||||
assertThat(temporalValues.getSqlTime()).isEqualTo(java.sql.Time.valueOf("15:30:14"));
|
||||
assertThat(temporalValues.getSqlTimestamp()).isEqualTo(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEntity_whenMappingUtilDateType_thenTemporalIsSpecifiedExplicitly() throws Exception {
|
||||
TemporalValues temporalValues = new TemporalValues();
|
||||
temporalValues.setUtilDate(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15"));
|
||||
temporalValues.setUtilTime(new SimpleDateFormat("HH:mm:ss").parse("15:30:14"));
|
||||
temporalValues.setUtilTimestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.332"));
|
||||
|
||||
session.save(temporalValues);
|
||||
session.flush();
|
||||
session.clear();
|
||||
|
||||
temporalValues = session.get(TemporalValues.class, temporalValues.getId());
|
||||
assertThat(temporalValues.getUtilDate()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15"));
|
||||
assertThat(temporalValues.getUtilTime()).isEqualTo(new SimpleDateFormat("HH:mm:ss").parse("15:30:14"));
|
||||
assertThat(temporalValues.getUtilTimestamp()).isEqualTo(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEntity_whenMappingCalendarType_thenTemporalIsSpecifiedExplicitly() throws Exception {
|
||||
TemporalValues temporalValues = new TemporalValues();
|
||||
|
||||
Calendar calendarDate = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
|
||||
calendarDate.set(Calendar.YEAR, 2017);
|
||||
calendarDate.set(Calendar.MONTH, 10);
|
||||
calendarDate.set(Calendar.DAY_OF_MONTH, 15);
|
||||
temporalValues.setCalendarDate(calendarDate);
|
||||
|
||||
Calendar calendarTimestamp = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
|
||||
calendarTimestamp.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.322"));
|
||||
temporalValues.setCalendarTimestamp(calendarTimestamp);
|
||||
|
||||
session.save(temporalValues);
|
||||
session.flush();
|
||||
session.clear();
|
||||
|
||||
temporalValues = session.get(TemporalValues.class, temporalValues.getId());
|
||||
assertThat(temporalValues.getCalendarDate().getTime()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15"));
|
||||
assertThat(temporalValues.getCalendarTimestamp().getTime()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.322"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEntity_whenMappingJavaTimeTypes_thenTemporalIsSelectedAutomatically() {
|
||||
TemporalValues temporalValues = new TemporalValues();
|
||||
|
||||
temporalValues.setLocalDate(LocalDate.parse("2017-11-15"));
|
||||
temporalValues.setLocalTime(LocalTime.parse("15:30:18"));
|
||||
temporalValues.setOffsetTime(OffsetTime.parse("08:22:12+01:00"));
|
||||
temporalValues.setInstant(Instant.parse("2017-11-15T08:22:12Z"));
|
||||
temporalValues.setLocalDateTime(LocalDateTime.parse("2017-11-15T08:22:12"));
|
||||
temporalValues.setOffsetDateTime(OffsetDateTime.parse("2017-11-15T08:22:12+01:00"));
|
||||
temporalValues.setZonedDateTime(ZonedDateTime.parse("2017-11-15T08:22:12+01:00[Europe/Paris]"));
|
||||
|
||||
session.save(temporalValues);
|
||||
session.flush();
|
||||
session.clear();
|
||||
|
||||
temporalValues = session.get(TemporalValues.class, temporalValues.getId());
|
||||
assertThat(temporalValues.getLocalDate()).isEqualTo(LocalDate.parse("2017-11-15"));
|
||||
assertThat(temporalValues.getLocalTime()).isEqualTo(LocalTime.parse("15:30:18"));
|
||||
assertThat(temporalValues.getOffsetTime()).isEqualTo(OffsetTime.parse("08:22:12+01:00"));
|
||||
assertThat(temporalValues.getInstant()).isEqualTo(Instant.parse("2017-11-15T08:22:12Z"));
|
||||
assertThat(temporalValues.getLocalDateTime()).isEqualTo(LocalDateTime.parse("2017-11-15T08:22:12"));
|
||||
assertThat(temporalValues.getOffsetDateTime()).isEqualTo(OffsetDateTime.parse("2017-11-15T08:22:12+01:00"));
|
||||
assertThat(temporalValues.getZonedDateTime()).isEqualTo(ZonedDateTime.parse("2017-11-15T08:22:12+01:00[Europe/Paris]"));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -29,6 +29,7 @@
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<junit4.version>4.12</junit4.version>
|
||||
<spring.version>5.0.1.RELEASE</spring.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
@@ -111,6 +112,17 @@
|
||||
<version>${junit4.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.junit5.spring;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
|
||||
import com.baeldung.junit5.Greetings;
|
||||
|
||||
@ExtendWith(SpringExtension.class)
|
||||
@ContextConfiguration(classes = { SpringTestConfiguration.class })
|
||||
public class GreetingsSpringTest {
|
||||
|
||||
@Test
|
||||
void whenCallingSayHello_thenReturnHello() {
|
||||
assertTrue("Hello".equals(Greetings.sayHello()));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.junit5.spring;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class SpringTestConfiguration {
|
||||
|
||||
}
|
||||
@@ -51,7 +51,6 @@ public class MemberStatusIntegrationTest {
|
||||
|
||||
/**
|
||||
* This test should fail, comment out <code>@Ignore</code> to see how failed test can be reflected in Serenity report. <br/>
|
||||
* Remember to add <code><testFailureIgnore>true</testFailureIgnore></code> under maven-surefire-plugin configuration.
|
||||
*/
|
||||
@Test
|
||||
@Ignore
|
||||
|
||||
@@ -26,12 +26,6 @@
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>apache-log4j-extras</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--log4j2 dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
|
||||
@@ -85,7 +85,6 @@
|
||||
<exclude>**/JdbcTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
<testFailureIgnore>true</testFailureIgnore>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
|
||||
@@ -63,7 +63,7 @@
|
||||
<exclude>**/JdbcTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
<testFailureIgnore>true</testFailureIgnore>
|
||||
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
|
||||
@@ -65,7 +65,6 @@
|
||||
<exclude>**/*EntryPointsTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
<testFailureIgnore>true</testFailureIgnore>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
|
||||
@@ -256,6 +256,7 @@
|
||||
<module>vertx-and-rxjava</module>
|
||||
<module>saas</module>
|
||||
<module>deeplearning4j</module>
|
||||
<module>spring-boot-admin</module>
|
||||
</modules>
|
||||
|
||||
<dependencies>
|
||||
@@ -338,7 +339,7 @@
|
||||
<exclude>**/JdbcTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
<testFailureIgnore>true</testFailureIgnore>
|
||||
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
|
||||
@@ -27,7 +27,6 @@
|
||||
<includes>
|
||||
<include>**/*LiveTest.java</include>
|
||||
</includes>
|
||||
<testFailureIgnore>false</testFailureIgnore>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
|
||||
@@ -152,7 +152,7 @@
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<testFailureIgnore>true</testFailureIgnore>
|
||||
|
||||
<failIfNoTests>false</failIfNoTests>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
|
||||
@@ -19,9 +19,11 @@
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<start-class>com.example.activitiwithspring.ActivitiWithSpringApplication</start-class>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<activiti.version>6.0.0</activiti.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@@ -30,9 +32,14 @@
|
||||
<artifactId>activiti-spring-boot-starter-basic</artifactId>
|
||||
<version>6.0.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.activiti</groupId>
|
||||
<artifactId>activiti-spring-boot-starter-security</artifactId>
|
||||
<version>${activiti.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -67,7 +74,7 @@
|
||||
<exclude>**/JdbcTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
<testFailureIgnore>true</testFailureIgnore>
|
||||
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.activiti.security.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
public class MvcConfig extends WebMvcConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
public void addViewControllers(ViewControllerRegistry registry) {
|
||||
registry.addViewController("/login")
|
||||
.setViewName("login");
|
||||
registry.addViewController("/homepage")
|
||||
.setViewName("homepage");
|
||||
}
|
||||
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.activiti.security.config;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.activiti.engine.IdentityService;
|
||||
import org.activiti.engine.RuntimeService;
|
||||
import org.activiti.engine.TaskService;
|
||||
import org.activiti.engine.runtime.ProcessInstance;
|
||||
import org.activiti.engine.task.Task;
|
||||
import org.activiti.spring.SpringProcessEngineConfiguration;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class ProcessController {
|
||||
|
||||
@Autowired
|
||||
private RuntimeService runtimeService;
|
||||
|
||||
@Autowired
|
||||
private TaskService taskService;
|
||||
|
||||
@Autowired
|
||||
private IdentityService identityService;
|
||||
|
||||
@Autowired
|
||||
SpringProcessEngineConfiguration config;
|
||||
|
||||
@GetMapping("/protected-process")
|
||||
public String startProcess() {
|
||||
|
||||
String userId = SecurityContextHolder.getContext()
|
||||
.getAuthentication()
|
||||
.getName();
|
||||
|
||||
identityService.setAuthenticatedUserId(userId);
|
||||
|
||||
ProcessInstance pi = runtimeService.startProcessInstanceByKey("protected-process");
|
||||
|
||||
List<Task> usertasks = taskService.createTaskQuery()
|
||||
.processInstanceId(pi.getId())
|
||||
.list();
|
||||
|
||||
taskService.complete(usertasks.iterator()
|
||||
.next()
|
||||
.getId());
|
||||
|
||||
return "Process started. Number of currently running process instances = " + runtimeService.createProcessInstanceQuery()
|
||||
.count();
|
||||
}
|
||||
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package com.baeldung.activiti.security.config;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.activiti.engine.identity.Group;
|
||||
import org.activiti.engine.identity.GroupQuery;
|
||||
import org.activiti.engine.impl.GroupQueryImpl;
|
||||
import org.activiti.engine.impl.Page;
|
||||
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
|
||||
import org.activiti.engine.impl.persistence.entity.GroupEntityImpl;
|
||||
import org.activiti.engine.impl.persistence.entity.GroupEntityManagerImpl;
|
||||
import org.activiti.engine.impl.persistence.entity.data.GroupDataManager;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.provisioning.JdbcUserDetailsManager;
|
||||
|
||||
public class SpringSecurityGroupManager extends GroupEntityManagerImpl {
|
||||
|
||||
private JdbcUserDetailsManager userManager;
|
||||
|
||||
public SpringSecurityGroupManager(ProcessEngineConfigurationImpl processEngineConfiguration, GroupDataManager groupDataManager) {
|
||||
super(processEngineConfiguration, groupDataManager);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Group> findGroupByQueryCriteria(GroupQueryImpl query, Page page) {
|
||||
|
||||
if (query.getUserId() != null) {
|
||||
return findGroupsByUser(query.getUserId());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long findGroupCountByQueryCriteria(GroupQueryImpl query) {
|
||||
return findGroupByQueryCriteria(query, null).size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Group> findGroupsByUser(String userId) {
|
||||
UserDetails userDetails = userManager.loadUserByUsername(userId);
|
||||
System.out.println("group manager");
|
||||
if (userDetails != null) {
|
||||
List<Group> groups = userDetails.getAuthorities()
|
||||
.stream()
|
||||
.map(a -> a.getAuthority())
|
||||
.map(a -> {
|
||||
Group g = new GroupEntityImpl();
|
||||
g.setId(a);
|
||||
return g;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
return groups;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void setUserManager(JdbcUserDetailsManager userManager) {
|
||||
this.userManager = userManager;
|
||||
}
|
||||
|
||||
public Group createNewGroup(String groupId) {
|
||||
throw new UnsupportedOperationException("This operation is not supported!");
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String groupId) {
|
||||
throw new UnsupportedOperationException("This operation is not supported!");
|
||||
|
||||
}
|
||||
|
||||
public GroupQuery createNewGroupQuery() {
|
||||
throw new UnsupportedOperationException("This operation is not supported!");
|
||||
}
|
||||
|
||||
public List<Group> findGroupsByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
|
||||
throw new UnsupportedOperationException("This operation is not supported!");
|
||||
}
|
||||
|
||||
public long findGroupCountByNativeQuery(Map<String, Object> parameterMap) {
|
||||
throw new UnsupportedOperationException("This operation is not supported!");
|
||||
}
|
||||
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
package com.baeldung.activiti.security.config;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.activiti.engine.identity.Group;
|
||||
import org.activiti.engine.identity.User;
|
||||
import org.activiti.engine.identity.UserQuery;
|
||||
import org.activiti.engine.impl.Page;
|
||||
import org.activiti.engine.impl.UserQueryImpl;
|
||||
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
|
||||
import org.activiti.engine.impl.persistence.entity.GroupEntityImpl;
|
||||
import org.activiti.engine.impl.persistence.entity.UserEntity;
|
||||
import org.activiti.engine.impl.persistence.entity.UserEntityImpl;
|
||||
import org.activiti.engine.impl.persistence.entity.UserEntityManagerImpl;
|
||||
import org.activiti.engine.impl.persistence.entity.data.UserDataManager;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.provisioning.JdbcUserDetailsManager;
|
||||
|
||||
public class SpringSecurityUserManager extends UserEntityManagerImpl {
|
||||
|
||||
private JdbcUserDetailsManager userManager;
|
||||
|
||||
public SpringSecurityUserManager(ProcessEngineConfigurationImpl processEngineConfiguration, UserDataManager userDataManager, JdbcUserDetailsManager userManager) {
|
||||
super(processEngineConfiguration, userDataManager);
|
||||
this.userManager = userManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserEntity findById(String userId) {
|
||||
UserDetails userDetails = userManager.loadUserByUsername(userId);
|
||||
if (userDetails != null) {
|
||||
UserEntityImpl user = new UserEntityImpl();
|
||||
user.setId(userId);
|
||||
return user;
|
||||
}
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<User> findUserByQueryCriteria(UserQueryImpl query, Page page) {
|
||||
List<User> users = null;
|
||||
if (query.getGroupId() != null) {
|
||||
users = userManager.findUsersInGroup(query.getGroupId())
|
||||
.stream()
|
||||
.map(username -> {
|
||||
User user = new UserEntityImpl();
|
||||
user.setId(username);
|
||||
return user;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
if (page != null) {
|
||||
return users.subList(page.getFirstResult(), page.getFirstResult() + page.getMaxResults());
|
||||
|
||||
}
|
||||
return users;
|
||||
}
|
||||
|
||||
if (query.getId() != null) {
|
||||
UserDetails userDetails = userManager.loadUserByUsername(query.getId());
|
||||
if (userDetails != null) {
|
||||
UserEntityImpl user = new UserEntityImpl();
|
||||
user.setId(query.getId());
|
||||
return Collections.singletonList(user);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean checkPassword(String userId, String password) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public void setUserManager(JdbcUserDetailsManager userManager) {
|
||||
this.userManager = userManager;
|
||||
}
|
||||
|
||||
public User createNewUser(String userId) {
|
||||
throw new UnsupportedOperationException("This operation is not supported!");
|
||||
}
|
||||
|
||||
public void updateUser(User updatedUser) {
|
||||
throw new UnsupportedOperationException("This operation is not supported!");
|
||||
|
||||
}
|
||||
|
||||
public void delete(UserEntity userEntity) {
|
||||
throw new UnsupportedOperationException("This operation is not supported!");
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deletePicture(User user) {
|
||||
UserEntity userEntity = (UserEntity) user;
|
||||
if (userEntity.getPictureByteArrayRef() != null) {
|
||||
userEntity.getPictureByteArrayRef()
|
||||
.delete();
|
||||
}
|
||||
}
|
||||
|
||||
public void delete(String userId) {
|
||||
throw new UnsupportedOperationException("This operation is not supported!");
|
||||
|
||||
}
|
||||
|
||||
public long findUserCountByQueryCriteria(UserQueryImpl query) {
|
||||
return findUserByQueryCriteria(query, null).size();
|
||||
}
|
||||
|
||||
public List<Group> findGroupsByUser(String userId) {
|
||||
UserDetails userDetails = userManager.loadUserByUsername(userId);
|
||||
if (userDetails != null) {
|
||||
List<Group> groups = userDetails.getAuthorities()
|
||||
.stream()
|
||||
.map(a -> a.getAuthority())
|
||||
.map(a -> {
|
||||
Group g = new GroupEntityImpl();
|
||||
g.setId(a);
|
||||
return g;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
return groups;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public UserQuery createNewUserQuery() {
|
||||
throw new UnsupportedOperationException("This operation is not supported!");
|
||||
}
|
||||
|
||||
public List<User> findUsersByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
|
||||
throw new UnsupportedOperationException("This operation is not supported!");
|
||||
}
|
||||
|
||||
public long findUserCountByNativeQuery(Map<String, Object> parameterMap) {
|
||||
throw new UnsupportedOperationException("This operation is not supported!");
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.activiti.security.withactiviti;
|
||||
|
||||
import org.activiti.engine.IdentityService;
|
||||
import org.activiti.spring.security.IdentityServiceUserDetailsService;
|
||||
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.WebSecurityConfigurerAdapter;
|
||||
|
||||
@Configuration
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.antMatcher("/**")
|
||||
.authorizeRequests()
|
||||
.antMatchers("/protected-process*")
|
||||
.authenticated()
|
||||
.anyRequest()
|
||||
.permitAll()
|
||||
.and()
|
||||
.formLogin()
|
||||
.loginPage("/login")
|
||||
.defaultSuccessUrl("/homepage")
|
||||
.failureUrl("/login?error=true")
|
||||
.and()
|
||||
.csrf()
|
||||
.disable()
|
||||
.logout()
|
||||
.logoutSuccessUrl("/login");
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private IdentityService identityService;
|
||||
|
||||
@Bean
|
||||
public IdentityServiceUserDetailsService userDetailsService() {
|
||||
return new IdentityServiceUserDetailsService(identityService);
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.userDetailsService(userDetailsService());
|
||||
}
|
||||
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.activiti.security.withactiviti;
|
||||
|
||||
import org.activiti.engine.IdentityService;
|
||||
import org.activiti.engine.identity.Group;
|
||||
import org.activiti.engine.identity.User;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
@SpringBootApplication(scanBasePackages = { "com.baeldung.activiti.security.config", "com.baeldung.activiti.security.withactiviti" })
|
||||
public class SpringSecurityActivitiApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringSecurityActivitiApplication.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
InitializingBean usersAndGroupsInitializer(IdentityService identityService) {
|
||||
return new InitializingBean() {
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
User user = identityService.newUser("activiti_user");
|
||||
user.setPassword("pass");
|
||||
identityService.saveUser(user);
|
||||
|
||||
Group group = identityService.newGroup("user");
|
||||
group.setName("ROLE_USER");
|
||||
group.setType("USER");
|
||||
identityService.saveGroup(group);
|
||||
identityService.createMembership(user.getId(), group.getId());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.activiti.security.withspring;
|
||||
|
||||
import org.activiti.engine.impl.persistence.entity.data.impl.MybatisGroupDataManager;
|
||||
import org.activiti.engine.impl.persistence.entity.data.impl.MybatisUserDataManager;
|
||||
import org.activiti.spring.SpringProcessEngineConfiguration;
|
||||
import org.activiti.spring.boot.SecurityAutoConfiguration;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.security.provisioning.JdbcUserDetailsManager;
|
||||
|
||||
import com.baeldung.activiti.security.config.SpringSecurityGroupManager;
|
||||
import com.baeldung.activiti.security.config.SpringSecurityUserManager;
|
||||
|
||||
@SpringBootApplication(exclude = SecurityAutoConfiguration.class, scanBasePackages = { "com.baeldung.activiti.security.config", "com.baeldung.activiti.security.withspring" })
|
||||
public class ActivitiSpringSecurityApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ActivitiSpringSecurityApplication.class, args);
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private SpringProcessEngineConfiguration processEngineConfiguration;
|
||||
|
||||
@Autowired
|
||||
private JdbcUserDetailsManager userManager;
|
||||
|
||||
@Bean
|
||||
InitializingBean processEngineInitializer() {
|
||||
return new InitializingBean() {
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
processEngineConfiguration.setUserEntityManager(new SpringSecurityUserManager(processEngineConfiguration, new MybatisUserDataManager(processEngineConfiguration), userManager));
|
||||
processEngineConfiguration.setGroupEntityManager(new SpringSecurityGroupManager(processEngineConfiguration, new MybatisGroupDataManager(processEngineConfiguration)));
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.activiti.security.withspring;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
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.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.provisioning.JdbcUserDetailsManager;
|
||||
|
||||
@Configuration
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Autowired
|
||||
private DataSource dataSource;
|
||||
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.antMatcher("/**")
|
||||
.authorizeRequests()
|
||||
.antMatchers("/protected-process*")
|
||||
.authenticated()
|
||||
.anyRequest()
|
||||
.permitAll()
|
||||
.and()
|
||||
.formLogin()
|
||||
.loginPage("/login")
|
||||
.defaultSuccessUrl("/homepage")
|
||||
.failureUrl("/login?error=true")
|
||||
.and()
|
||||
.csrf()
|
||||
.disable()
|
||||
.logout()
|
||||
.logoutSuccessUrl("/login");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JdbcUserDetailsManager userDetailsManager() {
|
||||
JdbcUserDetailsManager manager = new JdbcUserDetailsManager();
|
||||
manager.setDataSource(dataSource);
|
||||
return manager;
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.userDetailsService(userDetailsManager());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
insert into users(username, password, enabled) values ('spring_user', 'pass', true);
|
||||
|
||||
insert into authorities(username, authority) values ('spring_user','ROLE_USER');
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user