Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
8acbafdd2d
@ -0,0 +1,119 @@
|
||||
package com.baeldung.java9.language.stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.lang.Integer.*;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StreamFeaturesTest {
|
||||
|
||||
public static class TakeAndDropWhileTest {
|
||||
|
||||
public Stream<String> getStreamAfterTakeWhileOperation() {
|
||||
return Stream
|
||||
.iterate("", s -> s + "s")
|
||||
.takeWhile(s -> s.length() < 10);
|
||||
}
|
||||
|
||||
public Stream<String> getStreamAfterDropWhileOperation() {
|
||||
return Stream
|
||||
.iterate("", s -> s + "s")
|
||||
.takeWhile(s -> s.length() < 10)
|
||||
.dropWhile(s -> !s.contains("sssss"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTakeWhileOperation() {
|
||||
List<String> list = getStreamAfterTakeWhileOperation().collect(Collectors.toList());
|
||||
|
||||
assertEquals(10, list.size());
|
||||
|
||||
assertEquals("", list.get(0));
|
||||
assertEquals("ss", list.get(2));
|
||||
assertEquals("sssssssss", list.get(list.size() - 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDropWhileOperation() {
|
||||
List<String> list = getStreamAfterDropWhileOperation().collect(Collectors.toList());
|
||||
|
||||
assertEquals(5, list.size());
|
||||
|
||||
assertEquals("sssss", list.get(0));
|
||||
assertEquals("sssssss", list.get(2));
|
||||
assertEquals("sssssssss", list.get(list.size() - 1));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class IterateTest {
|
||||
|
||||
private Stream<Integer> getStream() {
|
||||
return Stream.iterate(0, i -> i < 10, i -> i + 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIterateOperation() {
|
||||
List<Integer> list = getStream().collect(Collectors.toList());
|
||||
|
||||
assertEquals(10, list.size());
|
||||
|
||||
assertEquals(valueOf(0), list.get(0));
|
||||
assertEquals(valueOf(5), list.get(5));
|
||||
assertEquals(valueOf(9), list.get(list.size() - 1));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class OfNullableTest {
|
||||
|
||||
private List<String> collection = Arrays.asList("A", "B", "C");
|
||||
private Map<String, Integer> map = new HashMap<>() {{
|
||||
put("A", 10);
|
||||
put("C", 30);
|
||||
}};
|
||||
|
||||
private Stream<Integer> getStreamWithOfNullable() {
|
||||
return collection.stream()
|
||||
.flatMap(s -> Stream.ofNullable(map.get(s)));
|
||||
}
|
||||
|
||||
private Stream<Integer> getStream() {
|
||||
return collection.stream()
|
||||
.flatMap(s -> {
|
||||
Integer temp = map.get(s);
|
||||
return temp != null ? Stream.of(temp) : Stream.empty();
|
||||
});
|
||||
}
|
||||
|
||||
private List<Integer> testOfNullableFrom(Stream<Integer> stream) {
|
||||
List<Integer> list = stream.collect(Collectors.toList());
|
||||
|
||||
assertEquals(2, list.size());
|
||||
|
||||
assertEquals(valueOf(10), list.get(0));
|
||||
assertEquals(valueOf(30), list.get(list.size() - 1));
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOfNullable() {
|
||||
|
||||
assertEquals(
|
||||
testOfNullableFrom(getStream()),
|
||||
testOfNullableFrom(getStreamWithOfNullable())
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
0
core-java/0.12457740242410742
Normal file
0
core-java/0.12457740242410742
Normal file
@ -0,0 +1,60 @@
|
||||
package com.baeldung.java.conversion;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Date;
|
||||
|
||||
import com.baeldung.datetime.UseLocalDateTime;
|
||||
|
||||
public class StringConversion {
|
||||
|
||||
public static int getInt(String str) {
|
||||
return Integer.parseInt(str);
|
||||
}
|
||||
|
||||
public static int getInteger(String str) {
|
||||
return Integer.valueOf(str);
|
||||
}
|
||||
|
||||
public static long getLongPrimitive(String str) {
|
||||
return Long.parseLong(str);
|
||||
}
|
||||
|
||||
public static Long getLong(String str) {
|
||||
return Long.valueOf(str);
|
||||
}
|
||||
|
||||
public static double getDouble(String str) {
|
||||
return Double.parseDouble(str);
|
||||
}
|
||||
|
||||
public static double getDoublePrimitive(String str) {
|
||||
return Double.valueOf(str);
|
||||
}
|
||||
|
||||
public static byte[] getByteArray(String str) {
|
||||
return str.getBytes();
|
||||
}
|
||||
|
||||
public static char[] getCharArray(String str) {
|
||||
return str.toCharArray();
|
||||
}
|
||||
|
||||
public static boolean getBooleanPrimitive(String str) {
|
||||
return Boolean.parseBoolean(str);
|
||||
}
|
||||
|
||||
public static boolean getBoolean(String str) {
|
||||
return Boolean.valueOf(str);
|
||||
}
|
||||
|
||||
public static Date getJava6Date(String str, String format) throws ParseException {
|
||||
SimpleDateFormat formatter = new SimpleDateFormat(format);
|
||||
return formatter.parse(str);
|
||||
}
|
||||
|
||||
public static LocalDateTime getJava8Date(String str) throws ParseException {
|
||||
return new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str);
|
||||
}
|
||||
}
|
23
pdf/pom.xml
23
pdf/pom.xml
@ -24,54 +24,41 @@
|
||||
<version>3.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
|
||||
<dependency>
|
||||
<groupId>org.apache.pdfbox</groupId>
|
||||
<artifactId>pdfbox</artifactId>
|
||||
<version>2.0.3</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox-tools -->
|
||||
<dependency>
|
||||
<groupId>org.apache.pdfbox</groupId>
|
||||
<artifactId>pdfbox-tools</artifactId>
|
||||
<version>2.0.3</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/net.sf.cssbox/pdf2dom -->
|
||||
<dependency>
|
||||
<groupId>net.sf.cssbox</groupId>
|
||||
<artifactId>pdf2dom</artifactId>
|
||||
<version>1.6</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
|
||||
<dependency>
|
||||
<groupId>com.itextpdf</groupId>
|
||||
<artifactId>itextpdf</artifactId>
|
||||
<version>5.5.10</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi</artifactId>
|
||||
<version>3.15</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-ooxml</artifactId>
|
||||
<version>3.15</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-scratchpad</artifactId>
|
||||
<version>3.15</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.xmlgraphics/batik-transcoder -->
|
||||
<dependency>
|
||||
<groupId>org.apache.xmlgraphics</groupId>
|
||||
<artifactId>batik-transcoder</artifactId>
|
||||
<version>1.8</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-ooxml</artifactId>
|
||||
<version>3.15</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -23,17 +23,13 @@ public class PDF2HTMLExample {
|
||||
}
|
||||
|
||||
private static void generateHTMLFromPDF(String filename) throws ParserConfigurationException, IOException {
|
||||
try {
|
||||
PDDocument pdf = PDDocument.load(new File(filename));
|
||||
PDFDomTree parser = new PDFDomTree();
|
||||
Writer output = new PrintWriter("src/output/pdf.html", "utf-8");
|
||||
parser.writeText(pdf, output);
|
||||
output.close();
|
||||
if (pdf != null) {
|
||||
pdf.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
PDDocument pdf = PDDocument.load(new File(filename));
|
||||
PDFDomTree parser = new PDFDomTree();
|
||||
Writer output = new PrintWriter("src/output/pdf.html", "utf-8");
|
||||
parser.writeText(pdf, output);
|
||||
output.close();
|
||||
if (pdf != null) {
|
||||
pdf.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -23,30 +23,26 @@ public class PDF2TextExample {
|
||||
}
|
||||
|
||||
private static void generateTxtFromPDF(String filename) throws IOException {
|
||||
try {
|
||||
File f = new File(filename);
|
||||
String parsedText;
|
||||
PDFParser parser = new PDFParser(new RandomAccessFile(f, "r"));
|
||||
parser.parse();
|
||||
File f = new File(filename);
|
||||
String parsedText;
|
||||
PDFParser parser = new PDFParser(new RandomAccessFile(f, "r"));
|
||||
parser.parse();
|
||||
|
||||
COSDocument cosDoc = parser.getDocument();
|
||||
COSDocument cosDoc = parser.getDocument();
|
||||
|
||||
PDFTextStripper pdfStripper = new PDFTextStripper();
|
||||
PDDocument pdDoc = new PDDocument(cosDoc);
|
||||
PDFTextStripper pdfStripper = new PDFTextStripper();
|
||||
PDDocument pdDoc = new PDDocument(cosDoc);
|
||||
|
||||
parsedText = pdfStripper.getText(pdDoc);
|
||||
parsedText = pdfStripper.getText(pdDoc);
|
||||
|
||||
if (cosDoc != null)
|
||||
cosDoc.close();
|
||||
if (pdDoc != null)
|
||||
pdDoc.close();
|
||||
|
||||
PrintWriter pw = new PrintWriter("src/output/pdf.txt");
|
||||
pw.print(parsedText);
|
||||
pw.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if (cosDoc != null)
|
||||
cosDoc.close();
|
||||
if (pdDoc != null)
|
||||
pdDoc.close();
|
||||
|
||||
PrintWriter pw = new PrintWriter("src/output/pdf.txt");
|
||||
pw.print(parsedText);
|
||||
pw.close();
|
||||
}
|
||||
|
||||
}
|
||||
|
1
pom.xml
1
pom.xml
@ -132,6 +132,7 @@
|
||||
<module>spring-security-rest-full</module>
|
||||
<module>spring-security-rest</module>
|
||||
<module>spring-security-x509</module>
|
||||
<module>spring-session</module>
|
||||
<module>spring-spel</module>
|
||||
<module>spring-thymeleaf</module>
|
||||
<module>spring-userservice</module>
|
||||
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.camel.file;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
import org.apache.camel.Exchange;
|
||||
import org.apache.camel.Processor;
|
||||
|
||||
public class FileProcessor implements Processor {
|
||||
|
||||
public void process(Exchange exchange) throws Exception {
|
||||
String originalFileName = (String) exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
|
||||
|
||||
Date date = new Date();
|
||||
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
|
||||
String changedFileName = dateFormat.format(date) + originalFileName;
|
||||
exchange.getIn().setHeader(Exchange.FILE_NAME, changedFileName);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.camel.file;
|
||||
|
||||
import org.apache.camel.builder.RouteBuilder;
|
||||
|
||||
public class FileRouter extends RouteBuilder {
|
||||
|
||||
private static final String SOURCE_FOLDER = "src/test/source-folder";
|
||||
private static final String DESTINATION_FOLDER = "src/test/destination-folder";
|
||||
|
||||
@Override
|
||||
public void configure() throws Exception {
|
||||
from("file://" + SOURCE_FOLDER + "?delete=true").process(new FileProcessor()).to("file://" + DESTINATION_FOLDER);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
<?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-3.1.xsd
|
||||
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
|
||||
|
||||
<bean id="fileRouter" class="com.baeldung.camel.file.FileRouter" />
|
||||
<bean id="fileProcessor" class="com.baeldung.camel.file.FileProcessor" />
|
||||
|
||||
<camelContext xmlns="http://camel.apache.org/schema/spring">
|
||||
<routeBuilder ref="fileRouter" />
|
||||
</camelContext>
|
||||
|
||||
</beans>
|
@ -1,39 +1,39 @@
|
||||
<?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-3.1.xsd
|
||||
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-3.1.xsd
|
||||
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
|
||||
|
||||
<camelContext xmlns="http://camel.apache.org/schema/spring">
|
||||
<camelContext xmlns="http://camel.apache.org/schema/spring">
|
||||
|
||||
<route customId="true" id="route1">
|
||||
<route customId="true" id="route1">
|
||||
|
||||
<!-- Read files from input directory -->
|
||||
<from uri="file://src/test/data/input"/>
|
||||
<!-- Read files from input directory -->
|
||||
<from uri="file://src/test/data/input" />
|
||||
|
||||
<!-- Transform content to UpperCase -->
|
||||
<process ref="myFileProcessor"/>
|
||||
<!-- Transform content to UpperCase -->
|
||||
<process ref="myFileProcessor" />
|
||||
|
||||
<!-- Write converted file content -->
|
||||
<to uri="file://src/test/data/outputUpperCase"/>
|
||||
<!-- Write converted file content -->
|
||||
<to uri="file://src/test/data/outputUpperCase" />
|
||||
|
||||
<!-- Transform content to LowerCase -->
|
||||
<transform>
|
||||
<simple>${body.toLowerCase()}</simple>
|
||||
</transform>
|
||||
<!-- Transform content to LowerCase -->
|
||||
<transform>
|
||||
<simple>${body.toLowerCase()}</simple>
|
||||
</transform>
|
||||
|
||||
<!-- Write converted file content -->
|
||||
<to uri="file://src/test/data/outputLowerCase"/>
|
||||
<!-- Write converted file content -->
|
||||
<to uri="file://src/test/data/outputLowerCase" />
|
||||
|
||||
<!-- Display process completion message on console -->
|
||||
<transform>
|
||||
<simple>.......... File content conversion completed ..........</simple>
|
||||
</transform>
|
||||
<to uri="stream:out"/>
|
||||
<!-- Display process completion message on console -->
|
||||
<transform>
|
||||
<simple>.......... File content conversion completed ..........</simple>
|
||||
</transform>
|
||||
<to uri="stream:out" />
|
||||
|
||||
</route>
|
||||
</route>
|
||||
|
||||
</camelContext>
|
||||
</camelContext>
|
||||
|
||||
<bean id="myFileProcessor" class="com.baeldung.camel.processor.FileProcessor"/>
|
||||
<bean id="myFileProcessor" class="com.baeldung.camel.processor.FileProcessor" />
|
||||
</beans>
|
@ -0,0 +1,68 @@
|
||||
package org.apache.camel.file.processor;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import org.apache.camel.CamelContext;
|
||||
import org.apache.camel.builder.RouteBuilder;
|
||||
import org.apache.camel.impl.DefaultCamelContext;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
|
||||
import com.baeldung.camel.file.FileProcessor;
|
||||
|
||||
|
||||
public class FileProcessorTest {
|
||||
|
||||
private static final long DURATION_MILIS = 10000;
|
||||
private static final String SOURCE_FOLDER = "src/test/source-folder";
|
||||
private static final String DESTINATION_FOLDER = "src/test/destination-folder";
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
File sourceFolder = new File(SOURCE_FOLDER);
|
||||
File destinationFolder = new File(DESTINATION_FOLDER);
|
||||
|
||||
cleanFolder(sourceFolder);
|
||||
cleanFolder(destinationFolder);
|
||||
|
||||
sourceFolder.mkdirs();
|
||||
File file1 = new File(SOURCE_FOLDER + "/File1.txt");
|
||||
File file2 = new File(SOURCE_FOLDER + "/File2.txt");
|
||||
file1.createNewFile();
|
||||
file2.createNewFile();
|
||||
}
|
||||
|
||||
private void cleanFolder(File folder) {
|
||||
File[] files = folder.listFiles();
|
||||
if (files != null) {
|
||||
for (File file : files) {
|
||||
if (file.isFile()) {
|
||||
file.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void moveFolderContentJavaDSLTest() throws Exception {
|
||||
final CamelContext camelContext = new DefaultCamelContext();
|
||||
camelContext.addRoutes(new RouteBuilder() {
|
||||
@Override
|
||||
public void configure() throws Exception {
|
||||
from("file://" + SOURCE_FOLDER + "?delete=true").process(new FileProcessor()).to("file://" + DESTINATION_FOLDER);
|
||||
}
|
||||
});
|
||||
camelContext.start();
|
||||
Thread.sleep(DURATION_MILIS);
|
||||
camelContext.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void moveFolderContentSpringDSLTest() throws InterruptedException {
|
||||
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("camel-context-test.xml");
|
||||
Thread.sleep(DURATION_MILIS);
|
||||
applicationContext.close();
|
||||
|
||||
}
|
||||
}
|
@ -11,6 +11,7 @@
|
||||
<module>spring-cloud-eureka</module>
|
||||
<module>spring-cloud-hystrix</module>
|
||||
<module>spring-cloud-bootstrap</module>
|
||||
<module>spring-cloud-ribbon-client</module>
|
||||
</modules>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
|
79
spring-cloud/spring-cloud-ribbon-client/pom.xml
Normal file
79
spring-cloud/spring-cloud-ribbon-client/pom.xml
Normal file
@ -0,0 +1,79 @@
|
||||
<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>spring-cloud-ribbon</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>spring-cloud-ribbon-client</name>
|
||||
<description>Introduction to Spring Cloud Rest Client with Netflix Ribbon</description>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.4.1.RELEASE</version>
|
||||
<relativePath /> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-ribbon</artifactId>
|
||||
</dependency>
|
||||
<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>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>Camden.SR1</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
<url>https://repo.spring.io/milestone</url>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
</project>
|
@ -0,0 +1,28 @@
|
||||
package com.baeldung.spring.cloud.ribbon.client;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
import com.netflix.client.config.IClientConfig;
|
||||
import com.netflix.loadbalancer.IPing;
|
||||
import com.netflix.loadbalancer.IRule;
|
||||
import com.netflix.loadbalancer.PingUrl;
|
||||
import com.netflix.loadbalancer.WeightedResponseTimeRule;
|
||||
import com.netflix.loadbalancer.AvailabilityFilteringRule;
|
||||
|
||||
public class RibbonConfiguration {
|
||||
|
||||
@Autowired
|
||||
IClientConfig ribbonClientConfig;
|
||||
|
||||
@Bean
|
||||
public IPing ribbonPing(IClientConfig config) {
|
||||
return new PingUrl();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IRule ribbonRule(IClientConfig config) {
|
||||
return new WeightedResponseTimeRule();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
package com.baeldung.spring.cloud.ribbon.client;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
|
||||
import org.springframework.cloud.netflix.ribbon.RibbonClient;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@SpringBootApplication
|
||||
@RestController
|
||||
@RibbonClient(name = "ping-a-server", configuration = RibbonConfiguration.class)
|
||||
public class ServerLocationApp {
|
||||
|
||||
@LoadBalanced
|
||||
@Bean
|
||||
RestTemplate getRestTemplate() {
|
||||
return new RestTemplate();
|
||||
}
|
||||
|
||||
@Autowired
|
||||
RestTemplate restTemplate;
|
||||
|
||||
@RequestMapping("/server-location")
|
||||
public String serverLocation() {
|
||||
String servLoc = this.restTemplate.getForObject("http://ping-server/locaus", String.class);
|
||||
return servLoc;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ServerLocationApp.class, args);
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
spring:
|
||||
application:
|
||||
name: spring-cloud-ribbon
|
||||
|
||||
server:
|
||||
port: 8888
|
||||
|
||||
ping-server:
|
||||
ribbon:
|
||||
eureka:
|
||||
enabled: false
|
||||
listOfServers: localhost:9092,localhost:9999
|
||||
ServerListRefreshInterval: 15000
|
@ -0,0 +1,54 @@
|
||||
package com.baeldung.spring.cloud.ribbon.client;
|
||||
|
||||
import static org.assertj.core.api.BDDAssertions.then;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.context.embedded.LocalServerPort;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = ServerLocationApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
public class ServerLocationAppTests {
|
||||
ConfigurableApplicationContext application2;
|
||||
ConfigurableApplicationContext application3;
|
||||
|
||||
@Before
|
||||
public void startApps() {
|
||||
this.application2 = startApp(9092);
|
||||
this.application3 = startApp(9999);
|
||||
}
|
||||
|
||||
@After
|
||||
public void closeApps() {
|
||||
this.application2.close();
|
||||
this.application3.close();
|
||||
}
|
||||
|
||||
@LocalServerPort
|
||||
private int port;
|
||||
|
||||
@Autowired
|
||||
private TestRestTemplate testRestTemplate;
|
||||
|
||||
@Test
|
||||
public void loadBalancingServersTest() throws InterruptedException {
|
||||
ResponseEntity<String> response = this.testRestTemplate.getForEntity("http://localhost:" + this.port + "/server-location", String.class);
|
||||
assertEquals(response.getBody(), "Australia");
|
||||
}
|
||||
|
||||
private ConfigurableApplicationContext startApp(int port) {
|
||||
return SpringApplication.run(TestConfig.class, "--server.port=" + port, "--spring.jmx.enabled=false");
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package com.baeldung.spring.cloud.ribbon.client;
|
||||
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@RestController
|
||||
public class TestConfig {
|
||||
|
||||
@RequestMapping(value = "/locaus")
|
||||
public String locationAUSDetails() {
|
||||
return "Australia";
|
||||
}
|
||||
}
|
@ -80,7 +80,7 @@ public class Bar implements Serializable {
|
||||
@Column(name = "timestamp")
|
||||
private long timestamp;
|
||||
|
||||
@Column(name = "created_date")
|
||||
@Column(name = "created_date", updatable = false, nullable = false)
|
||||
@CreatedDate
|
||||
private long createdDate;
|
||||
|
||||
|
@ -9,11 +9,11 @@
|
||||
<servlet-class>
|
||||
org.springframework.web.servlet.DispatcherServlet
|
||||
</servlet-class>
|
||||
<load-on-startup>1</load-on-startup>
|
||||
<init-param>
|
||||
<param-name>contextConfigLocation</param-name>
|
||||
<param-value>classpath*:mvc-configuration.xml</param-value>
|
||||
</init-param>
|
||||
<load-on-startup>1</load-on-startup>
|
||||
</servlet>
|
||||
|
||||
<servlet-mapping>
|
||||
|
@ -1,18 +1,13 @@
|
||||
package org.baeldung.okhttp;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import okhttp3.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import okhttp3.Call;
|
||||
import okhttp3.Callback;
|
||||
import okhttp3.HttpUrl;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class OkHttpGetLiveTest {
|
||||
|
||||
@ -54,7 +49,7 @@ public class OkHttpGetLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAsynchronousGetRequest_thenCorrect() {
|
||||
public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException {
|
||||
|
||||
OkHttpClient client = new OkHttpClient();
|
||||
|
||||
@ -71,8 +66,10 @@ public class OkHttpGetLiveTest {
|
||||
}
|
||||
|
||||
public void onFailure(Call call, IOException e) {
|
||||
|
||||
fail();
|
||||
}
|
||||
});
|
||||
|
||||
Thread.sleep(3000);
|
||||
}
|
||||
}
|
||||
|
@ -37,7 +37,7 @@ public class OkHttpMiscLiveTest {
|
||||
response.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Test(expected = IOException.class)
|
||||
public void whenCancelRequest_thenCorrect() throws IOException {
|
||||
|
||||
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
|
||||
@ -49,30 +49,22 @@ public class OkHttpMiscLiveTest {
|
||||
.build();
|
||||
|
||||
final int seconds = 1;
|
||||
|
||||
final long startNanos = System.nanoTime();
|
||||
|
||||
final Call call = client.newCall(request);
|
||||
|
||||
// Schedule a job to cancel the call in 1 second.
|
||||
executor.schedule(new Runnable() {
|
||||
public void run() {
|
||||
executor.schedule(() -> {
|
||||
|
||||
logger.debug("Canceling call: " + (System.nanoTime() - startNanos) / 1e9f);
|
||||
call.cancel();
|
||||
logger.debug("Canceled call: " + (System.nanoTime() - startNanos) / 1e9f);
|
||||
|
||||
logger.debug("Canceling call: " + (System.nanoTime() - startNanos) / 1e9f);
|
||||
call.cancel();
|
||||
logger.debug("Canceled call: " + (System.nanoTime() - startNanos) / 1e9f);
|
||||
}
|
||||
}, seconds, TimeUnit.SECONDS);
|
||||
|
||||
try {
|
||||
|
||||
logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f);
|
||||
Response response = call.execute();
|
||||
logger.debug("Call was expected to fail, but completed: " + (System.nanoTime() - startNanos) / 1e9f, response);
|
||||
|
||||
} catch (IOException e) {
|
||||
|
||||
logger.debug("Call failed as expected: " + (System.nanoTime() - startNanos) / 1e9f, e);
|
||||
}
|
||||
logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f);
|
||||
Response response = call.execute();
|
||||
logger.debug("Call completed: " + (System.nanoTime() - startNanos) / 1e9f, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
71
spring-session/jetty-session-demo/pom.xml
Normal file
71
spring-session/jetty-session-demo/pom.xml
Normal file
@ -0,0 +1,71 @@
|
||||
<?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>jetty-session-demo</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.4.0.RELEASE</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jetty</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.session</groupId>
|
||||
<artifactId>spring-session</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>Brixton.RELEASE</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.3</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.spring.session.tomcatex;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@SpringBootApplication
|
||||
@RestController
|
||||
public class JettyWebApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(JettyWebApplication.class, args);
|
||||
}
|
||||
|
||||
@RequestMapping
|
||||
public String helloJetty() {
|
||||
return "hello Jetty";
|
||||
}
|
||||
|
||||
@RequestMapping("/test")
|
||||
public String lksjdf() {
|
||||
return "";
|
||||
}
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.baeldung.spring.session.tomcatex;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
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.config.http.SessionCreationPolicy;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.sessionManagement()
|
||||
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
|
||||
.and()
|
||||
.authorizeRequests().anyRequest().hasRole("ADMIN");
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package com.baeldung.spring.session.tomcatex;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
|
||||
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;
|
||||
import org.springframework.session.web.http.HeaderHttpSessionStrategy;
|
||||
import org.springframework.session.web.http.HttpSessionStrategy;
|
||||
|
||||
@Configuration
|
||||
@EnableRedisHttpSession
|
||||
public class SessionConfig extends AbstractHttpSessionApplicationInitializer {
|
||||
@Bean
|
||||
public HttpSessionStrategy httpSessionStrategy() {
|
||||
return new HeaderHttpSessionStrategy();
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
server.port=8081
|
||||
spring.redis.host=localhost
|
||||
spring.redis.port=6379
|
22
spring-session/pom.xml
Normal file
22
spring-session/pom.xml
Normal 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>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>spring-session</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<modules>
|
||||
<module>jetty-session-demo</module>
|
||||
<module>tomcat-session-demo</module>
|
||||
</modules>
|
||||
</project>
|
66
spring-session/tomcat-session-demo/pom.xml
Normal file
66
spring-session/tomcat-session-demo/pom.xml
Normal file
@ -0,0 +1,66 @@
|
||||
<?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>tomcat-session-demo</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.4.0.RELEASE</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.session</groupId>
|
||||
<artifactId>spring-session</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>Brixton.RELEASE</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.3</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
@ -0,0 +1,31 @@
|
||||
package com.baeldung.spring.session.tomcatex;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
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;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.inMemoryAuthentication()
|
||||
.withUser("user").password("password").roles("USER").and()
|
||||
.withUser("admin").password("password").roles("ADMIN");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.httpBasic().and()
|
||||
.authorizeRequests()
|
||||
.antMatchers("/").permitAll()
|
||||
.antMatchers("/tomcat").hasRole("USER")
|
||||
.antMatchers("/tomcat/admin").hasRole("ADMIN")
|
||||
.anyRequest().authenticated();
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package com.baeldung.spring.session.tomcatex;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
|
||||
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;
|
||||
|
||||
@Configuration
|
||||
@EnableRedisHttpSession
|
||||
public class SessionConfig extends AbstractHttpSessionApplicationInitializer {
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
package com.baeldung.spring.session.tomcatex;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@SpringBootApplication
|
||||
@RestController
|
||||
public class TomcatWebApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(TomcatWebApplication.class, args);
|
||||
}
|
||||
|
||||
@RequestMapping
|
||||
public String helloDefault() {
|
||||
return "hello default";
|
||||
}
|
||||
|
||||
@RequestMapping("/tomcat")
|
||||
public String helloTomcat() {
|
||||
return "hello tomcat";
|
||||
}
|
||||
|
||||
@RequestMapping("/tomcat/admin")
|
||||
public String helloTomcatAdmin() {
|
||||
return "hello tomcat admin";
|
||||
}
|
||||
}
|
@ -0,0 +1,2 @@
|
||||
spring.redis.host=localhost
|
||||
spring.redis.port=6379
|
169
spring-social-login/pom.xml
Normal file
169
spring-social-login/pom.xml
Normal file
@ -0,0 +1,169 @@
|
||||
<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>spring-social-login</artifactId>
|
||||
|
||||
<name>spring-social-login</name>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.4.0.RELEASE</version>
|
||||
<relativePath></relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-config</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-taglibs</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.thymeleaf.extras</groupId>
|
||||
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.social</groupId>
|
||||
<artifactId>spring-social-facebook</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- test -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
||||
<build>
|
||||
<finalName>spring-social-login</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>integration</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
<includes>
|
||||
<include>**/*IntegrationTest.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<test.mime>json</test.mime>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
<commons-lang3.version>3.3.2</commons-lang3.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,18 @@
|
||||
package org.baeldung.config;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.domain.EntityScan;
|
||||
import org.springframework.boot.web.support.SpringBootServletInitializer;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableJpaRepositories("org.baeldung.persistence.dao")
|
||||
@EntityScan("org.baeldung.persistence.model")
|
||||
public class Application extends SpringBootServletInitializer {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,61 @@
|
||||
package org.baeldung.config;
|
||||
|
||||
import org.baeldung.security.FacebookSignInAdapter;
|
||||
import org.baeldung.security.FacebookConnectionSignup;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
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.core.userdetails.UserDetailsService;
|
||||
import org.springframework.social.connect.ConnectionFactoryLocator;
|
||||
import org.springframework.social.connect.UsersConnectionRepository;
|
||||
import org.springframework.social.connect.mem.InMemoryUsersConnectionRepository;
|
||||
import org.springframework.social.connect.web.ProviderSignInController;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@ComponentScan(basePackages = { "org.baeldung.security" })
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Autowired
|
||||
private UserDetailsService userDetailsService;
|
||||
|
||||
@Autowired
|
||||
private ConnectionFactoryLocator connectionFactoryLocator;
|
||||
|
||||
@Autowired
|
||||
private UsersConnectionRepository usersConnectionRepository;
|
||||
|
||||
@Autowired
|
||||
private FacebookConnectionSignup facebookConnectionSignup;
|
||||
|
||||
@Override
|
||||
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.userDetailsService(userDetailsService);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(final HttpSecurity http) throws Exception {
|
||||
// @formatter:off
|
||||
http
|
||||
.csrf().disable()
|
||||
.authorizeRequests()
|
||||
.antMatchers("/login*","/signin/**","/signup/**").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
.and()
|
||||
.formLogin().loginPage("/login").permitAll()
|
||||
.and()
|
||||
.logout();
|
||||
} // @formatter:on
|
||||
|
||||
@Bean
|
||||
// @Primary
|
||||
public ProviderSignInController providerSignInController() {
|
||||
((InMemoryUsersConnectionRepository) usersConnectionRepository).setConnectionSignUp(facebookConnectionSignup);
|
||||
return new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, new FacebookSignInAdapter());
|
||||
}
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
package org.baeldung.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
|
||||
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
public class WebConfig extends WebMvcConfigurerAdapter {
|
||||
|
||||
@Bean
|
||||
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
|
||||
return new PropertySourcesPlaceholderConfigurer();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) {
|
||||
configurer.enable();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addViewControllers(final ViewControllerRegistry registry) {
|
||||
super.addViewControllers(registry);
|
||||
registry.addViewController("/").setViewName("forward:/index");
|
||||
registry.addViewController("/index");
|
||||
registry.addViewController("/login");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package org.baeldung.persistence.dao;
|
||||
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
|
||||
User findByUsername(final String username);
|
||||
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
package org.baeldung.persistence.model;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class User {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false, unique = true)
|
||||
private String username;
|
||||
|
||||
private String password;
|
||||
|
||||
public User() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("User [id=").append(id).append(", username=").append(username).append(", password=").append(password).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package org.baeldung.security;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
|
||||
import org.baeldung.persistence.dao.UserRepository;
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.social.connect.Connection;
|
||||
import org.springframework.social.connect.ConnectionSignUp;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class FacebookConnectionSignup implements ConnectionSignUp {
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Override
|
||||
public String execute(Connection<?> connection) {
|
||||
System.out.println("signup === ");
|
||||
final User user = new User();
|
||||
user.setUsername(connection.getDisplayName());
|
||||
user.setPassword(randomAlphabetic(8));
|
||||
userRepository.save(user);
|
||||
return user.getUsername();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package org.baeldung.security;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.social.connect.Connection;
|
||||
import org.springframework.social.connect.web.SignInAdapter;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.context.request.NativeWebRequest;
|
||||
|
||||
@Service
|
||||
public class FacebookSignInAdapter implements SignInAdapter {
|
||||
@Override
|
||||
public String signIn(String localUserId, Connection<?> connection, NativeWebRequest request) {
|
||||
System.out.println(" ====== Sign In adapter");
|
||||
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(connection.getDisplayName(), null, Arrays.asList(new SimpleGrantedAuthority("FACEBOOK_USER"))));
|
||||
return null;
|
||||
}
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
package org.baeldung.security;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.baeldung.persistence.dao.UserRepository;
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class MyUserDetailsService implements UserDetailsService {
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
public MyUserDetailsService() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(final String username) {
|
||||
final User user = userRepository.findByUsername(username);
|
||||
if (user == null) {
|
||||
throw new UsernameNotFoundException(username);
|
||||
}
|
||||
return new org.springframework.security.core.userdetails.User(username, user.getPassword(), true, true, true, true, Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")));
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
spring.social.facebook.appId=1715784745414888
|
||||
spring.social.facebook.appSecret=abefd6497e9cc01ad03be28509617bf0
|
||||
spring.thymeleaf.cache=false
|
1
spring-social-login/src/main/resources/data.sql
Normal file
1
spring-social-login/src/main/resources/data.sql
Normal file
@ -0,0 +1 @@
|
||||
insert into User (id, username, password) values (1,'john', '123');
|
27
spring-social-login/src/main/resources/templates/index.html
Normal file
27
spring-social-login/src/main/resources/templates/index.html
Normal file
@ -0,0 +1,27 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<title>Spring Social Login</title>
|
||||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"/>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<nav class="navbar navbar-default">
|
||||
<div class="container-fluid">
|
||||
<div class="navbar-header">
|
||||
<a class="navbar-brand" th:href="@{/}">Spring Social Login</a>
|
||||
</div>
|
||||
<p class="navbar-text navbar-right">
|
||||
<span sec:authentication="name">Username</span>
|
||||
<a th:href="@{/logout}">Logout</a>
|
||||
</p>
|
||||
</div><!-- /.container-fluid -->
|
||||
</nav>
|
||||
|
||||
<div class="container">
|
||||
<h1 class="col-sm-12">Welcome, <span sec:authentication="name">Username</span></h1>
|
||||
<p class="col-sm-12 text-muted" sec:authentication="authorities">User authorities</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
44
spring-social-login/src/main/resources/templates/login.html
Normal file
44
spring-social-login/src/main/resources/templates/login.html
Normal file
@ -0,0 +1,44 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<title>Spring Social Login</title>
|
||||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div th:if="${param.logout}" class="alert alert-info">You have been logged out</div>
|
||||
<div th:if="${param.error}" class="alert alert-danger">There was an error, please try again</div>
|
||||
|
||||
<h1 class="col-sm-12">Login</h1>
|
||||
<form th:action="@{/login}" method="POST" >
|
||||
<div class="row col-sm-6">
|
||||
<div class="form-group">
|
||||
<label class="col-sm-3">Username</label>
|
||||
<span class="col-sm-9"><input class="form-control" type="text" name="username" /></span>
|
||||
</div>
|
||||
<br/>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-3">Password</label>
|
||||
<span class="col-sm-9"><input class="form-control" type="password" name="password" /></span>
|
||||
</div>
|
||||
|
||||
<div class="col-sm-12">
|
||||
<input type="submit" value="Login" class="btn btn-default" />
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
<div class="clearfix"></div>
|
||||
<br/>
|
||||
<br/>
|
||||
<div class="col-sm-12">
|
||||
<form action="/signin/facebook" method="POST">
|
||||
<input type="hidden" name="scope" value="public_profile" />
|
||||
<input type="submit" value="Login using Facebook" class="btn btn-primary" />
|
||||
</form>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,18 @@
|
||||
package org.baeldung.test;
|
||||
|
||||
import org.baeldung.config.Application;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||
public class ApplicationIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void whenLoadApplication_thenSuccess() {
|
||||
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user