Merge remote-tracking branch 'upstream/master' into craedel-log4j2
This commit is contained in:
commit
1c0e0c6ec1
|
@ -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())
|
||||||
|
);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package org.baeldung.equalshashcode.entities;
|
package com.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
|
@ -1,4 +1,4 @@
|
||||||
package org.baeldung.equalshashcode.entities;
|
package com.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
public class PrimitiveClass {
|
public class PrimitiveClass {
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package org.baeldung.equalshashcode.entities;
|
package com.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
public class Rectangle extends Shape {
|
public class Rectangle extends Shape {
|
||||||
private double width;
|
private double width;
|
|
@ -1,4 +1,4 @@
|
||||||
package org.baeldung.equalshashcode.entities;
|
package com.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
public abstract class Shape {
|
public abstract class Shape {
|
||||||
public abstract double area();
|
public abstract double area();
|
|
@ -1,4 +1,4 @@
|
||||||
package org.baeldung.equalshashcode.entities;
|
package com.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
import java.awt.Color;
|
import java.awt.Color;
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package org.baeldung.executable;
|
package com.baeldung.executable;
|
||||||
|
|
||||||
import javax.swing.JOptionPane;
|
import javax.swing.JOptionPane;
|
||||||
|
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -24,7 +24,7 @@ public class EchoClient {
|
||||||
public String sendEcho(String msg) {
|
public String sendEcho(String msg) {
|
||||||
DatagramPacket packet = null;
|
DatagramPacket packet = null;
|
||||||
try {
|
try {
|
||||||
buf=msg.getBytes();
|
buf = msg.getBytes();
|
||||||
packet = new DatagramPacket(buf, buf.length, address, 4445);
|
packet = new DatagramPacket(buf, buf.length, address, 4445);
|
||||||
socket.send(packet);
|
socket.send(packet);
|
||||||
packet = new DatagramPacket(buf, buf.length);
|
packet = new DatagramPacket(buf, buf.length);
|
||||||
|
|
|
@ -17,6 +17,11 @@ public class EchoClient {
|
||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static void stop() throws IOException {
|
||||||
|
client.close();
|
||||||
|
buffer = null;
|
||||||
|
}
|
||||||
|
|
||||||
private EchoClient() {
|
private EchoClient() {
|
||||||
try {
|
try {
|
||||||
client = SocketChannel.open(new InetSocketAddress("localhost", 5454));
|
client = SocketChannel.open(new InetSocketAddress("localhost", 5454));
|
||||||
|
@ -42,5 +47,4 @@ public class EchoClient {
|
||||||
return response;
|
return response;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,21 +1,19 @@
|
||||||
package com.baeldung.java.nio.selector;
|
package com.baeldung.java.nio.selector;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.nio.channels.SelectionKey;
|
||||||
|
import java.nio.channels.Selector;
|
||||||
import java.nio.channels.ServerSocketChannel;
|
import java.nio.channels.ServerSocketChannel;
|
||||||
import java.nio.channels.SocketChannel;
|
import java.nio.channels.SocketChannel;
|
||||||
import java.nio.channels.Selector;
|
|
||||||
import java.nio.channels.SelectionKey;
|
|
||||||
import java.nio.ByteBuffer;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
import java.net.InetSocketAddress;
|
import java.util.Set;
|
||||||
import java.io.File;
|
|
||||||
|
|
||||||
public class EchoServer {
|
public class EchoServer {
|
||||||
|
|
||||||
public static void main(String[] args)
|
public static void main(String[] args) throws IOException {
|
||||||
|
|
||||||
throws IOException {
|
|
||||||
Selector selector = Selector.open();
|
Selector selector = Selector.open();
|
||||||
ServerSocketChannel serverSocket = ServerSocketChannel.open();
|
ServerSocketChannel serverSocket = ServerSocketChannel.open();
|
||||||
serverSocket.bind(new InetSocketAddress("localhost", 5454));
|
serverSocket.bind(new InetSocketAddress("localhost", 5454));
|
||||||
|
@ -49,7 +47,6 @@ public class EchoServer {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static Process start() throws IOException, InterruptedException {
|
public static Process start() throws IOException, InterruptedException {
|
||||||
String javaHome = System.getProperty("java.home");
|
String javaHome = System.getProperty("java.home");
|
||||||
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
|
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
|
||||||
|
|
|
@ -12,8 +12,8 @@ public class UseLocalDateTimeUnitTest {
|
||||||
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
|
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_whenUsingParse_thenLocalDateTime(){
|
public void givenString_whenUsingParse_thenLocalDateTime() {
|
||||||
Assert.assertEquals(LocalDate.of(2016, Month.MAY, 10),useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
|
Assert.assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
|
||||||
Assert.assertEquals(LocalTime.of(6,30),useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
|
Assert.assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -12,43 +12,43 @@ public class UseLocalDateUnitTest {
|
||||||
UseLocalDate useLocalDate = new UseLocalDate();
|
UseLocalDate useLocalDate = new UseLocalDate();
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenValues_whenUsingFactoryOf_thenLocalDate(){
|
public void givenValues_whenUsingFactoryOf_thenLocalDate() {
|
||||||
Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingFactoryOfMethod(2016,5,10).toString());
|
Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_whenUsingParse_thenLocalDate(){
|
public void givenString_whenUsingParse_thenLocalDate() {
|
||||||
Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
|
Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingClock_thenLocalDate(){
|
public void whenUsingClock_thenLocalDate() {
|
||||||
Assert.assertEquals(LocalDate.now(),useLocalDate.getLocalDateFromClock());
|
Assert.assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDate_whenUsingPlus_thenNextDay(){
|
public void givenDate_whenUsingPlus_thenNextDay() {
|
||||||
Assert.assertEquals(LocalDate.now().plusDays(1),useLocalDate.getNextDay(LocalDate.now()));
|
Assert.assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDate_whenUsingMinus_thenPreviousDay(){
|
public void givenDate_whenUsingMinus_thenPreviousDay() {
|
||||||
Assert.assertEquals(LocalDate.now().minusDays(1),useLocalDate.getPreviousDay(LocalDate.now()));
|
Assert.assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek(){
|
public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek() {
|
||||||
Assert.assertEquals(DayOfWeek.SUNDAY,useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
|
Assert.assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth(){
|
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() {
|
||||||
Assert.assertEquals(1,useLocalDate.getFirstDayOfMonth().getDayOfMonth());
|
Assert.assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight(){
|
public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight() {
|
||||||
Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"),useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
|
Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,27 +10,27 @@ public class UseLocalTimeUnitTest {
|
||||||
UseLocalTime useLocalTime = new UseLocalTime();
|
UseLocalTime useLocalTime = new UseLocalTime();
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenValues_whenUsingFactoryOf_thenLocalTime(){
|
public void givenValues_whenUsingFactoryOf_thenLocalTime() {
|
||||||
Assert.assertEquals("07:07:07",useLocalTime.getLocalTimeUsingFactoryOfMethod(7,7,7).toString());
|
Assert.assertEquals("07:07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7, 7).toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_whenUsingParse_thenLocalTime(){
|
public void givenString_whenUsingParse_thenLocalTime() {
|
||||||
Assert.assertEquals("06:30",useLocalTime.getLocalTimeUsingParseMethod("06:30").toString());
|
Assert.assertEquals("06:30", useLocalTime.getLocalTimeUsingParseMethod("06:30").toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTime_whenAddHour_thenLocalTime(){
|
public void givenTime_whenAddHour_thenLocalTime() {
|
||||||
Assert.assertEquals("07:30",useLocalTime.addAnHour(LocalTime.of(6,30)).toString());
|
Assert.assertEquals("07:30", useLocalTime.addAnHour(LocalTime.of(6, 30)).toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getHourFromLocalTime(){
|
public void getHourFromLocalTime() {
|
||||||
Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1,1)));
|
Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1, 1)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getLocalTimeWithMinuteSetToValue(){
|
public void getLocalTimeWithMinuteSetToValue() {
|
||||||
Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10,10), 20));
|
Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10, 10), 20));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,17 +7,17 @@ import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class UsePeriodUnitTest {
|
public class UsePeriodUnitTest {
|
||||||
UsePeriod usingPeriod=new UsePeriod();
|
UsePeriod usingPeriod = new UsePeriod();
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPeriodAndLocalDate_thenCalculateModifiedDate(){
|
public void givenPeriodAndLocalDate_thenCalculateModifiedDate() {
|
||||||
Period period = Period.ofDays(1);
|
Period period = Period.ofDays(1);
|
||||||
LocalDate localDate = LocalDate.parse("2007-05-10");
|
LocalDate localDate = LocalDate.parse("2007-05-10");
|
||||||
Assert.assertEquals(localDate.plusDays(1),usingPeriod.modifyDates(localDate, period));
|
Assert.assertEquals(localDate.plusDays(1), usingPeriod.modifyDates(localDate, period));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDates_thenGetPeriod(){
|
public void givenDates_thenGetPeriod() {
|
||||||
LocalDate localDate1 = LocalDate.parse("2007-05-10");
|
LocalDate localDate1 = LocalDate.parse("2007-05-10");
|
||||||
LocalDate localDate2 = LocalDate.parse("2007-05-15");
|
LocalDate localDate2 = LocalDate.parse("2007-05-15");
|
||||||
|
|
||||||
|
|
|
@ -9,12 +9,12 @@ import org.junit.Test;
|
||||||
|
|
||||||
public class UseZonedDateTimeUnitTest {
|
public class UseZonedDateTimeUnitTest {
|
||||||
|
|
||||||
UseZonedDateTime zonedDateTime=new UseZonedDateTime();
|
UseZonedDateTime zonedDateTime = new UseZonedDateTime();
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenZoneId_thenZonedDateTime(){
|
public void givenZoneId_thenZonedDateTime() {
|
||||||
ZoneId zoneId=ZoneId.of("Europe/Paris");
|
ZoneId zoneId = ZoneId.of("Europe/Paris");
|
||||||
ZonedDateTime zonedDatetime=zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId);
|
ZonedDateTime zonedDatetime = zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId);
|
||||||
Assert.assertEquals(zoneId,ZoneId.from(zonedDatetime));
|
Assert.assertEquals(zoneId, ZoneId.from(zonedDatetime));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -32,7 +32,6 @@ public class EncoderDecoderUnitTest {
|
||||||
return encoded;
|
return encoded;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private String decode(String value) {
|
private String decode(String value) {
|
||||||
String decoded = null;
|
String decoded = null;
|
||||||
try {
|
try {
|
||||||
|
@ -59,9 +58,7 @@ public class EncoderDecoderUnitTest {
|
||||||
requestParams.put("key2", "value@!$2");
|
requestParams.put("key2", "value@!$2");
|
||||||
requestParams.put("key3", "value%3");
|
requestParams.put("key3", "value%3");
|
||||||
|
|
||||||
String encodedURL = requestParams.keySet().stream()
|
String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com?", ""));
|
||||||
.map(key -> key + "=" + encodeValue(requestParams.get(key)))
|
|
||||||
.collect(joining("&", "http://www.baeldung.com?", ""));
|
|
||||||
|
|
||||||
Assert.assertThat(testUrl, CoreMatchers.is(encodedURL));
|
Assert.assertThat(testUrl, CoreMatchers.is(encodedURL));
|
||||||
}
|
}
|
||||||
|
@ -72,12 +69,9 @@ public class EncoderDecoderUnitTest {
|
||||||
|
|
||||||
String query = url.getQuery();
|
String query = url.getQuery();
|
||||||
|
|
||||||
String decodedQuery = Arrays.stream(query.split("&"))
|
String decodedQuery = Arrays.stream(query.split("&")).map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1])).collect(joining("&"));
|
||||||
.map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1]))
|
|
||||||
.collect(joining("&"));
|
|
||||||
|
|
||||||
Assert.assertEquals(
|
Assert.assertEquals("http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery);
|
||||||
"http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.enums;
|
package com.baeldung.enums;
|
||||||
|
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
|
|
@ -0,0 +1,46 @@
|
||||||
|
package com.baeldung.hexToAscii;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class HexToAscii {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public static void whenHexToAscii() {
|
||||||
|
String asciiString = "http://www.baeldung.com/jackson-serialize-dates";
|
||||||
|
String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573";
|
||||||
|
|
||||||
|
assertEquals(asciiString, hexToAscii(hexEquivalent));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public static void whenAsciiToHex() {
|
||||||
|
String asciiString = "http://www.baeldung.com/jackson-serialize-dates";
|
||||||
|
String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573";
|
||||||
|
|
||||||
|
assertEquals(hexEquivalent, asciiToHex(asciiString));
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
|
||||||
|
private static String asciiToHex(String asciiStr) {
|
||||||
|
char[] chars = asciiStr.toCharArray();
|
||||||
|
StringBuilder hex = new StringBuilder();
|
||||||
|
for (char ch : chars) {
|
||||||
|
hex.append(Integer.toHexString((int) ch));
|
||||||
|
}
|
||||||
|
|
||||||
|
return hex.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String hexToAscii(String hexStr) {
|
||||||
|
StringBuilder output = new StringBuilder("");
|
||||||
|
for (int i = 0; i < hexStr.length(); i += 2) {
|
||||||
|
String str = hexStr.substring(i, i + 2);
|
||||||
|
output.append((char) Integer.parseInt(str, 16));
|
||||||
|
}
|
||||||
|
return output.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,118 @@
|
||||||
|
package com.baeldung.java.networking.interfaces;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.net.*;
|
||||||
|
import java.util.Enumeration;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class NetworkInterfaceManualTest {
|
||||||
|
@Test
|
||||||
|
public void givenName_whenReturnsNetworkInterface_thenCorrect() throws SocketException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||||
|
assertNotNull(nif);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInExistentName_whenReturnsNull_thenCorrect() throws SocketException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("inexistent_name");
|
||||||
|
assertNull(nif);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIP_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
byte[] ip = new byte[] { 127, 0, 0, 1 };
|
||||||
|
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByAddress(ip));
|
||||||
|
assertNotNull(nif);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenHostName_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByName("localhost"));
|
||||||
|
assertNotNull(nif);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLocalHost_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
|
||||||
|
assertNotNull(nif);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLoopBack_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLoopbackAddress());
|
||||||
|
assertNotNull(nif);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIndex_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByIndex(0);
|
||||||
|
assertNotNull(nif);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInterface_whenReturnsInetAddresses_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||||
|
Enumeration<InetAddress> addressEnum = nif.getInetAddresses();
|
||||||
|
InetAddress address = addressEnum.nextElement();
|
||||||
|
assertEquals("127.0.0.1", address.getHostAddress());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInterface_whenReturnsInterfaceAddresses_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||||
|
|
||||||
|
List<InterfaceAddress> addressEnum = nif.getInterfaceAddresses();
|
||||||
|
InterfaceAddress address = addressEnum.get(0);
|
||||||
|
InetAddress localAddress = address.getAddress();
|
||||||
|
InetAddress broadCastAddress = address.getBroadcast();
|
||||||
|
assertEquals("127.0.0.1", localAddress.getHostAddress());
|
||||||
|
assertEquals("127.255.255.255", broadCastAddress.getHostAddress());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInterface_whenChecksIfLoopback_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||||
|
assertTrue(nif.isLoopback());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInterface_whenChecksIfUp_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||||
|
assertTrue(nif.isUp());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInterface_whenChecksIfPointToPoint_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||||
|
assertFalse(nif.isPointToPoint());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInterface_whenChecksIfVirtual_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||||
|
assertFalse(nif.isVirtual());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInterface_whenChecksMulticastSupport_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||||
|
assertTrue(nif.supportsMulticast());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInterface_whenGetsMacAddress_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||||
|
byte[] bytes = nif.getHardwareAddress();
|
||||||
|
assertNotNull(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInterface_whenGetsMTU_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("net0");
|
||||||
|
int mtu = nif.getMTU();
|
||||||
|
assertEquals(1500, mtu);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.java.networking.udp;
|
package com.baeldung.java.networking.udp;
|
||||||
|
|
||||||
|
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
|
@ -4,19 +4,32 @@ import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class NioEchoIntegrationTest {
|
public class NioEchoIntegrationTest {
|
||||||
|
|
||||||
|
Process server;
|
||||||
|
EchoClient client;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() throws IOException, InterruptedException {
|
||||||
|
server = EchoServer.start();
|
||||||
|
client = EchoClient.start();
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClient_whenServerEchosMessage_thenCorrect() throws IOException, InterruptedException {
|
public void givenServerClient_whenServerEchosMessage_thenCorrect() {
|
||||||
Process process = EchoServer.start();
|
|
||||||
EchoClient client = EchoClient.start();
|
|
||||||
String resp1 = client.sendMessage("hello");
|
String resp1 = client.sendMessage("hello");
|
||||||
String resp2 = client.sendMessage("world");
|
String resp2 = client.sendMessage("world");
|
||||||
assertEquals("hello", resp1);
|
assertEquals("hello", resp1);
|
||||||
assertEquals("world", resp2);
|
assertEquals("world", resp2);
|
||||||
|
}
|
||||||
|
|
||||||
process.destroy();
|
@After
|
||||||
|
public void teardown() throws IOException {
|
||||||
|
server.destroy();
|
||||||
|
EchoClient.stop();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,7 +4,6 @@ import static org.junit.Assert.assertFalse;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.file.CopyOption;
|
|
||||||
import java.nio.file.DirectoryNotEmptyException;
|
import java.nio.file.DirectoryNotEmptyException;
|
||||||
import java.nio.file.FileAlreadyExistsException;
|
import java.nio.file.FileAlreadyExistsException;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
|
@ -12,7 +11,7 @@ import java.nio.file.NoSuchFileException;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
import java.nio.file.StandardCopyOption;
|
import java.nio.file.StandardCopyOption;
|
||||||
import java.util.Date;
|
import java.util.UUID;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
@ -33,7 +32,7 @@ public class FileTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenExistentDirPath_whenConfirmsNotRegularFile_thenCorrect() {
|
public void givenDirPath_whenConfirmsNotRegularFile_thenCorrect() {
|
||||||
Path p = Paths.get(HOME);
|
Path p = Paths.get(HOME);
|
||||||
assertFalse(Files.isRegularFile(p));
|
assertFalse(Files.isRegularFile(p));
|
||||||
}
|
}
|
||||||
|
@ -67,7 +66,7 @@ public class FileTest {
|
||||||
// creating file
|
// creating file
|
||||||
@Test
|
@Test
|
||||||
public void givenFilePath_whenCreatesNewFile_thenCorrect() throws IOException {
|
public void givenFilePath_whenCreatesNewFile_thenCorrect() throws IOException {
|
||||||
String fileName = "myfile_" + new Date().getTime() + ".txt";
|
String fileName = "myfile_" + UUID.randomUUID().toString() + ".txt";
|
||||||
Path p = Paths.get(HOME + "/" + fileName);
|
Path p = Paths.get(HOME + "/" + fileName);
|
||||||
assertFalse(Files.exists(p));
|
assertFalse(Files.exists(p));
|
||||||
Files.createFile(p);
|
Files.createFile(p);
|
||||||
|
@ -77,7 +76,7 @@ public class FileTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDirPath_whenCreatesNewDir_thenCorrect() throws IOException {
|
public void givenDirPath_whenCreatesNewDir_thenCorrect() throws IOException {
|
||||||
String dirName = "myDir_" + new Date().getTime();
|
String dirName = "myDir_" + UUID.randomUUID().toString();
|
||||||
Path p = Paths.get(HOME + "/" + dirName);
|
Path p = Paths.get(HOME + "/" + dirName);
|
||||||
assertFalse(Files.exists(p));
|
assertFalse(Files.exists(p));
|
||||||
Files.createDirectory(p);
|
Files.createDirectory(p);
|
||||||
|
@ -89,7 +88,7 @@ public class FileTest {
|
||||||
|
|
||||||
@Test(expected = NoSuchFileException.class)
|
@Test(expected = NoSuchFileException.class)
|
||||||
public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() throws IOException {
|
public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() throws IOException {
|
||||||
String dirName = "myDir_" + new Date().getTime() + "/subdir";
|
String dirName = "myDir_" + UUID.randomUUID().toString() + "/subdir";
|
||||||
Path p = Paths.get(HOME + "/" + dirName);
|
Path p = Paths.get(HOME + "/" + dirName);
|
||||||
assertFalse(Files.exists(p));
|
assertFalse(Files.exists(p));
|
||||||
Files.createDirectory(p);
|
Files.createDirectory(p);
|
||||||
|
@ -98,7 +97,7 @@ public class FileTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDirPath_whenCreatesRecursively_thenCorrect() throws IOException {
|
public void givenDirPath_whenCreatesRecursively_thenCorrect() throws IOException {
|
||||||
Path dir = Paths.get(HOME + "/myDir_" + new Date().getTime());
|
Path dir = Paths.get(HOME + "/myDir_" + UUID.randomUUID().toString());
|
||||||
Path subdir = dir.resolve("subdir");
|
Path subdir = dir.resolve("subdir");
|
||||||
assertFalse(Files.exists(dir));
|
assertFalse(Files.exists(dir));
|
||||||
assertFalse(Files.exists(subdir));
|
assertFalse(Files.exists(subdir));
|
||||||
|
@ -119,7 +118,7 @@ public class FileTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenFilePath_whenCreatesTempFileWithDefaultsNaming_thenCorrect() throws IOException {
|
public void givenPath_whenCreatesTempFileWithDefaults_thenCorrect() throws IOException {
|
||||||
Path p = Paths.get(HOME + "/");
|
Path p = Paths.get(HOME + "/");
|
||||||
p = Files.createTempFile(p, null, null);
|
p = Files.createTempFile(p, null, null);
|
||||||
// like 8600179353689423985.tmp
|
// like 8600179353689423985.tmp
|
||||||
|
@ -148,7 +147,7 @@ public class FileTest {
|
||||||
|
|
||||||
@Test(expected = DirectoryNotEmptyException.class)
|
@Test(expected = DirectoryNotEmptyException.class)
|
||||||
public void givenPath_whenFailsToDeleteNonEmptyDir_thenCorrect() throws IOException {
|
public void givenPath_whenFailsToDeleteNonEmptyDir_thenCorrect() throws IOException {
|
||||||
Path dir = Paths.get(HOME + "/emptyDir" + new Date().getTime());
|
Path dir = Paths.get(HOME + "/emptyDir" + UUID.randomUUID().toString());
|
||||||
Files.createDirectory(dir);
|
Files.createDirectory(dir);
|
||||||
assertTrue(Files.exists(dir));
|
assertTrue(Files.exists(dir));
|
||||||
Path file = dir.resolve("file.txt");
|
Path file = dir.resolve("file.txt");
|
||||||
|
@ -159,15 +158,11 @@ public class FileTest {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test(expected = NoSuchFileException.class)
|
||||||
public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException {
|
public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException {
|
||||||
Path p = Paths.get(HOME + "/inexistentFile.txt");
|
Path p = Paths.get(HOME + "/inexistentFile.txt");
|
||||||
assertFalse(Files.exists(p));
|
assertFalse(Files.exists(p));
|
||||||
try {
|
Files.delete(p);
|
||||||
Files.delete(p);
|
|
||||||
} catch (IOException e) {
|
|
||||||
assertTrue(e instanceof NoSuchFileException);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -182,8 +177,8 @@ public class FileTest {
|
||||||
// copy file
|
// copy file
|
||||||
@Test
|
@Test
|
||||||
public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException {
|
public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException {
|
||||||
Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
|
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||||
Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime());
|
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||||
Files.createDirectory(dir1);
|
Files.createDirectory(dir1);
|
||||||
Files.createDirectory(dir2);
|
Files.createDirectory(dir2);
|
||||||
Path file1 = dir1.resolve("filetocopy.txt");
|
Path file1 = dir1.resolve("filetocopy.txt");
|
||||||
|
@ -198,8 +193,8 @@ public class FileTest {
|
||||||
|
|
||||||
@Test(expected = FileAlreadyExistsException.class)
|
@Test(expected = FileAlreadyExistsException.class)
|
||||||
public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException {
|
public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||||
Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
|
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||||
Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime());
|
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||||
Files.createDirectory(dir1);
|
Files.createDirectory(dir1);
|
||||||
Files.createDirectory(dir2);
|
Files.createDirectory(dir2);
|
||||||
Path file1 = dir1.resolve("filetocopy.txt");
|
Path file1 = dir1.resolve("filetocopy.txt");
|
||||||
|
@ -215,8 +210,8 @@ public class FileTest {
|
||||||
// moving files
|
// moving files
|
||||||
@Test
|
@Test
|
||||||
public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException {
|
public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException {
|
||||||
Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
|
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||||
Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime());
|
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||||
Files.createDirectory(dir1);
|
Files.createDirectory(dir1);
|
||||||
Files.createDirectory(dir2);
|
Files.createDirectory(dir2);
|
||||||
Path file1 = dir1.resolve("filetocopy.txt");
|
Path file1 = dir1.resolve("filetocopy.txt");
|
||||||
|
@ -232,8 +227,8 @@ public class FileTest {
|
||||||
|
|
||||||
@Test(expected = FileAlreadyExistsException.class)
|
@Test(expected = FileAlreadyExistsException.class)
|
||||||
public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException {
|
public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||||
Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
|
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||||
Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime());
|
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||||
Files.createDirectory(dir1);
|
Files.createDirectory(dir1);
|
||||||
Files.createDirectory(dir2);
|
Files.createDirectory(dir2);
|
||||||
Path file1 = dir1.resolve("filetocopy.txt");
|
Path file1 = dir1.resolve("filetocopy.txt");
|
||||||
|
@ -247,4 +242,5 @@ public class FileTest {
|
||||||
assertTrue(Files.exists(file2));
|
assertTrue(Files.exists(file2));
|
||||||
assertFalse(Files.exists(file1));
|
assertFalse(Files.exists(file1));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -13,7 +13,7 @@ import java.util.Date;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class PathTest {
|
public class PathManualTest {
|
||||||
|
|
||||||
private static final String HOME = System.getProperty("user.home");
|
private static final String HOME = System.getProperty("user.home");
|
||||||
|
|
|
@ -0,0 +1,52 @@
|
||||||
|
package com.baeldung.java8;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class Java8ForEachTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void compareForEachMethods_thenPrintResults() {
|
||||||
|
|
||||||
|
List<String> names = new ArrayList<>();
|
||||||
|
names.add("Larry");
|
||||||
|
names.add("Steve");
|
||||||
|
names.add("James");
|
||||||
|
names.add("Conan");
|
||||||
|
names.add("Ellen");
|
||||||
|
|
||||||
|
// Java 5 - for-loop
|
||||||
|
System.out.println("--- Enhanced for-loop ---");
|
||||||
|
for (String name : names) {
|
||||||
|
System.out.println(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Java 8 - forEach
|
||||||
|
System.out.println("--- forEach method ---");
|
||||||
|
names.forEach(name -> System.out.println(name));
|
||||||
|
|
||||||
|
// Anonymous inner class that implements Consumer interface
|
||||||
|
System.out.println("--- Anonymous inner class ---");
|
||||||
|
names.forEach(new Consumer<String>() {
|
||||||
|
public void accept(String name) {
|
||||||
|
System.out.println(name);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create a Consumer implementation to then use in a forEach method
|
||||||
|
Consumer<String> consumerNames = name -> {
|
||||||
|
System.out.println(name);
|
||||||
|
};
|
||||||
|
System.out.println("--- Implementation of Consumer interface ---");
|
||||||
|
names.forEach(consumerNames);
|
||||||
|
|
||||||
|
// Print elements using a Method Reference
|
||||||
|
System.out.println("--- Method Reference ---");
|
||||||
|
names.forEach(System.out::println);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -27,18 +27,14 @@ public class Java8StreamApiUnitTest {
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void init() {
|
public void init() {
|
||||||
productList = Arrays.asList(
|
productList = Arrays.asList(new Product(23, "potatoes"), new Product(14, "orange"), new Product(13, "lemon"), new Product(23, "bread"), new Product(13, "sugar"));
|
||||||
new Product(23, "potatoes"), new Product(14, "orange"),
|
|
||||||
new Product(13, "lemon"), new Product(23, "bread"),
|
|
||||||
new Product(13, "sugar"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void checkPipeline_whenStreamOneElementShorter_thenCorrect() {
|
public void checkPipeline_whenStreamOneElementShorter_thenCorrect() {
|
||||||
|
|
||||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||||
long size = list.stream().skip(1)
|
long size = list.stream().skip(1).map(element -> element.substring(0, 3)).count();
|
||||||
.map(element -> element.substring(0, 3)).count();
|
|
||||||
assertEquals(list.size() - 1, size);
|
assertEquals(list.size() - 1, size);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -48,11 +44,10 @@ public class Java8StreamApiUnitTest {
|
||||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||||
|
|
||||||
counter = 0;
|
counter = 0;
|
||||||
long sizeFirst = list.stream()
|
long sizeFirst = list.stream().skip(2).map(element -> {
|
||||||
.skip(2).map(element -> {
|
wasCalled();
|
||||||
wasCalled();
|
return element.substring(0, 3);
|
||||||
return element.substring(0, 3);
|
}).count();
|
||||||
}).count();
|
|
||||||
assertEquals(1, counter);
|
assertEquals(1, counter);
|
||||||
|
|
||||||
counter = 0;
|
counter = 0;
|
||||||
|
@ -84,7 +79,7 @@ public class Java8StreamApiUnitTest {
|
||||||
Stream<String> streamOfArray = Stream.of("a", "b", "c");
|
Stream<String> streamOfArray = Stream.of("a", "b", "c");
|
||||||
assertEquals(3, streamOfArray.count());
|
assertEquals(3, streamOfArray.count());
|
||||||
|
|
||||||
String[] arr = new String[]{"a", "b", "c"};
|
String[] arr = new String[] { "a", "b", "c" };
|
||||||
Stream<String> streamOfArrayPart = Arrays.stream(arr, 1, 3);
|
Stream<String> streamOfArrayPart = Arrays.stream(arr, 1, 3);
|
||||||
assertEquals(2, streamOfArrayPart.count());
|
assertEquals(2, streamOfArrayPart.count());
|
||||||
|
|
||||||
|
@ -112,7 +107,7 @@ public class Java8StreamApiUnitTest {
|
||||||
}
|
}
|
||||||
assertEquals("a", streamOfStrings.findFirst().get());
|
assertEquals("a", streamOfStrings.findFirst().get());
|
||||||
|
|
||||||
Stream<String> streamBuilder = Stream.<String>builder().add("a").add("b").add("c").build();
|
Stream<String> streamBuilder = Stream.<String> builder().add("a").add("b").add("c").build();
|
||||||
assertEquals(3, streamBuilder.count());
|
assertEquals(3, streamBuilder.count());
|
||||||
|
|
||||||
Stream<String> streamGenerated = Stream.generate(() -> "element").limit(10);
|
Stream<String> streamGenerated = Stream.generate(() -> "element").limit(10);
|
||||||
|
@ -126,14 +121,13 @@ public class Java8StreamApiUnitTest {
|
||||||
public void runStreamPipeline_whenOrderIsRight_thenCorrect() {
|
public void runStreamPipeline_whenOrderIsRight_thenCorrect() {
|
||||||
|
|
||||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||||
Optional<String> stream = list.stream()
|
Optional<String> stream = list.stream().filter(element -> {
|
||||||
.filter(element -> {
|
log.info("filter() was called");
|
||||||
log.info("filter() was called");
|
return element.contains("2");
|
||||||
return element.contains("2");
|
}).map(element -> {
|
||||||
}).map(element -> {
|
log.info("map() was called");
|
||||||
log.info("map() was called");
|
return element.toUpperCase();
|
||||||
return element.toUpperCase();
|
}).findFirst();
|
||||||
}).findFirst();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -145,32 +139,28 @@ public class Java8StreamApiUnitTest {
|
||||||
int reducedTwoParams = IntStream.range(1, 4).reduce(10, (a, b) -> a + b);
|
int reducedTwoParams = IntStream.range(1, 4).reduce(10, (a, b) -> a + b);
|
||||||
assertEquals(16, reducedTwoParams);
|
assertEquals(16, reducedTwoParams);
|
||||||
|
|
||||||
int reducedThreeParams = Stream.of(1, 2, 3)
|
int reducedThreeParams = Stream.of(1, 2, 3).reduce(10, (a, b) -> a + b, (a, b) -> {
|
||||||
.reduce(10, (a, b) -> a + b, (a, b) -> {
|
log.info("combiner was called");
|
||||||
log.info("combiner was called");
|
return a + b;
|
||||||
return a + b;
|
});
|
||||||
});
|
|
||||||
assertEquals(16, reducedThreeParams);
|
assertEquals(16, reducedThreeParams);
|
||||||
|
|
||||||
int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream()
|
int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream().reduce(10, (a, b) -> a + b, (a, b) -> {
|
||||||
.reduce(10, (a, b) -> a + b, (a, b) -> {
|
log.info("combiner was called");
|
||||||
log.info("combiner was called");
|
return a + b;
|
||||||
return a + b;
|
});
|
||||||
});
|
|
||||||
assertEquals(36, reducedThreeParamsParallel);
|
assertEquals(36, reducedThreeParamsParallel);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void collecting_whenAsExpected_thenCorrect() {
|
public void collecting_whenAsExpected_thenCorrect() {
|
||||||
|
|
||||||
List<String> collectorCollection = productList.stream()
|
List<String> collectorCollection = productList.stream().map(Product::getName).collect(Collectors.toList());
|
||||||
.map(Product::getName).collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertTrue(collectorCollection instanceof List);
|
assertTrue(collectorCollection instanceof List);
|
||||||
assertEquals(5, collectorCollection.size());
|
assertEquals(5, collectorCollection.size());
|
||||||
|
|
||||||
String listToString = productList.stream().map(Product::getName)
|
String listToString = productList.stream().map(Product::getName).collect(Collectors.joining(", ", "[", "]"));
|
||||||
.collect(Collectors.joining(", ", "[", "]"));
|
|
||||||
|
|
||||||
assertTrue(listToString.contains(",") && listToString.contains("[") && listToString.contains("]"));
|
assertTrue(listToString.contains(",") && listToString.contains("[") && listToString.contains("]"));
|
||||||
|
|
||||||
|
@ -180,36 +170,29 @@ public class Java8StreamApiUnitTest {
|
||||||
int summingPrice = productList.stream().collect(Collectors.summingInt(Product::getPrice));
|
int summingPrice = productList.stream().collect(Collectors.summingInt(Product::getPrice));
|
||||||
assertEquals(86, summingPrice);
|
assertEquals(86, summingPrice);
|
||||||
|
|
||||||
IntSummaryStatistics statistics = productList.stream()
|
IntSummaryStatistics statistics = productList.stream().collect(Collectors.summarizingInt(Product::getPrice));
|
||||||
.collect(Collectors.summarizingInt(Product::getPrice));
|
|
||||||
assertEquals(23, statistics.getMax());
|
assertEquals(23, statistics.getMax());
|
||||||
|
|
||||||
Map<Integer, List<Product>> collectorMapOfLists = productList.stream()
|
Map<Integer, List<Product>> collectorMapOfLists = productList.stream().collect(Collectors.groupingBy(Product::getPrice));
|
||||||
.collect(Collectors.groupingBy(Product::getPrice));
|
|
||||||
assertEquals(3, collectorMapOfLists.keySet().size());
|
assertEquals(3, collectorMapOfLists.keySet().size());
|
||||||
|
|
||||||
Map<Boolean, List<Product>> mapPartioned = productList.stream()
|
Map<Boolean, List<Product>> mapPartioned = productList.stream().collect(Collectors.partitioningBy(element -> element.getPrice() > 15));
|
||||||
.collect(Collectors.partitioningBy(element -> element.getPrice() > 15));
|
|
||||||
assertEquals(2, mapPartioned.keySet().size());
|
assertEquals(2, mapPartioned.keySet().size());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test(expected = UnsupportedOperationException.class)
|
@Test(expected = UnsupportedOperationException.class)
|
||||||
public void collect_whenThrows_thenCorrect() {
|
public void collect_whenThrows_thenCorrect() {
|
||||||
Set<Product> unmodifiableSet = productList.stream()
|
Set<Product> unmodifiableSet = productList.stream().collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
|
||||||
.collect(Collectors.collectingAndThen(Collectors.toSet(),
|
|
||||||
Collections::unmodifiableSet));
|
|
||||||
unmodifiableSet.add(new Product(4, "tea"));
|
unmodifiableSet.add(new Product(4, "tea"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void customCollector_whenResultContainsAllElementsFrSource_thenCorrect() {
|
public void customCollector_whenResultContainsAllElementsFrSource_thenCorrect() {
|
||||||
Collector<Product, ?, LinkedList<Product>> toLinkedList =
|
Collector<Product, ?, LinkedList<Product>> toLinkedList = Collector.of(LinkedList::new, LinkedList::add, (first, second) -> {
|
||||||
Collector.of(LinkedList::new, LinkedList::add,
|
first.addAll(second);
|
||||||
(first, second) -> {
|
return first;
|
||||||
first.addAll(second);
|
});
|
||||||
return first;
|
|
||||||
});
|
|
||||||
|
|
||||||
LinkedList<Product> linkedListOfPersons = productList.stream().collect(toLinkedList);
|
LinkedList<Product> linkedListOfPersons = productList.stream().collect(toLinkedList);
|
||||||
assertTrue(linkedListOfPersons.containsAll(productList));
|
assertTrue(linkedListOfPersons.containsAll(productList));
|
||||||
|
@ -219,23 +202,20 @@ public class Java8StreamApiUnitTest {
|
||||||
public void parallelStream_whenWorks_thenCorrect() {
|
public void parallelStream_whenWorks_thenCorrect() {
|
||||||
Stream<Product> streamOfCollection = productList.parallelStream();
|
Stream<Product> streamOfCollection = productList.parallelStream();
|
||||||
boolean isParallel = streamOfCollection.isParallel();
|
boolean isParallel = streamOfCollection.isParallel();
|
||||||
boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12)
|
boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12).anyMatch(price -> price > 200);
|
||||||
.anyMatch(price -> price > 200);
|
|
||||||
assertTrue(isParallel && haveBigPrice);
|
assertTrue(isParallel && haveBigPrice);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void parallel_whenIsParallel_thenCorrect() {
|
public void parallel_whenIsParallel_thenCorrect() {
|
||||||
IntStream intStreamParallel =
|
IntStream intStreamParallel = IntStream.range(1, 150).parallel().map(element -> element * 34);
|
||||||
IntStream.range(1, 150).parallel().map(element -> element * 34);
|
|
||||||
boolean isParallel = intStreamParallel.isParallel();
|
boolean isParallel = intStreamParallel.isParallel();
|
||||||
assertTrue(isParallel);
|
assertTrue(isParallel);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void parallel_whenIsSequential_thenCorrect() {
|
public void parallel_whenIsSequential_thenCorrect() {
|
||||||
IntStream intStreamParallel =
|
IntStream intStreamParallel = IntStream.range(1, 150).parallel().map(element -> element * 34);
|
||||||
IntStream.range(1, 150).parallel().map(element -> element * 34);
|
|
||||||
IntStream intStreamSequential = intStreamParallel.sequential();
|
IntStream intStreamSequential = intStreamParallel.sequential();
|
||||||
boolean isParallel = intStreamParallel.isParallel();
|
boolean isParallel = intStreamParallel.isParallel();
|
||||||
assertFalse(isParallel);
|
assertFalse(isParallel);
|
||||||
|
|
|
@ -36,7 +36,7 @@ public class Java8StreamsUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void checkStreamCount_whenCreating_givenDifferentSources() {
|
public void checkStreamCount_whenCreating_givenDifferentSources() {
|
||||||
String[] arr = new String[]{"a", "b", "c"};
|
String[] arr = new String[] { "a", "b", "c" };
|
||||||
Stream<String> streamArr = Arrays.stream(arr);
|
Stream<String> streamArr = Arrays.stream(arr);
|
||||||
assertEquals(streamArr.count(), 3);
|
assertEquals(streamArr.count(), 3);
|
||||||
|
|
||||||
|
@ -47,14 +47,12 @@ public class Java8StreamsUnitTest {
|
||||||
assertEquals(count, 9);
|
assertEquals(count, 9);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void checkStreamCount_whenOperationFilter_thanCorrect() {
|
public void checkStreamCount_whenOperationFilter_thanCorrect() {
|
||||||
Stream<String> streamFilter = list.stream().filter(element -> element.isEmpty());
|
Stream<String> streamFilter = list.stream().filter(element -> element.isEmpty());
|
||||||
assertEquals(streamFilter.count(), 2);
|
assertEquals(streamFilter.count(), 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void checkStreamCount_whenOperationMap_thanCorrect() {
|
public void checkStreamCount_whenOperationMap_thanCorrect() {
|
||||||
List<String> uris = new ArrayList<>();
|
List<String> uris = new ArrayList<>();
|
||||||
|
@ -65,12 +63,10 @@ public class Java8StreamsUnitTest {
|
||||||
List<Detail> details = new ArrayList<>();
|
List<Detail> details = new ArrayList<>();
|
||||||
details.add(new Detail());
|
details.add(new Detail());
|
||||||
details.add(new Detail());
|
details.add(new Detail());
|
||||||
Stream<String> streamFlatMap = details.stream()
|
Stream<String> streamFlatMap = details.stream().flatMap(detail -> detail.getParts().stream());
|
||||||
.flatMap(detail -> detail.getParts().stream());
|
|
||||||
assertEquals(streamFlatMap.count(), 4);
|
assertEquals(streamFlatMap.count(), 4);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void checkStreamCount_whenOperationMatch_thenCorrect() {
|
public void checkStreamCount_whenOperationMatch_thenCorrect() {
|
||||||
boolean isValid = list.stream().anyMatch(element -> element.contains("h"));
|
boolean isValid = list.stream().anyMatch(element -> element.contains("h"));
|
||||||
|
@ -81,7 +77,6 @@ public class Java8StreamsUnitTest {
|
||||||
assertFalse(isValidTwo);
|
assertFalse(isValidTwo);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void checkStreamReducedValue_whenOperationReduce_thenCorrect() {
|
public void checkStreamReducedValue_whenOperationReduce_thenCorrect() {
|
||||||
List<Integer> integers = new ArrayList<>();
|
List<Integer> integers = new ArrayList<>();
|
||||||
|
@ -94,20 +89,17 @@ public class Java8StreamsUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void checkStreamContains_whenOperationCollect_thenCorrect() {
|
public void checkStreamContains_whenOperationCollect_thenCorrect() {
|
||||||
List<String> resultList = list.stream()
|
List<String> resultList = list.stream().map(element -> element.toUpperCase()).collect(Collectors.toList());
|
||||||
.map(element -> element.toUpperCase())
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
assertEquals(resultList.size(), list.size());
|
assertEquals(resultList.size(), list.size());
|
||||||
assertTrue(resultList.contains(""));
|
assertTrue(resultList.contains(""));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void checkParallelStream_whenDoWork() {
|
public void checkParallelStream_whenDoWork() {
|
||||||
list.parallelStream().forEach(element -> doWork(element));
|
list.parallelStream().forEach(element -> doWork(element));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void doWork(String string) {
|
private void doWork(String string) {
|
||||||
assertTrue(true); //just imitate an amount of work
|
assertTrue(true); // just imitate an amount of work
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -46,9 +46,7 @@ public class GuavaThreadPoolIntegrationTest {
|
||||||
ListenableFuture<String> future1 = listeningExecutorService.submit(() -> "Hello");
|
ListenableFuture<String> future1 = listeningExecutorService.submit(() -> "Hello");
|
||||||
ListenableFuture<String> future2 = listeningExecutorService.submit(() -> "World");
|
ListenableFuture<String> future2 = listeningExecutorService.submit(() -> "World");
|
||||||
|
|
||||||
String greeting = Futures.allAsList(future1, future2).get()
|
String greeting = Futures.allAsList(future1, future2).get().stream().collect(Collectors.joining(" "));
|
||||||
.stream()
|
|
||||||
.collect(Collectors.joining(" "));
|
|
||||||
assertEquals("Hello World", greeting);
|
assertEquals("Hello World", greeting);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,6 +7,8 @@ import java.util.List;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.equalshashcode.entities.ComplexClass;
|
||||||
|
|
||||||
public class ComplexClassUnitTest {
|
public class ComplexClassUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -3,6 +3,8 @@ package org.baeldung.equalshashcode.entities;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.equalshashcode.entities.PrimitiveClass;
|
||||||
|
|
||||||
public class PrimitiveClassUnitTest {
|
public class PrimitiveClassUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -5,6 +5,8 @@ import java.awt.Color;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.equalshashcode.entities.Square;
|
||||||
|
|
||||||
public class SquareClassUnitTest {
|
public class SquareClassUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -1,25 +0,0 @@
|
||||||
package com.baeldung.enterprise.patterns.front.controller.filters;
|
|
||||||
|
|
||||||
import javax.servlet.FilterChain;
|
|
||||||
import javax.servlet.ServletException;
|
|
||||||
import javax.servlet.ServletRequest;
|
|
||||||
import javax.servlet.ServletResponse;
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpSession;
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
public class AuditFilter extends BaseFilter {
|
|
||||||
@Override
|
|
||||||
public void doFilter(
|
|
||||||
ServletRequest request,
|
|
||||||
ServletResponse response,
|
|
||||||
FilterChain chain
|
|
||||||
) throws IOException, ServletException {
|
|
||||||
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
|
|
||||||
HttpSession session = httpServletRequest.getSession(false);
|
|
||||||
if (session != null && session.getAttribute("username") != null) {
|
|
||||||
request.setAttribute("username", session.getAttribute("username"));
|
|
||||||
}
|
|
||||||
chain.doFilter(request, response);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,23 +0,0 @@
|
||||||
package com.baeldung.enterprise.patterns.front.controller.filters;
|
|
||||||
|
|
||||||
import javax.servlet.FilterChain;
|
|
||||||
import javax.servlet.ServletException;
|
|
||||||
import javax.servlet.ServletRequest;
|
|
||||||
import javax.servlet.ServletResponse;
|
|
||||||
import javax.servlet.annotation.WebFilter;
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
@WebFilter(servletNames = "front-controller")
|
|
||||||
public class VisitorCounterFilter extends BaseFilter {
|
|
||||||
private int counter;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void doFilter(
|
|
||||||
ServletRequest request,
|
|
||||||
ServletResponse response,
|
|
||||||
FilterChain chain
|
|
||||||
) throws IOException, ServletException {
|
|
||||||
request.setAttribute("counter", ++counter);
|
|
||||||
chain.doFilter(request, response);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -3,6 +3,7 @@ package com.baeldung.patterns.intercepting.filter.commands;
|
||||||
import javax.servlet.ServletException;
|
import javax.servlet.ServletException;
|
||||||
import javax.servlet.http.HttpSession;
|
import javax.servlet.http.HttpSession;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
public class LoginCommand extends FrontCommand {
|
public class LoginCommand extends FrontCommand {
|
||||||
@Override
|
@Override
|
||||||
|
@ -12,10 +13,8 @@ public class LoginCommand extends FrontCommand {
|
||||||
session.setAttribute("username", request.getParameter("username"));
|
session.setAttribute("username", request.getParameter("username"));
|
||||||
response.sendRedirect(request.getParameter("redirect"));
|
response.sendRedirect(request.getParameter("redirect"));
|
||||||
} else {
|
} else {
|
||||||
String queryString = request.getQueryString();
|
String queryString = Optional.ofNullable(request.getQueryString())
|
||||||
if (queryString == null) {
|
.orElse("command=Home");
|
||||||
queryString = "command=Home";
|
|
||||||
}
|
|
||||||
request.setAttribute("redirect", request.getRequestURL()
|
request.setAttribute("redirect", request.getRequestURL()
|
||||||
.append("?").append(queryString).toString());
|
.append("?").append(queryString).toString());
|
||||||
forward("login");
|
forward("login");
|
||||||
|
|
|
@ -3,14 +3,17 @@ package com.baeldung.patterns.intercepting.filter.commands;
|
||||||
import javax.servlet.ServletException;
|
import javax.servlet.ServletException;
|
||||||
import javax.servlet.http.HttpSession;
|
import javax.servlet.http.HttpSession;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
public class LogoutCommand extends FrontCommand {
|
public class LogoutCommand extends FrontCommand {
|
||||||
@Override
|
@Override
|
||||||
public void process() throws ServletException, IOException {
|
public void process() throws ServletException, IOException {
|
||||||
super.process();
|
super.process();
|
||||||
HttpSession session = request.getSession(false);
|
Optional.ofNullable(request.getSession(false))
|
||||||
session.removeAttribute("username");
|
.ifPresent(session -> {
|
||||||
session.removeAttribute("order");
|
session.removeAttribute("username");
|
||||||
|
session.removeAttribute("order");
|
||||||
|
});
|
||||||
response.sendRedirect("/?command=Home");
|
response.sendRedirect("/?command=Home");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,6 +8,7 @@ import com.baeldung.patterns.intercepting.filter.data.OrderImpl;
|
||||||
import javax.servlet.ServletException;
|
import javax.servlet.ServletException;
|
||||||
import javax.servlet.http.HttpSession;
|
import javax.servlet.http.HttpSession;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
public class OrderCommand extends FrontCommand {
|
public class OrderCommand extends FrontCommand {
|
||||||
@Override
|
@Override
|
||||||
|
@ -15,11 +16,10 @@ public class OrderCommand extends FrontCommand {
|
||||||
super.process();
|
super.process();
|
||||||
if (request.getMethod().equals("POST")) {
|
if (request.getMethod().equals("POST")) {
|
||||||
HttpSession session = request.getSession(false);
|
HttpSession session = request.getSession(false);
|
||||||
Order order = (Order) session.getAttribute("order");
|
Order order = Optional
|
||||||
if (order == null) {
|
.ofNullable(session.getAttribute("order"))
|
||||||
String username = (String) session.getAttribute("username");
|
.map(Order.class::cast)
|
||||||
order = new OrderImpl(username);
|
.orElseGet(() -> new OrderImpl((String) session.getAttribute("username")));
|
||||||
}
|
|
||||||
Bookshelf bookshelf = (Bookshelf) request.getServletContext()
|
Bookshelf bookshelf = (Bookshelf) request.getServletContext()
|
||||||
.getAttribute("bookshelf");
|
.getAttribute("bookshelf");
|
||||||
String isbn = request.getParameter("isbn");
|
String isbn = request.getParameter("isbn");
|
||||||
|
|
|
@ -4,6 +4,7 @@ import javax.servlet.*;
|
||||||
import javax.servlet.annotation.WebFilter;
|
import javax.servlet.annotation.WebFilter;
|
||||||
import javax.servlet.annotation.WebInitParam;
|
import javax.servlet.annotation.WebInitParam;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
@WebFilter(
|
@WebFilter(
|
||||||
servletNames = {"intercepting-filter"},
|
servletNames = {"intercepting-filter"},
|
||||||
|
@ -24,10 +25,9 @@ public class EncodingFilter extends BaseFilter {
|
||||||
ServletResponse response,
|
ServletResponse response,
|
||||||
FilterChain chain
|
FilterChain chain
|
||||||
) throws IOException, ServletException {
|
) throws IOException, ServletException {
|
||||||
String encoding = request.getParameter("encoding");
|
String encoding = Optional
|
||||||
if (encoding == null) {
|
.ofNullable(request.getParameter("encoding"))
|
||||||
encoding = this.encoding;
|
.orElse(this.encoding);
|
||||||
}
|
|
||||||
response.setCharacterEncoding(encoding);
|
response.setCharacterEncoding(encoding);
|
||||||
chain.doFilter(request, response);
|
chain.doFilter(request, response);
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,6 +10,7 @@ import javax.servlet.ServletResponse;
|
||||||
import javax.servlet.annotation.WebFilter;
|
import javax.servlet.annotation.WebFilter;
|
||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
@WebFilter(servletNames = "intercepting-filter")
|
@WebFilter(servletNames = "intercepting-filter")
|
||||||
public class LoggingFilter extends BaseFilter {
|
public class LoggingFilter extends BaseFilter {
|
||||||
|
@ -23,10 +24,10 @@ public class LoggingFilter extends BaseFilter {
|
||||||
) throws IOException, ServletException {
|
) throws IOException, ServletException {
|
||||||
chain.doFilter(request, response);
|
chain.doFilter(request, response);
|
||||||
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
|
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
|
||||||
String username = (String) httpServletRequest.getAttribute("username");
|
String username = Optional
|
||||||
if (username == null) {
|
.ofNullable(httpServletRequest.getAttribute("username"))
|
||||||
username = "guest";
|
.map(Object::toString)
|
||||||
}
|
.orElse("guest");
|
||||||
log.info("Request from '{}@{}': {}?{}", username, request.getRemoteAddr(),
|
log.info("Request from '{}@{}': {}?{}", username, request.getRemoteAddr(),
|
||||||
httpServletRequest.getRequestURI(), request.getParameterMap());
|
httpServletRequest.getRequestURI(), request.getParameterMap());
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,6 +5,7 @@ import javax.servlet.http.HttpServletRequest;
|
||||||
import javax.servlet.http.HttpSession;
|
import javax.servlet.http.HttpSession;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
|
import java.util.Optional;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
public class VisitorCounterFilter implements Filter {
|
public class VisitorCounterFilter implements Filter {
|
||||||
|
@ -21,8 +22,9 @@ public class VisitorCounterFilter implements Filter {
|
||||||
FilterChain chain
|
FilterChain chain
|
||||||
) throws IOException, ServletException {
|
) throws IOException, ServletException {
|
||||||
HttpSession session = ((HttpServletRequest) request).getSession(false);
|
HttpSession session = ((HttpServletRequest) request).getSession(false);
|
||||||
String username = (String) session.getAttribute("username");
|
Optional.ofNullable(session.getAttribute("username"))
|
||||||
users.add(username);
|
.map(Object::toString)
|
||||||
|
.ifPresent(users::add);
|
||||||
request.setAttribute("counter", users.size());
|
request.setAttribute("counter", users.size());
|
||||||
chain.doFilter(request, response);
|
chain.doFilter(request, response);
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1 @@
|
||||||
|
/target/
|
|
@ -0,0 +1,87 @@
|
||||||
|
<?xml version="1.0"?>
|
||||||
|
<project
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
|
||||||
|
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
<artifactId>pdf</artifactId>
|
||||||
|
<name>pdf</name>
|
||||||
|
<url>http://maven.apache.org</url>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>3.8.1</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.pdfbox</groupId>
|
||||||
|
<artifactId>pdfbox-tools</artifactId>
|
||||||
|
<version>2.0.3</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>net.sf.cssbox</groupId>
|
||||||
|
<artifactId>pdf2dom</artifactId>
|
||||||
|
<version>1.6</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.itextpdf</groupId>
|
||||||
|
<artifactId>itextpdf</artifactId>
|
||||||
|
<version>5.5.10</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.poi</groupId>
|
||||||
|
<artifactId>poi</artifactId>
|
||||||
|
<version>3.15</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.poi</groupId>
|
||||||
|
<artifactId>poi-scratchpad</artifactId>
|
||||||
|
<version>3.15</version>
|
||||||
|
</dependency>
|
||||||
|
<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>
|
||||||
|
<finalName>pdf</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>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
|
@ -0,0 +1,35 @@
|
||||||
|
package com.baeldung.pdf;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.PrintWriter;
|
||||||
|
import java.io.Writer;
|
||||||
|
|
||||||
|
import javax.xml.parsers.ParserConfigurationException;
|
||||||
|
|
||||||
|
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||||
|
import org.fit.pdfdom.PDFDomTree;
|
||||||
|
|
||||||
|
public class PDF2HTMLExample {
|
||||||
|
|
||||||
|
private static final String FILENAME = "src/main/resources/pdf.pdf";
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
try {
|
||||||
|
generateHTMLFromPDF(FILENAME);
|
||||||
|
} catch (IOException | ParserConfigurationException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void generateHTMLFromPDF(String filename) throws ParserConfigurationException, IOException {
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,35 @@
|
||||||
|
package com.baeldung.pdf;
|
||||||
|
|
||||||
|
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||||
|
import org.apache.pdfbox.rendering.ImageType;
|
||||||
|
import org.apache.pdfbox.rendering.PDFRenderer;
|
||||||
|
import org.apache.pdfbox.tools.imageio.ImageIOUtil;
|
||||||
|
|
||||||
|
import java.awt.image.BufferedImage;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class PDF2ImageExample {
|
||||||
|
|
||||||
|
private static final String FILENAME = "src/main/resources/pdf.pdf";
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
try {
|
||||||
|
generateImageFromPDF(FILENAME, "png");
|
||||||
|
generateImageFromPDF(FILENAME, "jpeg");
|
||||||
|
generateImageFromPDF(FILENAME, "gif");
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void generateImageFromPDF(String filename, String extension) throws IOException {
|
||||||
|
PDDocument document = PDDocument.load(new File(filename));
|
||||||
|
PDFRenderer pdfRenderer = new PDFRenderer(document);
|
||||||
|
for (int page = 0; page < document.getNumberOfPages(); ++page) {
|
||||||
|
BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);
|
||||||
|
ImageIOUtil.writeImage(bim, String.format("src/output/pdf-%d.%s", page + 1, extension), 300);
|
||||||
|
}
|
||||||
|
document.close();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,48 @@
|
||||||
|
package com.baeldung.pdf;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.PrintWriter;
|
||||||
|
|
||||||
|
import org.apache.pdfbox.cos.COSDocument;
|
||||||
|
import org.apache.pdfbox.io.RandomAccessFile;
|
||||||
|
import org.apache.pdfbox.pdfparser.PDFParser;
|
||||||
|
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||||
|
import org.apache.pdfbox.text.PDFTextStripper;
|
||||||
|
|
||||||
|
public class PDF2TextExample {
|
||||||
|
|
||||||
|
private static final String FILENAME = "src/main/resources/pdf.pdf";
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
try {
|
||||||
|
generateTxtFromPDF(FILENAME);
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void generateTxtFromPDF(String filename) throws IOException {
|
||||||
|
File f = new File(filename);
|
||||||
|
String parsedText;
|
||||||
|
PDFParser parser = new PDFParser(new RandomAccessFile(f, "r"));
|
||||||
|
parser.parse();
|
||||||
|
|
||||||
|
COSDocument cosDoc = parser.getDocument();
|
||||||
|
|
||||||
|
PDFTextStripper pdfStripper = new PDFTextStripper();
|
||||||
|
PDDocument pdDoc = new PDDocument(cosDoc);
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,50 @@
|
||||||
|
package com.baeldung.pdf;
|
||||||
|
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import org.apache.poi.xwpf.usermodel.BreakType;
|
||||||
|
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||||
|
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
|
||||||
|
import org.apache.poi.xwpf.usermodel.XWPFRun;
|
||||||
|
|
||||||
|
import com.itextpdf.text.pdf.PdfReader;
|
||||||
|
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
|
||||||
|
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
|
||||||
|
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;
|
||||||
|
|
||||||
|
public class PDF2WordExample {
|
||||||
|
|
||||||
|
private static final String FILENAME = "src/main/resources/pdf.pdf";
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
try {
|
||||||
|
generateDocFromPDF(FILENAME);
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void generateDocFromPDF(String filename) throws IOException {
|
||||||
|
XWPFDocument doc = new XWPFDocument();
|
||||||
|
|
||||||
|
String pdf = filename;
|
||||||
|
PdfReader reader = new PdfReader(pdf);
|
||||||
|
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
|
||||||
|
|
||||||
|
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
|
||||||
|
TextExtractionStrategy strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
|
||||||
|
String text = strategy.getResultantText();
|
||||||
|
XWPFParagraph p = doc.createParagraph();
|
||||||
|
XWPFRun run = p.createRun();
|
||||||
|
run.setText(text);
|
||||||
|
run.addBreak(BreakType.PAGE);
|
||||||
|
}
|
||||||
|
FileOutputStream out = new FileOutputStream("src/output/pdf.docx");
|
||||||
|
doc.write(out);
|
||||||
|
out.close();
|
||||||
|
reader.close();
|
||||||
|
doc.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Binary file not shown.
9
pom.xml
9
pom.xml
|
@ -1,5 +1,5 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
<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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-modules</artifactId>
|
<artifactId>parent-modules</artifactId>
|
||||||
|
@ -95,6 +95,7 @@
|
||||||
<module>spring-data-neo4j</module>
|
<module>spring-data-neo4j</module>
|
||||||
<module>spring-data-redis</module>
|
<module>spring-data-redis</module>
|
||||||
<module>spring-data-rest</module>
|
<module>spring-data-rest</module>
|
||||||
|
<module>spring-dispatcher-servlet</module>
|
||||||
<module>spring-exceptions</module>
|
<module>spring-exceptions</module>
|
||||||
<module>spring-freemarker</module>
|
<module>spring-freemarker</module>
|
||||||
<module>spring-hibernate3</module>
|
<module>spring-hibernate3</module>
|
||||||
|
@ -131,6 +132,7 @@
|
||||||
<module>spring-security-rest-full</module>
|
<module>spring-security-rest-full</module>
|
||||||
<module>spring-security-rest</module>
|
<module>spring-security-rest</module>
|
||||||
<module>spring-security-x509</module>
|
<module>spring-security-x509</module>
|
||||||
|
<module>spring-session</module>
|
||||||
<module>spring-spel</module>
|
<module>spring-spel</module>
|
||||||
<module>spring-thymeleaf</module>
|
<module>spring-thymeleaf</module>
|
||||||
<module>spring-userservice</module>
|
<module>spring-userservice</module>
|
||||||
|
@ -143,6 +145,7 @@
|
||||||
<module>xml</module>
|
<module>xml</module>
|
||||||
<module>xmlunit2</module>
|
<module>xmlunit2</module>
|
||||||
<module>xstream</module>
|
<module>xstream</module>
|
||||||
</modules>
|
<module>pdf</module>
|
||||||
|
</modules>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -11,6 +11,7 @@
|
||||||
<module>spring-cloud-eureka</module>
|
<module>spring-cloud-eureka</module>
|
||||||
<module>spring-cloud-hystrix</module>
|
<module>spring-cloud-hystrix</module>
|
||||||
<module>spring-cloud-bootstrap</module>
|
<module>spring-cloud-bootstrap</module>
|
||||||
|
<module>spring-cloud-ribbon-client</module>
|
||||||
</modules>
|
</modules>
|
||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
|
|
|
@ -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";
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,82 @@
|
||||||
|
<?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>
|
||||||
|
|
||||||
|
<artifactId>spring-dispatcher-servlet</artifactId>
|
||||||
|
<packaging>war</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
<relativePath>..</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.servlet</groupId>
|
||||||
|
<artifactId>javax.servlet-api</artifactId>
|
||||||
|
<version>3.1.0</version>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-webmvc</artifactId>
|
||||||
|
<version>4.3.3.RELEASE</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.thymeleaf</groupId>
|
||||||
|
<artifactId>thymeleaf-spring4</artifactId>
|
||||||
|
<version>3.0.2.RELEASE</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.slf4j</groupId>
|
||||||
|
<artifactId>slf4j-api</artifactId>
|
||||||
|
<version>1.7.21</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.logging.log4j</groupId>
|
||||||
|
<artifactId>log4j-core</artifactId>
|
||||||
|
<version>2.7</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.logging.log4j</groupId>
|
||||||
|
<artifactId>log4j-slf4j-impl</artifactId>
|
||||||
|
<version>2.7</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.5.1</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-war-plugin</artifactId>
|
||||||
|
<version>3.0.0</version>
|
||||||
|
<configuration>
|
||||||
|
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.eclipse.jetty</groupId>
|
||||||
|
<artifactId>jetty-maven-plugin</artifactId>
|
||||||
|
<version>9.3.12.v20160915</version>
|
||||||
|
<configuration>
|
||||||
|
<webApp>
|
||||||
|
<contextPath>/</contextPath>
|
||||||
|
</webApp>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
|
@ -0,0 +1,19 @@
|
||||||
|
package com.baeldung.spring.dispatcher.servlet;
|
||||||
|
|
||||||
|
import com.baeldung.spring.dispatcher.servlet.models.Task;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class RootConfiguration {
|
||||||
|
@Bean
|
||||||
|
public Map<String, List<Task>> taskList() {
|
||||||
|
Map<String, List<Task>> taskMap = new HashMap<>();
|
||||||
|
List<Task> taskList = new ArrayList<>();
|
||||||
|
taskList.add(new Task("Clean the dishes!", new Date()));
|
||||||
|
taskMap.put("Cid", taskList);
|
||||||
|
return taskMap;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
package com.baeldung.spring.dispatcher.servlet;
|
||||||
|
|
||||||
|
import org.springframework.web.context.ContextLoaderListener;
|
||||||
|
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||||
|
import org.springframework.web.servlet.DispatcherServlet;
|
||||||
|
|
||||||
|
import javax.servlet.MultipartConfigElement;
|
||||||
|
import javax.servlet.ServletContext;
|
||||||
|
import javax.servlet.ServletException;
|
||||||
|
import javax.servlet.ServletRegistration;
|
||||||
|
|
||||||
|
public class WebApplicationInitializer implements org.springframework.web.WebApplicationInitializer {
|
||||||
|
@Override
|
||||||
|
public void onStartup(ServletContext servletContext) throws ServletException {
|
||||||
|
AnnotationConfigWebApplicationContext rootContext =
|
||||||
|
new AnnotationConfigWebApplicationContext();
|
||||||
|
rootContext.register(RootConfiguration.class);
|
||||||
|
servletContext.addListener(new ContextLoaderListener(rootContext));
|
||||||
|
AnnotationConfigWebApplicationContext webContext =
|
||||||
|
new AnnotationConfigWebApplicationContext();
|
||||||
|
webContext.register(WebConfiguration.class);
|
||||||
|
DispatcherServlet dispatcherServlet = new DispatcherServlet(webContext);
|
||||||
|
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher",
|
||||||
|
dispatcherServlet);
|
||||||
|
servlet.addMapping("/*");
|
||||||
|
MultipartConfigElement multipartConfigElement =
|
||||||
|
new MultipartConfigElement("/tmp");
|
||||||
|
servlet.setMultipartConfig(multipartConfigElement);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,129 @@
|
||||||
|
package com.baeldung.spring.dispatcher.servlet;
|
||||||
|
|
||||||
|
import org.springframework.context.MessageSource;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.context.support.ResourceBundleMessageSource;
|
||||||
|
import org.springframework.ui.context.support.ResourceBundleThemeSource;
|
||||||
|
import org.springframework.web.multipart.MultipartResolver;
|
||||||
|
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
|
||||||
|
import org.springframework.web.servlet.HandlerExceptionResolver;
|
||||||
|
import org.springframework.web.servlet.LocaleResolver;
|
||||||
|
import org.springframework.web.servlet.ThemeResolver;
|
||||||
|
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||||
|
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||||
|
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||||
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||||
|
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
|
||||||
|
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
|
||||||
|
import org.springframework.web.servlet.theme.CookieThemeResolver;
|
||||||
|
import org.springframework.web.servlet.theme.ThemeChangeInterceptor;
|
||||||
|
import org.thymeleaf.spring4.SpringTemplateEngine;
|
||||||
|
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
|
||||||
|
import org.thymeleaf.templatemode.TemplateMode;
|
||||||
|
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
|
||||||
|
|
||||||
|
import javax.servlet.ServletContext;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@ComponentScan("com.baeldung.spring.dispatcher.servlet.web")
|
||||||
|
@EnableWebMvc
|
||||||
|
public class WebConfiguration extends WebMvcConfigurerAdapter {
|
||||||
|
@Override
|
||||||
|
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||||
|
registry
|
||||||
|
.addResourceHandler("/public/**")
|
||||||
|
.addResourceLocations("/public/");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addInterceptors(InterceptorRegistry registry) {
|
||||||
|
registry.addInterceptor(localeChangeInterceptor());
|
||||||
|
registry.addInterceptor(themeChangeInterceptor());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public ServletContextTemplateResolver templateResolver(ServletContext servletContext) {
|
||||||
|
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext);
|
||||||
|
templateResolver.setPrefix("/WEB-INF/views/");
|
||||||
|
templateResolver.setSuffix(".html");
|
||||||
|
templateResolver.setTemplateMode(TemplateMode.HTML);
|
||||||
|
return templateResolver;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public SpringTemplateEngine templateEngine(ServletContextTemplateResolver templateResolver) {
|
||||||
|
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
|
||||||
|
templateEngine.setTemplateResolver(templateResolver);
|
||||||
|
return templateEngine;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public ThymeleafViewResolver viewResolver(SpringTemplateEngine templateEngine) {
|
||||||
|
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
|
||||||
|
viewResolver.setTemplateEngine(templateEngine);
|
||||||
|
return viewResolver;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public MessageSource messageSource() {
|
||||||
|
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
|
||||||
|
messageSource.setBasename("messages");
|
||||||
|
messageSource.setFallbackToSystemLocale(false);
|
||||||
|
return messageSource;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public LocaleResolver localeResolver() {
|
||||||
|
CookieLocaleResolver localeResolver = new CookieLocaleResolver();
|
||||||
|
localeResolver.setDefaultLocale(Locale.ENGLISH);
|
||||||
|
localeResolver.setCookieName("locale");
|
||||||
|
localeResolver.setCookieMaxAge(-1);
|
||||||
|
return localeResolver;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public LocaleChangeInterceptor localeChangeInterceptor() {
|
||||||
|
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
|
||||||
|
localeChangeInterceptor.setParamName("lang");
|
||||||
|
localeChangeInterceptor.setIgnoreInvalidLocale(true);
|
||||||
|
return localeChangeInterceptor;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public ResourceBundleThemeSource themeSource() {
|
||||||
|
ResourceBundleThemeSource themeSource = new ResourceBundleThemeSource();
|
||||||
|
themeSource.setBasenamePrefix("theme-");
|
||||||
|
themeSource.setFallbackToSystemLocale(false);
|
||||||
|
return themeSource;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public ThemeResolver themeResolver() {
|
||||||
|
CookieThemeResolver themeResolver = new CookieThemeResolver();
|
||||||
|
themeResolver.setDefaultThemeName("robotask");
|
||||||
|
themeResolver.setCookieName("theme");
|
||||||
|
themeResolver.setCookieMaxAge(-1);
|
||||||
|
return themeResolver;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public ThemeChangeInterceptor themeChangeInterceptor() {
|
||||||
|
ThemeChangeInterceptor themeChangeInterceptor = new ThemeChangeInterceptor();
|
||||||
|
themeChangeInterceptor.setParamName("theme");
|
||||||
|
return themeChangeInterceptor;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public MultipartResolver multipartResolver() {
|
||||||
|
return new StandardServletMultipartResolver();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public HandlerExceptionResolver handlerExceptionResolver() {
|
||||||
|
return new ExceptionHandlerExceptionResolver();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,58 @@
|
||||||
|
package com.baeldung.spring.dispatcher.servlet.models;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public class Attachment {
|
||||||
|
private String id;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
public Attachment() {
|
||||||
|
this.id = UUID.randomUUID().toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Attachment(String name, String description) {
|
||||||
|
this();
|
||||||
|
this.name = name;
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(String id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescription() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDescription(String description) {
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) return true;
|
||||||
|
if (o == null || getClass() != o.getClass()) return false;
|
||||||
|
Attachment that = (Attachment) o;
|
||||||
|
return id.equals(that.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return id.hashCode();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,52 @@
|
||||||
|
package com.baeldung.spring.dispatcher.servlet.models;
|
||||||
|
|
||||||
|
import org.springframework.format.annotation.DateTimeFormat;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
public class Task {
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
@DateTimeFormat(pattern = "yyyy-MM-dd'T'hh:mm")
|
||||||
|
private Date due;
|
||||||
|
|
||||||
|
private Set<Attachment> attachments = new HashSet<>();
|
||||||
|
|
||||||
|
public Task() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task(Date due) {
|
||||||
|
this.due = due;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task(String description, Date due) {
|
||||||
|
this.description = description;
|
||||||
|
this.due = due;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescription() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDescription(String description) {
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Date getDue() {
|
||||||
|
return due;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDue(Date due) {
|
||||||
|
this.due = due;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Set<Attachment> getAttachments() {
|
||||||
|
return attachments;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAttachments(Set<Attachment> attachments) {
|
||||||
|
this.attachments = attachments;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
package com.baeldung.spring.dispatcher.servlet.web;
|
||||||
|
|
||||||
|
import org.springframework.core.io.FileSystemResource;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
|
||||||
|
@RequestMapping("/attachments")
|
||||||
|
public interface AttachmentController {
|
||||||
|
@GetMapping("/{attachmentId}")
|
||||||
|
ResponseEntity<FileSystemResource> getAttachment(
|
||||||
|
@PathVariable("attachmentId") String attachmentId,
|
||||||
|
@RequestParam(name = "download", required = false, defaultValue = "false") boolean forcedDownload
|
||||||
|
);
|
||||||
|
}
|
|
@ -0,0 +1,45 @@
|
||||||
|
package com.baeldung.spring.dispatcher.servlet.web;
|
||||||
|
|
||||||
|
import com.baeldung.spring.dispatcher.servlet.models.Task;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.core.io.FileSystemResource;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.stereotype.Controller;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
|
||||||
|
import java.net.URLConnection;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Controller
|
||||||
|
public class AttachmentControllerImpl implements AttachmentController {
|
||||||
|
@Autowired
|
||||||
|
private Map<String, List<Task>> taskMap;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ResponseEntity<FileSystemResource> getAttachment(
|
||||||
|
@PathVariable("attachmentId") String attachmentId,
|
||||||
|
@RequestParam(name = "download", required = false, defaultValue = "false") boolean forcedDownload
|
||||||
|
) {
|
||||||
|
FileSystemResource resource = new FileSystemResource("/tmp/" + attachmentId);
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
taskMap.values().stream()
|
||||||
|
.flatMap(Collection::stream)
|
||||||
|
.flatMap(t -> t.getAttachments().stream())
|
||||||
|
.filter(a -> a.getId().equals(attachmentId))
|
||||||
|
.findFirst()
|
||||||
|
.ifPresent(a -> {
|
||||||
|
headers.add("Content-Disposition",
|
||||||
|
"attachment; filename=" + a.getName());
|
||||||
|
headers.add("Content-Type", forcedDownload ?
|
||||||
|
MediaType.APPLICATION_OCTET_STREAM_VALUE :
|
||||||
|
URLConnection.guessContentTypeFromName(a.getName()));
|
||||||
|
});
|
||||||
|
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,19 @@
|
||||||
|
package com.baeldung.spring.dispatcher.servlet.web;
|
||||||
|
|
||||||
|
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||||
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
|
import org.springframework.web.servlet.ModelAndView;
|
||||||
|
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
|
||||||
|
@ControllerAdvice
|
||||||
|
public class GlobalDefaultExceptionHandler {
|
||||||
|
@ExceptionHandler(Exception.class)
|
||||||
|
public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception e) throws Exception {
|
||||||
|
ModelAndView modelAndView = new ModelAndView();
|
||||||
|
modelAndView.addObject("exception", e);
|
||||||
|
modelAndView.addObject("url", request.getRequestURL());
|
||||||
|
modelAndView.setViewName("error");
|
||||||
|
return modelAndView;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,13 @@
|
||||||
|
package com.baeldung.spring.dispatcher.servlet.web;
|
||||||
|
|
||||||
|
import org.springframework.ui.Model;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
|
||||||
|
@RequestMapping("/")
|
||||||
|
public interface HomeController {
|
||||||
|
@GetMapping("/*")
|
||||||
|
String home(
|
||||||
|
Model model
|
||||||
|
);
|
||||||
|
}
|
|
@ -0,0 +1,25 @@
|
||||||
|
package com.baeldung.spring.dispatcher.servlet.web;
|
||||||
|
|
||||||
|
import com.baeldung.spring.dispatcher.servlet.models.Task;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Controller;
|
||||||
|
import org.springframework.ui.Model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Controller
|
||||||
|
public class HomeControllerImpl implements HomeController {
|
||||||
|
@Autowired
|
||||||
|
private Map<String, List<Task>> taskMap;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String home(Model model) {
|
||||||
|
List<String> users = taskMap.keySet().stream()
|
||||||
|
.sorted()
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
model.addAttribute("users", users);
|
||||||
|
return "home";
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,49 @@
|
||||||
|
package com.baeldung.spring.dispatcher.servlet.web;
|
||||||
|
|
||||||
|
import com.baeldung.spring.dispatcher.servlet.models.Task;
|
||||||
|
import org.springframework.ui.Model;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
@RequestMapping("/tasks")
|
||||||
|
public interface TaskController {
|
||||||
|
@GetMapping("/{username}/list")
|
||||||
|
String listTasks(
|
||||||
|
@PathVariable("username") String username,
|
||||||
|
Model model
|
||||||
|
);
|
||||||
|
|
||||||
|
@GetMapping("/{username}/add")
|
||||||
|
String addTask(
|
||||||
|
@PathVariable("username") String username,
|
||||||
|
Model model
|
||||||
|
);
|
||||||
|
|
||||||
|
@PostMapping("/{username}/add")
|
||||||
|
String addTask(
|
||||||
|
@PathVariable("username") String username,
|
||||||
|
@ModelAttribute Task task
|
||||||
|
);
|
||||||
|
|
||||||
|
@GetMapping("/{username}/get/{id}")
|
||||||
|
String getTask(
|
||||||
|
@PathVariable("username") String username,
|
||||||
|
@PathVariable("id") int id,
|
||||||
|
Model model
|
||||||
|
);
|
||||||
|
|
||||||
|
@GetMapping("/{username}/get/{id}/attach")
|
||||||
|
String attachToTask(
|
||||||
|
@PathVariable("username") String username,
|
||||||
|
@PathVariable("id") int id,
|
||||||
|
Model model
|
||||||
|
);
|
||||||
|
|
||||||
|
@PostMapping("/{username}/get/{id}/attach")
|
||||||
|
String attachToTask(
|
||||||
|
@PathVariable("username") String username,
|
||||||
|
@PathVariable("id") int id,
|
||||||
|
@RequestParam("attachment") MultipartFile attachment,
|
||||||
|
@RequestParam("description") String description
|
||||||
|
);
|
||||||
|
}
|
|
@ -0,0 +1,111 @@
|
||||||
|
package com.baeldung.spring.dispatcher.servlet.web;
|
||||||
|
|
||||||
|
import com.baeldung.spring.dispatcher.servlet.models.Attachment;
|
||||||
|
import com.baeldung.spring.dispatcher.servlet.models.Task;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Controller;
|
||||||
|
import org.springframework.ui.Model;
|
||||||
|
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import java.io.*;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Controller
|
||||||
|
public class TaskControllerImpl implements TaskController {
|
||||||
|
@Autowired
|
||||||
|
private Map<String, List<Task>> taskMap;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String listTasks(
|
||||||
|
@PathVariable("username") String username,
|
||||||
|
Model model
|
||||||
|
) {
|
||||||
|
List<Task> tasks = taskMap.get(username).stream()
|
||||||
|
.sorted(Comparator.comparing(Task::getDue))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
model.addAttribute("username", username);
|
||||||
|
model.addAttribute("tasks", tasks);
|
||||||
|
return "task-list";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String addTask(
|
||||||
|
@PathVariable("username") String username,
|
||||||
|
Model model
|
||||||
|
) {
|
||||||
|
model.addAttribute("username", username);
|
||||||
|
model.addAttribute("task", new Task(new Date()));
|
||||||
|
return "task-add";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String addTask(
|
||||||
|
@PathVariable("username") String username,
|
||||||
|
@ModelAttribute Task task
|
||||||
|
) {
|
||||||
|
List<Task> taskList = taskMap.get(username);
|
||||||
|
if (taskList == null) {
|
||||||
|
taskList = new ArrayList<>();
|
||||||
|
}
|
||||||
|
taskList.add(task);
|
||||||
|
taskMap.put(username, taskList);
|
||||||
|
return "redirect:list";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getTask(
|
||||||
|
@PathVariable("username") String username,
|
||||||
|
@PathVariable("id") int id,
|
||||||
|
Model model
|
||||||
|
) {
|
||||||
|
Task task = taskMap.get(username).get(id);
|
||||||
|
model.addAttribute("username", username);
|
||||||
|
model.addAttribute("id", id);
|
||||||
|
model.addAttribute("task", task);
|
||||||
|
return "task-get";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String attachToTask(
|
||||||
|
@PathVariable("username") String username,
|
||||||
|
@PathVariable("id") int id,
|
||||||
|
Model model
|
||||||
|
) {
|
||||||
|
model.addAttribute("username", username);
|
||||||
|
model.addAttribute("id", id);
|
||||||
|
return "task-attach";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String attachToTask(
|
||||||
|
@PathVariable("username") String username,
|
||||||
|
@PathVariable("id") int id,
|
||||||
|
@RequestParam("attachment") MultipartFile multipartFile,
|
||||||
|
@RequestParam("description") String description
|
||||||
|
) {
|
||||||
|
Task task = taskMap.get(username).get(id);
|
||||||
|
Attachment attachment = new Attachment(multipartFile.getOriginalFilename(),
|
||||||
|
description);
|
||||||
|
task.getAttachments().add(attachment);
|
||||||
|
try (InputStream inputStream =
|
||||||
|
new BufferedInputStream(multipartFile.getInputStream());
|
||||||
|
OutputStream outputStream =
|
||||||
|
new BufferedOutputStream(Files.newOutputStream(
|
||||||
|
Paths.get("/tmp", attachment.getId())))) {
|
||||||
|
byte[] buf = new byte[1024 * 16];
|
||||||
|
int len;
|
||||||
|
while ((len = inputStream.read(buf)) != -1) {
|
||||||
|
outputStream.write(buf, 0, len);
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException("Failed to upload file!", e);
|
||||||
|
}
|
||||||
|
return "redirect:./";
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,14 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Configuration status="WARN">
|
||||||
|
<Appenders>
|
||||||
|
<Console name="Console" target="SYSTEM_OUT">
|
||||||
|
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36}:%n[+] %msg%n"/>
|
||||||
|
</Console>
|
||||||
|
</Appenders>
|
||||||
|
|
||||||
|
<Loggers>
|
||||||
|
<Root level="info">
|
||||||
|
<AppenderRef ref="Console"/>
|
||||||
|
</Root>
|
||||||
|
</Loggers>
|
||||||
|
</Configuration>
|
|
@ -0,0 +1,22 @@
|
||||||
|
home.title=Welcome to TaskTools!
|
||||||
|
task.add.description=description
|
||||||
|
task.add.due=due
|
||||||
|
task.add.header=Adding a task to {0}''s list:
|
||||||
|
task.add.submit=Submit
|
||||||
|
task.add.title={0}: task add
|
||||||
|
task.attach.attachment=attached file
|
||||||
|
task.attach.description=description
|
||||||
|
task.attach.header=task #{0}: attach file
|
||||||
|
task.attach.submit=Submit
|
||||||
|
task.attach.title=#{0}: Attach file
|
||||||
|
task.get.attach=Attach file
|
||||||
|
task.get.attachments=attachments:
|
||||||
|
task.get.download=Download
|
||||||
|
task.get.header=task #{0}:
|
||||||
|
task.get.list=Back
|
||||||
|
task.get.title={0}: task details
|
||||||
|
task.list.add-new=Add new
|
||||||
|
task.list.details=Details
|
||||||
|
task.list.header={0}''s tasks:
|
||||||
|
task.list.home=Home
|
||||||
|
task.list.title={0}: task list
|
|
@ -0,0 +1,22 @@
|
||||||
|
home.title=Willkommen bei TaskTools!
|
||||||
|
task.add.description=Beschreibung
|
||||||
|
task.add.due=f\u00e4llig
|
||||||
|
task.add.header=F\u00fcge eine Aufgabe zu {0}''s Liste hinzu:
|
||||||
|
task.add.submit=Senden
|
||||||
|
task.add.title={0}: Task hinzuf\u00fcgen
|
||||||
|
task.attach.attachment=Angeh\u00e4ngte Datei
|
||||||
|
task.attach.description=Beschreibung
|
||||||
|
task.attach.header=Task #{0}: Datei anh\u00e4ngen
|
||||||
|
task.attach.submit=Senden
|
||||||
|
task.attach.title=#{0}: Datei anh\u00e4ngen
|
||||||
|
task.get.attach=Datei anh\u00e4ngen
|
||||||
|
task.get.attachments=Anh\u00e4nge:
|
||||||
|
task.get.download=Download
|
||||||
|
task.get.header=Task #{0}:
|
||||||
|
task.get.list=Zur\u00fcck
|
||||||
|
task.get.title={0}: Task Details
|
||||||
|
task.list.add-new=Neuer Task
|
||||||
|
task.list.details=Details
|
||||||
|
task.list.header={0}''s Tasks:
|
||||||
|
task.list.home=Startseite
|
||||||
|
task.list.title={0}: Task Liste
|
|
@ -0,0 +1 @@
|
||||||
|
stylesheet=/public/css/themes/post_it.css
|
|
@ -0,0 +1 @@
|
||||||
|
stylesheet=/public/css/themes/robotask.css
|
|
@ -0,0 +1,13 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html xmlns:th="http://www.thymeleaf.org">
|
||||||
|
<head>
|
||||||
|
<title>Error</title>
|
||||||
|
<link rel="stylesheet" type="text/css" href="/public/css/base.css">
|
||||||
|
<link rel="stylesheet" type="text/css" th:href="${#themes.code('stylesheet')}">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h2>Error:</h2>
|
||||||
|
<p th:text="|URL: ${url}|"></p>
|
||||||
|
<p th:text="${exception}"></p>
|
||||||
|
</body>
|
||||||
|
</html>
|
|
@ -0,0 +1,16 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html xmlns:th="http://www.thymeleaf.org">
|
||||||
|
<head>
|
||||||
|
<title th:text="#{home.title}"></title>
|
||||||
|
<link rel="stylesheet" type="text/css" href="/public/css/base.css">
|
||||||
|
<link rel="stylesheet" type="text/css" th:href="${#themes.code('stylesheet')}">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h2>TaskTools</h2>
|
||||||
|
<ul>
|
||||||
|
<li th:each="username : ${users}">
|
||||||
|
<a th:href="@{/tasks/{username}/list(username=${username})}" th:text="${username}"></a>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</body>
|
||||||
|
</html>
|
|
@ -0,0 +1,16 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html xmlns:th="http://www.thymeleaf.org">
|
||||||
|
<head>
|
||||||
|
<title th:text="#{task.add.title(${username})}"></title>
|
||||||
|
<link rel="stylesheet" type="text/css" href="/public/css/base.css">
|
||||||
|
<link rel="stylesheet" type="text/css" th:href="${#themes.code('stylesheet')}">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h2 th:text="#{task.add.header(${username})}"></h2>
|
||||||
|
<form method="post" action="#" th:action="@{/tasks/{username}/add(username=${username})}" th:object="${task}">
|
||||||
|
<input type="text" th:field="*{description}" th:placeholder="#{task.add.description}"/>
|
||||||
|
<input type="datetime-local" th:field="*{due}" th:placeholder="#{task.add.due}"/>
|
||||||
|
<input type="submit" th:value="#{task.add.submit}"/>
|
||||||
|
</form>
|
||||||
|
</body>
|
||||||
|
</html>
|
|
@ -0,0 +1,17 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html xmlns:th="http://www.thymeleaf.org">
|
||||||
|
<head>
|
||||||
|
<title th:text="#{task.attach.title(${id})}"></title>
|
||||||
|
<link rel="stylesheet" type="text/css" href="/public/css/base.css">
|
||||||
|
<link rel="stylesheet" type="text/css" th:href="${#themes.code('stylesheet')}">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h2 th:text="#{task.attach.header(${id})}"></h2>
|
||||||
|
<form method="post" action="#" enctype="multipart/form-data"
|
||||||
|
th:action="@{/tasks/{username}/get/{id}/attach(username=${username},id=${id})}">
|
||||||
|
<input type="file" name="attachment" th:placeholder="#{task.attach.attachment}"/>
|
||||||
|
<input type="text" name="description" th:placeholder="#{task.attach.description}"/>
|
||||||
|
<input type="submit" th:value="#{task.attach.submit}"/>
|
||||||
|
</form>
|
||||||
|
</body>
|
||||||
|
</html>
|
|
@ -0,0 +1,28 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html xmlns:th="http://www.thymeleaf.org">
|
||||||
|
<head>
|
||||||
|
<title th:text="#{task.get.title(${task.description})}"></title>
|
||||||
|
<link rel="stylesheet" type="text/css" href="/public/css/base.css">
|
||||||
|
<link rel="stylesheet" type="text/css" th:href="${#themes.code('stylesheet')}">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h2 th:text="#{task.get.header(${id})}"></h2>
|
||||||
|
<p th:text="${task.due}"></p>
|
||||||
|
<p th:text="${task.description}"></p>
|
||||||
|
<hr/>
|
||||||
|
<p th:text="#{task.get.attachments}"></p>
|
||||||
|
<dl th:each="attachment : ${task.attachments}">
|
||||||
|
<dt><img src="#" th:src="@{/attachments/{id}(id=${attachment.id})}"></dt>
|
||||||
|
<dt>
|
||||||
|
<span th:text="${attachment.name}"></span>
|
||||||
|
<a class="button" th:href="@{/attachments/{id}(id=${attachment.id},download=true)}"
|
||||||
|
th:text="#{task.get.download}"></a>
|
||||||
|
</dt>
|
||||||
|
<dd th:text="${attachment.description}"></dd>
|
||||||
|
</dl>
|
||||||
|
<p>
|
||||||
|
<a th:href="@{/tasks/{username}/list(username=${username})}" th:text="#{task.get.list}"></a>
|
||||||
|
<a th:href="@{/tasks/{username}/get/{id}/attach(username=${username},id=${id})}" th:text="#{task.get.attach}"></a>
|
||||||
|
</p>
|
||||||
|
</body>
|
||||||
|
</html>
|
|
@ -0,0 +1,22 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html xmlns:th="http://www.thymeleaf.org">
|
||||||
|
<head>
|
||||||
|
<title th:text="#{task.list.title(${username})}"></title>
|
||||||
|
<link rel="stylesheet" type="text/css" href="/public/css/base.css">
|
||||||
|
<link rel="stylesheet" type="text/css" th:href="${#themes.code('stylesheet')}">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h2 th:text="#{task.list.header(${username})}"></h2>
|
||||||
|
<ul>
|
||||||
|
<li th:each="task : ${tasks}">
|
||||||
|
<p th:text="*{task.due}"></p>
|
||||||
|
<p th:text="*{task.description}"></p>
|
||||||
|
<a th:href="@{/tasks/{username}/get/{id}(username=${username},id=${taskStat.index})}" th:text="#{task.list.details}"></a>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<p>
|
||||||
|
<a th:href="@{/}" th:text="#{task.list.home}"></a>
|
||||||
|
<a th:href="@{/tasks/{username}/add(username=${username})}" th:text="#{task.list.add-new}"></a>
|
||||||
|
</p>
|
||||||
|
</body>
|
||||||
|
</html>
|
|
@ -0,0 +1,8 @@
|
||||||
|
a.button {
|
||||||
|
-webkit-appearance: button;
|
||||||
|
-moz-appearance: button;
|
||||||
|
appearance: button;
|
||||||
|
text-decoration: none;
|
||||||
|
color: #2196f3;
|
||||||
|
background-color: #e0e0e0;
|
||||||
|
}
|
|
@ -0,0 +1,8 @@
|
||||||
|
@import url('https://fonts.googleapis.com/css?family=Indie+Flower');
|
||||||
|
|
||||||
|
* {
|
||||||
|
font-family: 'Indie Flower', sans-serif;
|
||||||
|
font-size: 18px;
|
||||||
|
color: #ffeb3b;
|
||||||
|
background-color: #212121;
|
||||||
|
}
|
|
@ -0,0 +1,8 @@
|
||||||
|
@import url('https://fonts.googleapis.com/css?family=Roboto');
|
||||||
|
|
||||||
|
* {
|
||||||
|
font-family: Roboto, sans-serif;
|
||||||
|
font-size: 1em;
|
||||||
|
color: #212121;
|
||||||
|
background-color: #fafafa;
|
||||||
|
}
|
|
@ -80,7 +80,7 @@ public class Bar implements Serializable {
|
||||||
@Column(name = "timestamp")
|
@Column(name = "timestamp")
|
||||||
private long timestamp;
|
private long timestamp;
|
||||||
|
|
||||||
@Column(name = "created_date")
|
@Column(name = "created_date", updatable = false, nullable = false)
|
||||||
@CreatedDate
|
@CreatedDate
|
||||||
private long createdDate;
|
private long createdDate;
|
||||||
|
|
||||||
|
|
|
@ -3,11 +3,11 @@
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
<groupId>com.baeldung.samples.spring.integration</groupId>
|
<groupId>com.baeldung.samples.spring.integration</groupId>
|
||||||
<artifactId>baeldungSIsample</artifactId>
|
<artifactId>spring-integration</artifactId>
|
||||||
<version>1.0.0.BUILD-SNAPSHOT</version>
|
<version>1.0.0.BUILD-SNAPSHOT</version>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
<name>Baeldung Spring Intro</name>
|
<name>spring-integration</name>
|
||||||
<url>http://www.springsource.org/spring-integration</url>
|
<url>http://www.springsource.org/spring-integration</url>
|
||||||
|
|
||||||
<prerequisites>
|
<prerequisites>
|
||||||
|
|
|
@ -13,5 +13,12 @@
|
||||||
- [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache)
|
- [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache)
|
||||||
- [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource)
|
- [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource)
|
||||||
|
|
||||||
To ignore "No persistence xml file found in project", you do:
|
### Eclipse Config
|
||||||
Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project"
|
After importing the project into Eclipse, you may see the following error:
|
||||||
|
"No persistence xml file found in project"
|
||||||
|
|
||||||
|
This can be ignored:
|
||||||
|
- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project"
|
||||||
|
Or:
|
||||||
|
- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,51 @@
|
||||||
|
package com.baeldung.web.controller;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.test.context.ContextConfiguration;
|
||||||
|
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||||
|
import org.springframework.test.context.web.WebAppConfiguration;
|
||||||
|
|
||||||
|
import com.baeldung.model.Employee;
|
||||||
|
import com.baeldung.spring.web.config.WebConfig;
|
||||||
|
|
||||||
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
|
@WebAppConfiguration
|
||||||
|
@ContextConfiguration(classes = WebConfig.class)
|
||||||
|
public class EmployeeTestWithoutMockMvc {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private EmployeeController employeeController;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() {
|
||||||
|
employeeController.initEmployees();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenInitEmployees_thenVerifyValuesInitiation() {
|
||||||
|
|
||||||
|
Employee employee1 = employeeController.employeeMap.get(1L);
|
||||||
|
Employee employee2 = employeeController.employeeMap.get(2L);
|
||||||
|
Employee employee3 = employeeController.employeeMap.get(3L);
|
||||||
|
|
||||||
|
Assert.assertTrue(employee1.getId() == 1L);
|
||||||
|
Assert.assertTrue(employee1.getName().equals("John"));
|
||||||
|
Assert.assertTrue(employee1.getContactNumber().equals("223334411"));
|
||||||
|
Assert.assertTrue(employee1.getWorkingArea().equals("rh"));
|
||||||
|
|
||||||
|
Assert.assertTrue(employee2.getId() == 2L);
|
||||||
|
Assert.assertTrue(employee2.getName().equals("Peter"));
|
||||||
|
Assert.assertTrue(employee2.getContactNumber().equals("22001543"));
|
||||||
|
Assert.assertTrue(employee2.getWorkingArea().equals("informatics"));
|
||||||
|
|
||||||
|
Assert.assertTrue(employee3.getId() == 3L);
|
||||||
|
Assert.assertTrue(employee3.getName().equals("Mike"));
|
||||||
|
Assert.assertTrue(employee3.getContactNumber().equals("223334411"));
|
||||||
|
Assert.assertTrue(employee3.getWorkingArea().equals("admin"));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -9,11 +9,11 @@
|
||||||
<servlet-class>
|
<servlet-class>
|
||||||
org.springframework.web.servlet.DispatcherServlet
|
org.springframework.web.servlet.DispatcherServlet
|
||||||
</servlet-class>
|
</servlet-class>
|
||||||
<load-on-startup>1</load-on-startup>
|
|
||||||
<init-param>
|
<init-param>
|
||||||
<param-name>contextConfigLocation</param-name>
|
<param-name>contextConfigLocation</param-name>
|
||||||
<param-value>classpath*:mvc-configuration.xml</param-value>
|
<param-value>classpath*:mvc-configuration.xml</param-value>
|
||||||
</init-param>
|
</init-param>
|
||||||
|
<load-on-startup>1</load-on-startup>
|
||||||
</servlet>
|
</servlet>
|
||||||
|
|
||||||
<servlet-mapping>
|
<servlet-mapping>
|
||||||
|
|
|
@ -0,0 +1,52 @@
|
||||||
|
package com.baeldung.spring.controller;
|
||||||
|
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Controller;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMethod;
|
||||||
|
import org.springframework.web.servlet.ModelAndView;
|
||||||
|
|
||||||
|
@Controller
|
||||||
|
public class ErrorController {
|
||||||
|
|
||||||
|
@RequestMapping(value = "500Error", method = RequestMethod.GET)
|
||||||
|
public void throwRuntimeException() {
|
||||||
|
throw new NullPointerException("Throwing a null pointer exception");
|
||||||
|
}
|
||||||
|
|
||||||
|
@RequestMapping(value = "errors", method = RequestMethod.GET)
|
||||||
|
public ModelAndView renderErrorPage(HttpServletRequest httpRequest) {
|
||||||
|
ModelAndView errorPage = new ModelAndView("errorPage");
|
||||||
|
String errorMsg = "";
|
||||||
|
int httpErrorCode = getErrorCode(httpRequest);
|
||||||
|
|
||||||
|
switch (httpErrorCode) {
|
||||||
|
case 400: {
|
||||||
|
errorMsg = "Http Error Code : 400 . Bad Request";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 401: {
|
||||||
|
errorMsg = "Http Error Code : 401. Unauthorized";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 404: {
|
||||||
|
errorMsg = "Http Error Code : 404. Resource not found";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
// Handle other 4xx error codes.
|
||||||
|
case 500: {
|
||||||
|
errorMsg = "Http Error Code : 500. Internal Server Error";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
// Handle other 5xx error codes.
|
||||||
|
}
|
||||||
|
errorPage.addObject("errorMsg", errorMsg);
|
||||||
|
return errorPage;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int getErrorCode(HttpServletRequest httpRequest) {
|
||||||
|
return (Integer) httpRequest
|
||||||
|
.getAttribute("javax.servlet.error.status_code");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,10 @@
|
||||||
|
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
|
||||||
|
<%@ page session="false"%>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Home</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>${errorMsg}</h1>
|
||||||
|
</body>
|
||||||
|
</html>
|
|
@ -43,4 +43,7 @@
|
||||||
<welcome-file>index.jsp</welcome-file>
|
<welcome-file>index.jsp</welcome-file>
|
||||||
</welcome-file-list>
|
</welcome-file-list>
|
||||||
|
|
||||||
|
<error-page>
|
||||||
|
<location>/errors</location>
|
||||||
|
</error-page>
|
||||||
</web-app>
|
</web-app>
|
|
@ -332,5 +332,17 @@
|
||||||
<com.squareup.okhttp3.version>3.4.1</com.squareup.okhttp3.version>
|
<com.squareup.okhttp3.version>3.4.1</com.squareup.okhttp3.version>
|
||||||
|
|
||||||
</properties>
|
</properties>
|
||||||
|
<reporting>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
|
<artifactId>findbugs-maven-plugin</artifactId>
|
||||||
|
<version>3.0.4</version>
|
||||||
|
<configuration>
|
||||||
|
<effort>Max</effort>
|
||||||
|
<omitVisitors>FindDeadLocalStores,FindNullDeref</omitVisitors>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</reporting>
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -1,18 +1,13 @@
|
||||||
package org.baeldung.okhttp;
|
package org.baeldung.okhttp;
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import okhttp3.*;
|
||||||
import static org.junit.Assert.assertThat;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
import org.junit.Test;
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
import okhttp3.Call;
|
import static org.junit.Assert.fail;
|
||||||
import okhttp3.Callback;
|
|
||||||
import okhttp3.HttpUrl;
|
|
||||||
import okhttp3.OkHttpClient;
|
|
||||||
import okhttp3.Request;
|
|
||||||
import okhttp3.Response;
|
|
||||||
|
|
||||||
public class OkHttpGetLiveTest {
|
public class OkHttpGetLiveTest {
|
||||||
|
|
||||||
|
@ -54,7 +49,7 @@ public class OkHttpGetLiveTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenAsynchronousGetRequest_thenCorrect() {
|
public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException {
|
||||||
|
|
||||||
OkHttpClient client = new OkHttpClient();
|
OkHttpClient client = new OkHttpClient();
|
||||||
|
|
||||||
|
@ -71,8 +66,10 @@ public class OkHttpGetLiveTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
public void onFailure(Call call, IOException e) {
|
public void onFailure(Call call, IOException e) {
|
||||||
|
fail();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Thread.sleep(3000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -37,7 +37,7 @@ public class OkHttpMiscLiveTest {
|
||||||
response.close();
|
response.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test(expected = IOException.class)
|
||||||
public void whenCancelRequest_thenCorrect() throws IOException {
|
public void whenCancelRequest_thenCorrect() throws IOException {
|
||||||
|
|
||||||
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
|
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
|
||||||
|
@ -49,30 +49,22 @@ public class OkHttpMiscLiveTest {
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
final int seconds = 1;
|
final int seconds = 1;
|
||||||
|
|
||||||
final long startNanos = System.nanoTime();
|
final long startNanos = System.nanoTime();
|
||||||
|
|
||||||
final Call call = client.newCall(request);
|
final Call call = client.newCall(request);
|
||||||
|
|
||||||
// Schedule a job to cancel the call in 1 second.
|
// Schedule a job to cancel the call in 1 second.
|
||||||
executor.schedule(new Runnable() {
|
executor.schedule(() -> {
|
||||||
public void run() {
|
|
||||||
|
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);
|
}, seconds, TimeUnit.SECONDS);
|
||||||
|
|
||||||
try {
|
logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f);
|
||||||
|
Response response = call.execute();
|
||||||
logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f);
|
logger.debug("Call completed: " + (System.nanoTime() - startNanos) / 1e9f, response);
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -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
|
|
@ -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>
|
|
@ -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>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue