diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesTest.java new file mode 100644 index 0000000000..a260e84164 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesTest.java @@ -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 getStreamAfterTakeWhileOperation() { + return Stream + .iterate("", s -> s + "s") + .takeWhile(s -> s.length() < 10); + } + + public Stream getStreamAfterDropWhileOperation() { + return Stream + .iterate("", s -> s + "s") + .takeWhile(s -> s.length() < 10) + .dropWhile(s -> !s.contains("sssss")); + } + + @Test + public void testTakeWhileOperation() { + List 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 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 getStream() { + return Stream.iterate(0, i -> i < 10, i -> i + 1); + } + + @Test + public void testIterateOperation() { + List 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 collection = Arrays.asList("A", "B", "C"); + private Map map = new HashMap<>() {{ + put("A", 10); + put("C", 30); + }}; + + private Stream getStreamWithOfNullable() { + return collection.stream() + .flatMap(s -> Stream.ofNullable(map.get(s))); + } + + private Stream getStream() { + return collection.stream() + .flatMap(s -> { + Integer temp = map.get(s); + return temp != null ? Stream.of(temp) : Stream.empty(); + }); + } + + private List testOfNullableFrom(Stream stream) { + List 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()) + ); + + } + + } + +} diff --git a/core-java/0.12457740242410742 b/core-java/0.12457740242410742 new file mode 100644 index 0000000000..e69de29bb2 diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java similarity index 97% rename from core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java rename to core-java/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java index 6329f41252..5a13f505c2 100644 --- a/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java +++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java @@ -1,4 +1,4 @@ -package org.baeldung.equalshashcode.entities; +package com.baeldung.equalshashcode.entities; import java.util.List; import java.util.Set; diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/PrimitiveClass.java similarity index 96% rename from core-java/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java rename to core-java/src/main/java/com/baeldung/equalshashcode/entities/PrimitiveClass.java index ebe005688c..29b280865e 100644 --- a/core-java/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java +++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/PrimitiveClass.java @@ -1,4 +1,4 @@ -package org.baeldung.equalshashcode.entities; +package com.baeldung.equalshashcode.entities; public class PrimitiveClass { diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Rectangle.java similarity index 96% rename from core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java rename to core-java/src/main/java/com/baeldung/equalshashcode/entities/Rectangle.java index 1e1423f0b3..168e3af0c6 100644 --- a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java +++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Rectangle.java @@ -1,4 +1,4 @@ -package org.baeldung.equalshashcode.entities; +package com.baeldung.equalshashcode.entities; public class Rectangle extends Shape { private double width; diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Shape.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Shape.java similarity index 70% rename from core-java/src/main/java/org/baeldung/equalshashcode/entities/Shape.java rename to core-java/src/main/java/com/baeldung/equalshashcode/entities/Shape.java index 3bfc81da8f..628359becf 100644 --- a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Shape.java +++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Shape.java @@ -1,4 +1,4 @@ -package org.baeldung.equalshashcode.entities; +package com.baeldung.equalshashcode.entities; public abstract class Shape { public abstract double area(); diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Square.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java similarity index 96% rename from core-java/src/main/java/org/baeldung/equalshashcode/entities/Square.java rename to core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java index f11e34f0ba..b9125c3e2f 100644 --- a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Square.java +++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java @@ -1,4 +1,4 @@ -package org.baeldung.equalshashcode.entities; +package com.baeldung.equalshashcode.entities; import java.awt.Color; diff --git a/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java b/core-java/src/main/java/com/baeldung/executable/ExecutableMavenJar.java similarity index 86% rename from core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java rename to core-java/src/main/java/com/baeldung/executable/ExecutableMavenJar.java index 09344902b7..6c79e89717 100644 --- a/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java +++ b/core-java/src/main/java/com/baeldung/executable/ExecutableMavenJar.java @@ -1,4 +1,4 @@ -package org.baeldung.executable; +package com.baeldung.executable; import javax.swing.JOptionPane; diff --git a/core-java/src/main/java/com/baeldung/java/conversion/StringConversion.java b/core-java/src/main/java/com/baeldung/java/conversion/StringConversion.java new file mode 100644 index 0000000000..0a0f79566e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/conversion/StringConversion.java @@ -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); + } +} diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java index 1fb9af3a9d..916442533b 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java +++ b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java @@ -24,7 +24,7 @@ public class EchoClient { public String sendEcho(String msg) { DatagramPacket packet = null; try { - buf=msg.getBytes(); + buf = msg.getBytes(); packet = new DatagramPacket(buf, buf.length, address, 4445); socket.send(packet); packet = new DatagramPacket(buf, buf.length); diff --git a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java index 1c034051aa..61f339db58 100644 --- a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java +++ b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java @@ -17,6 +17,11 @@ public class EchoClient { return instance; } + public static void stop() throws IOException { + client.close(); + buffer = null; + } + private EchoClient() { try { client = SocketChannel.open(new InetSocketAddress("localhost", 5454)); @@ -42,5 +47,4 @@ public class EchoClient { return response; } - } diff --git a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java index 1d4e01bbc3..2ed9a27c4c 100644 --- a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java +++ b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java @@ -1,21 +1,19 @@ 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.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.net.InetSocketAddress; -import java.io.File; +import java.util.Set; public class EchoServer { - public static void main(String[] args) - - throws IOException { + public static void main(String[] args) throws IOException { Selector selector = Selector.open(); ServerSocketChannel serverSocket = ServerSocketChannel.open(); serverSocket.bind(new InetSocketAddress("localhost", 5454)); @@ -49,7 +47,6 @@ public class EchoServer { } } - public static Process start() throws IOException, InterruptedException { String javaHome = System.getProperty("java.home"); String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; diff --git a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java index 906d641632..57e1f33280 100644 --- a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java @@ -8,12 +8,12 @@ import org.junit.Assert; import org.junit.Test; public class UseLocalDateTimeUnitTest { - + UseLocalDateTime useLocalDateTime = new UseLocalDateTime(); - + @Test - public void givenString_whenUsingParse_thenLocalDateTime(){ - 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()); + public void givenString_whenUsingParse_thenLocalDateTime() { + 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()); } } diff --git a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java index dcfca792af..8f1997e9e8 100644 --- a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java @@ -8,47 +8,47 @@ import org.junit.Assert; import org.junit.Test; public class UseLocalDateUnitTest { - + UseLocalDate useLocalDate = new UseLocalDate(); - + @Test - public void givenValues_whenUsingFactoryOf_thenLocalDate(){ - Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingFactoryOfMethod(2016,5,10).toString()); + public void givenValues_whenUsingFactoryOf_thenLocalDate() { + Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString()); } - + @Test - public void givenString_whenUsingParse_thenLocalDate(){ - Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString()); + public void givenString_whenUsingParse_thenLocalDate() { + Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString()); } - + @Test - public void whenUsingClock_thenLocalDate(){ - Assert.assertEquals(LocalDate.now(),useLocalDate.getLocalDateFromClock()); + public void whenUsingClock_thenLocalDate() { + Assert.assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock()); } - + @Test - public void givenDate_whenUsingPlus_thenNextDay(){ - Assert.assertEquals(LocalDate.now().plusDays(1),useLocalDate.getNextDay(LocalDate.now())); + public void givenDate_whenUsingPlus_thenNextDay() { + Assert.assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now())); } - + @Test - public void givenDate_whenUsingMinus_thenPreviousDay(){ - Assert.assertEquals(LocalDate.now().minusDays(1),useLocalDate.getPreviousDay(LocalDate.now())); + public void givenDate_whenUsingMinus_thenPreviousDay() { + Assert.assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now())); } - + @Test - public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek(){ - Assert.assertEquals(DayOfWeek.SUNDAY,useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22"))); + public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek() { + Assert.assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22"))); } - + @Test - public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth(){ - Assert.assertEquals(1,useLocalDate.getFirstDayOfMonth().getDayOfMonth()); + public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() { + Assert.assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth()); } - + @Test - public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight(){ - Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"),useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22"))); + public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight() { + Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22"))); } } diff --git a/core-java/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java index 520b79d4bf..996e200ae9 100644 --- a/core-java/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java @@ -6,31 +6,31 @@ import org.junit.Assert; import org.junit.Test; public class UseLocalTimeUnitTest { - + UseLocalTime useLocalTime = new UseLocalTime(); - + @Test - public void givenValues_whenUsingFactoryOf_thenLocalTime(){ - Assert.assertEquals("07:07:07",useLocalTime.getLocalTimeUsingFactoryOfMethod(7,7,7).toString()); + public void givenValues_whenUsingFactoryOf_thenLocalTime() { + Assert.assertEquals("07:07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7, 7).toString()); } - + @Test - public void givenString_whenUsingParse_thenLocalTime(){ - Assert.assertEquals("06:30",useLocalTime.getLocalTimeUsingParseMethod("06:30").toString()); + public void givenString_whenUsingParse_thenLocalTime() { + Assert.assertEquals("06:30", useLocalTime.getLocalTimeUsingParseMethod("06:30").toString()); } - + @Test - public void givenTime_whenAddHour_thenLocalTime(){ - Assert.assertEquals("07:30",useLocalTime.addAnHour(LocalTime.of(6,30)).toString()); + public void givenTime_whenAddHour_thenLocalTime() { + Assert.assertEquals("07:30", useLocalTime.addAnHour(LocalTime.of(6, 30)).toString()); } - + @Test - public void getHourFromLocalTime(){ - Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1,1))); + public void getHourFromLocalTime() { + Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1, 1))); } - + @Test - public void getLocalTimeWithMinuteSetToValue(){ - Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10,10), 20)); + public void getLocalTimeWithMinuteSetToValue() { + Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10, 10), 20)); } } diff --git a/core-java/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java index a060d974ed..7c030c328a 100644 --- a/core-java/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java @@ -7,20 +7,20 @@ import org.junit.Assert; import org.junit.Test; public class UsePeriodUnitTest { - UsePeriod usingPeriod=new UsePeriod(); - + UsePeriod usingPeriod = new UsePeriod(); + @Test - public void givenPeriodAndLocalDate_thenCalculateModifiedDate(){ + public void givenPeriodAndLocalDate_thenCalculateModifiedDate() { Period period = Period.ofDays(1); 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 - public void givenDates_thenGetPeriod(){ + public void givenDates_thenGetPeriod() { LocalDate localDate1 = LocalDate.parse("2007-05-10"); LocalDate localDate2 = LocalDate.parse("2007-05-15"); - + Assert.assertEquals(Period.ofDays(5), usingPeriod.getDifferenceBetweenDates(localDate1, localDate2)); } } diff --git a/core-java/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java index d5652430fe..5fb079b94c 100644 --- a/core-java/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java @@ -8,13 +8,13 @@ import org.junit.Assert; import org.junit.Test; public class UseZonedDateTimeUnitTest { - - UseZonedDateTime zonedDateTime=new UseZonedDateTime(); - + + UseZonedDateTime zonedDateTime = new UseZonedDateTime(); + @Test - public void givenZoneId_thenZonedDateTime(){ - ZoneId zoneId=ZoneId.of("Europe/Paris"); - ZonedDateTime zonedDatetime=zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId); - Assert.assertEquals(zoneId,ZoneId.from(zonedDatetime)); + public void givenZoneId_thenZonedDateTime() { + ZoneId zoneId = ZoneId.of("Europe/Paris"); + ZonedDateTime zonedDatetime = zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId); + Assert.assertEquals(zoneId, ZoneId.from(zonedDatetime)); } } diff --git a/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java b/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java index 0e3ec29dfd..c944dfa6fe 100644 --- a/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java +++ b/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java @@ -32,7 +32,6 @@ public class EncoderDecoderUnitTest { return encoded; } - private String decode(String value) { String decoded = null; try { @@ -59,9 +58,7 @@ public class EncoderDecoderUnitTest { requestParams.put("key2", "value@!$2"); requestParams.put("key3", "value%3"); - String encodedURL = requestParams.keySet().stream() - .map(key -> key + "=" + encodeValue(requestParams.get(key))) - .collect(joining("&", "http://www.baeldung.com?", "")); + String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com?", "")); Assert.assertThat(testUrl, CoreMatchers.is(encodedURL)); } @@ -72,12 +69,9 @@ public class EncoderDecoderUnitTest { String query = url.getQuery(); - String decodedQuery = Arrays.stream(query.split("&")) - .map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1])) - .collect(joining("&")); + String decodedQuery = Arrays.stream(query.split("&")).map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1])).collect(joining("&")); - Assert.assertEquals( - "http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery); + Assert.assertEquals("http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery); } } diff --git a/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java index de60becfce..6cf6ad3551 100644 --- a/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java +++ b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.enums; - import org.junit.Test; import java.util.ArrayList; diff --git a/core-java/src/test/java/com/baeldung/hexToAscii/HexToAscii.java b/core-java/src/test/java/com/baeldung/hexToAscii/HexToAscii.java new file mode 100644 index 0000000000..2a3c4b109e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/hexToAscii/HexToAscii.java @@ -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(); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceManualTest.java b/core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceManualTest.java new file mode 100644 index 0000000000..8635a24f18 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceManualTest.java @@ -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 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 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); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java b/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java index 2ca2d3a0c8..aff851ae4b 100644 --- a/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.java.networking.udp; - import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/core-java/src/test/java/com/baeldung/java/nio/selector/NioEchoIntegrationTest.java b/core-java/src/test/java/com/baeldung/java/nio/selector/NioEchoIntegrationTest.java index 748dc5b9f4..fc64799578 100644 --- a/core-java/src/test/java/com/baeldung/java/nio/selector/NioEchoIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/java/nio/selector/NioEchoIntegrationTest.java @@ -4,19 +4,32 @@ import static org.junit.Assert.assertEquals; import java.io.IOException; +import org.junit.After; +import org.junit.Before; import org.junit.Test; public class NioEchoIntegrationTest { + Process server; + EchoClient client; + + @Before + public void setup() throws IOException, InterruptedException { + server = EchoServer.start(); + client = EchoClient.start(); + } + @Test - public void givenClient_whenServerEchosMessage_thenCorrect() throws IOException, InterruptedException { - Process process = EchoServer.start(); - EchoClient client = EchoClient.start(); + public void givenServerClient_whenServerEchosMessage_thenCorrect() { String resp1 = client.sendMessage("hello"); String resp2 = client.sendMessage("world"); assertEquals("hello", resp1); assertEquals("world", resp2); + } - process.destroy(); + @After + public void teardown() throws IOException { + server.destroy(); + EchoClient.stop(); } } diff --git a/core-java/src/test/java/com/baeldung/java/nio2/FileTest.java b/core-java/src/test/java/com/baeldung/java/nio2/FileTest.java index 4a1ad1da60..64fbb4ae25 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/FileTest.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/FileTest.java @@ -4,7 +4,6 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; -import java.nio.file.CopyOption; import java.nio.file.DirectoryNotEmptyException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; @@ -12,7 +11,7 @@ import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; -import java.util.Date; +import java.util.UUID; import org.junit.Test; @@ -33,7 +32,7 @@ public class FileTest { } @Test - public void givenExistentDirPath_whenConfirmsNotRegularFile_thenCorrect() { + public void givenDirPath_whenConfirmsNotRegularFile_thenCorrect() { Path p = Paths.get(HOME); assertFalse(Files.isRegularFile(p)); } @@ -67,7 +66,7 @@ public class FileTest { // creating file @Test 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); assertFalse(Files.exists(p)); Files.createFile(p); @@ -77,7 +76,7 @@ public class FileTest { @Test 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); assertFalse(Files.exists(p)); Files.createDirectory(p); @@ -89,7 +88,7 @@ public class FileTest { @Test(expected = NoSuchFileException.class) 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); assertFalse(Files.exists(p)); Files.createDirectory(p); @@ -98,7 +97,7 @@ public class FileTest { @Test 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"); assertFalse(Files.exists(dir)); assertFalse(Files.exists(subdir)); @@ -119,7 +118,7 @@ public class FileTest { } @Test - public void givenFilePath_whenCreatesTempFileWithDefaultsNaming_thenCorrect() throws IOException { + public void givenPath_whenCreatesTempFileWithDefaults_thenCorrect() throws IOException { Path p = Paths.get(HOME + "/"); p = Files.createTempFile(p, null, null); // like 8600179353689423985.tmp @@ -148,7 +147,7 @@ public class FileTest { @Test(expected = DirectoryNotEmptyException.class) 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); assertTrue(Files.exists(dir)); 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 { Path p = Paths.get(HOME + "/inexistentFile.txt"); assertFalse(Files.exists(p)); - try { - Files.delete(p); - } catch (IOException e) { - assertTrue(e instanceof NoSuchFileException); - } + Files.delete(p); } @@ -182,8 +177,8 @@ public class FileTest { // copy file @Test public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException { - Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime()); - Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime()); + Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString()); + Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString()); Files.createDirectory(dir1); Files.createDirectory(dir2); Path file1 = dir1.resolve("filetocopy.txt"); @@ -198,8 +193,8 @@ public class FileTest { @Test(expected = FileAlreadyExistsException.class) public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException { - Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime()); - Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime()); + Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString()); + Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString()); Files.createDirectory(dir1); Files.createDirectory(dir2); Path file1 = dir1.resolve("filetocopy.txt"); @@ -215,8 +210,8 @@ public class FileTest { // moving files @Test public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException { - Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime()); - Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime()); + Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString()); + Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString()); Files.createDirectory(dir1); Files.createDirectory(dir2); Path file1 = dir1.resolve("filetocopy.txt"); @@ -232,8 +227,8 @@ public class FileTest { @Test(expected = FileAlreadyExistsException.class) public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException { - Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime()); - Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime()); + Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString()); + Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString()); Files.createDirectory(dir1); Files.createDirectory(dir2); Path file1 = dir1.resolve("filetocopy.txt"); @@ -247,4 +242,5 @@ public class FileTest { assertTrue(Files.exists(file2)); assertFalse(Files.exists(file1)); } + } diff --git a/core-java/src/test/java/com/baeldung/java/nio2/PathTest.java b/core-java/src/test/java/com/baeldung/java/nio2/PathManualTest.java similarity index 99% rename from core-java/src/test/java/com/baeldung/java/nio2/PathTest.java rename to core-java/src/test/java/com/baeldung/java/nio2/PathManualTest.java index 004aeb3deb..acfb2c08e9 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/PathTest.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/PathManualTest.java @@ -13,7 +13,7 @@ import java.util.Date; import org.junit.Test; -public class PathTest { +public class PathManualTest { private static final String HOME = System.getProperty("user.home"); diff --git a/core-java/src/test/java/com/baeldung/java8/Java8ForEachTest.java b/core-java/src/test/java/com/baeldung/java8/Java8ForEachTest.java new file mode 100644 index 0000000000..d9b0aa9d98 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java8/Java8ForEachTest.java @@ -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 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() { + public void accept(String name) { + System.out.println(name); + } + }); + + // Create a Consumer implementation to then use in a forEach method + Consumer 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); + + } + +} diff --git a/core-java/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java b/core-java/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java index d9a72063af..73a10a57f4 100644 --- a/core-java/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java @@ -27,18 +27,14 @@ public class Java8StreamApiUnitTest { @Before public void init() { - productList = Arrays.asList( - new Product(23, "potatoes"), new Product(14, "orange"), - new Product(13, "lemon"), new Product(23, "bread"), - new Product(13, "sugar")); + productList = Arrays.asList(new Product(23, "potatoes"), new Product(14, "orange"), new Product(13, "lemon"), new Product(23, "bread"), new Product(13, "sugar")); } @Test public void checkPipeline_whenStreamOneElementShorter_thenCorrect() { List list = Arrays.asList("abc1", "abc2", "abc3"); - long size = list.stream().skip(1) - .map(element -> element.substring(0, 3)).count(); + long size = list.stream().skip(1).map(element -> element.substring(0, 3)).count(); assertEquals(list.size() - 1, size); } @@ -48,11 +44,10 @@ public class Java8StreamApiUnitTest { List list = Arrays.asList("abc1", "abc2", "abc3"); counter = 0; - long sizeFirst = list.stream() - .skip(2).map(element -> { - wasCalled(); - return element.substring(0, 3); - }).count(); + long sizeFirst = list.stream().skip(2).map(element -> { + wasCalled(); + return element.substring(0, 3); + }).count(); assertEquals(1, counter); counter = 0; @@ -84,7 +79,7 @@ public class Java8StreamApiUnitTest { Stream streamOfArray = Stream.of("a", "b", "c"); assertEquals(3, streamOfArray.count()); - String[] arr = new String[]{"a", "b", "c"}; + String[] arr = new String[] { "a", "b", "c" }; Stream streamOfArrayPart = Arrays.stream(arr, 1, 3); assertEquals(2, streamOfArrayPart.count()); @@ -112,7 +107,7 @@ public class Java8StreamApiUnitTest { } assertEquals("a", streamOfStrings.findFirst().get()); - Stream streamBuilder = Stream.builder().add("a").add("b").add("c").build(); + Stream streamBuilder = Stream. builder().add("a").add("b").add("c").build(); assertEquals(3, streamBuilder.count()); Stream streamGenerated = Stream.generate(() -> "element").limit(10); @@ -126,14 +121,13 @@ public class Java8StreamApiUnitTest { public void runStreamPipeline_whenOrderIsRight_thenCorrect() { List list = Arrays.asList("abc1", "abc2", "abc3"); - Optional stream = list.stream() - .filter(element -> { - log.info("filter() was called"); - return element.contains("2"); - }).map(element -> { - log.info("map() was called"); - return element.toUpperCase(); - }).findFirst(); + Optional stream = list.stream().filter(element -> { + log.info("filter() was called"); + return element.contains("2"); + }).map(element -> { + log.info("map() was called"); + return element.toUpperCase(); + }).findFirst(); } @Test @@ -145,32 +139,28 @@ public class Java8StreamApiUnitTest { int reducedTwoParams = IntStream.range(1, 4).reduce(10, (a, b) -> a + b); assertEquals(16, reducedTwoParams); - int reducedThreeParams = Stream.of(1, 2, 3) - .reduce(10, (a, b) -> a + b, (a, b) -> { - log.info("combiner was called"); - return a + b; - }); + int reducedThreeParams = Stream.of(1, 2, 3).reduce(10, (a, b) -> a + b, (a, b) -> { + log.info("combiner was called"); + return a + b; + }); assertEquals(16, reducedThreeParams); - int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream() - .reduce(10, (a, b) -> a + b, (a, b) -> { - log.info("combiner was called"); - return a + b; - }); + int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream().reduce(10, (a, b) -> a + b, (a, b) -> { + log.info("combiner was called"); + return a + b; + }); assertEquals(36, reducedThreeParamsParallel); } @Test public void collecting_whenAsExpected_thenCorrect() { - List collectorCollection = productList.stream() - .map(Product::getName).collect(Collectors.toList()); + List collectorCollection = productList.stream().map(Product::getName).collect(Collectors.toList()); assertTrue(collectorCollection instanceof List); assertEquals(5, collectorCollection.size()); - String listToString = productList.stream().map(Product::getName) - .collect(Collectors.joining(", ", "[", "]")); + String listToString = productList.stream().map(Product::getName).collect(Collectors.joining(", ", "[", "]")); assertTrue(listToString.contains(",") && listToString.contains("[") && listToString.contains("]")); @@ -180,36 +170,29 @@ public class Java8StreamApiUnitTest { int summingPrice = productList.stream().collect(Collectors.summingInt(Product::getPrice)); assertEquals(86, summingPrice); - IntSummaryStatistics statistics = productList.stream() - .collect(Collectors.summarizingInt(Product::getPrice)); + IntSummaryStatistics statistics = productList.stream().collect(Collectors.summarizingInt(Product::getPrice)); assertEquals(23, statistics.getMax()); - Map> collectorMapOfLists = productList.stream() - .collect(Collectors.groupingBy(Product::getPrice)); + Map> collectorMapOfLists = productList.stream().collect(Collectors.groupingBy(Product::getPrice)); assertEquals(3, collectorMapOfLists.keySet().size()); - Map> mapPartioned = productList.stream() - .collect(Collectors.partitioningBy(element -> element.getPrice() > 15)); + Map> mapPartioned = productList.stream().collect(Collectors.partitioningBy(element -> element.getPrice() > 15)); assertEquals(2, mapPartioned.keySet().size()); } @Test(expected = UnsupportedOperationException.class) public void collect_whenThrows_thenCorrect() { - Set unmodifiableSet = productList.stream() - .collect(Collectors.collectingAndThen(Collectors.toSet(), - Collections::unmodifiableSet)); + Set unmodifiableSet = productList.stream().collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet)); unmodifiableSet.add(new Product(4, "tea")); } @Test public void customCollector_whenResultContainsAllElementsFrSource_thenCorrect() { - Collector> toLinkedList = - Collector.of(LinkedList::new, LinkedList::add, - (first, second) -> { - first.addAll(second); - return first; - }); + Collector> toLinkedList = Collector.of(LinkedList::new, LinkedList::add, (first, second) -> { + first.addAll(second); + return first; + }); LinkedList linkedListOfPersons = productList.stream().collect(toLinkedList); assertTrue(linkedListOfPersons.containsAll(productList)); @@ -219,23 +202,20 @@ public class Java8StreamApiUnitTest { public void parallelStream_whenWorks_thenCorrect() { Stream streamOfCollection = productList.parallelStream(); boolean isParallel = streamOfCollection.isParallel(); - boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12) - .anyMatch(price -> price > 200); + boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12).anyMatch(price -> price > 200); assertTrue(isParallel && haveBigPrice); } @Test public void parallel_whenIsParallel_thenCorrect() { - IntStream intStreamParallel = - IntStream.range(1, 150).parallel().map(element -> element * 34); + IntStream intStreamParallel = IntStream.range(1, 150).parallel().map(element -> element * 34); boolean isParallel = intStreamParallel.isParallel(); assertTrue(isParallel); } @Test public void parallel_whenIsSequential_thenCorrect() { - IntStream intStreamParallel = - IntStream.range(1, 150).parallel().map(element -> element * 34); + IntStream intStreamParallel = IntStream.range(1, 150).parallel().map(element -> element * 34); IntStream intStreamSequential = intStreamParallel.sequential(); boolean isParallel = intStreamParallel.isParallel(); assertFalse(isParallel); diff --git a/core-java/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java b/core-java/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java index fc83553c6e..e40f9f9506 100644 --- a/core-java/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java @@ -36,7 +36,7 @@ public class Java8StreamsUnitTest { @Test public void checkStreamCount_whenCreating_givenDifferentSources() { - String[] arr = new String[]{"a", "b", "c"}; + String[] arr = new String[] { "a", "b", "c" }; Stream streamArr = Arrays.stream(arr); assertEquals(streamArr.count(), 3); @@ -47,14 +47,12 @@ public class Java8StreamsUnitTest { assertEquals(count, 9); } - @Test public void checkStreamCount_whenOperationFilter_thanCorrect() { Stream streamFilter = list.stream().filter(element -> element.isEmpty()); assertEquals(streamFilter.count(), 2); } - @Test public void checkStreamCount_whenOperationMap_thanCorrect() { List uris = new ArrayList<>(); @@ -65,12 +63,10 @@ public class Java8StreamsUnitTest { List details = new ArrayList<>(); details.add(new Detail()); details.add(new Detail()); - Stream streamFlatMap = details.stream() - .flatMap(detail -> detail.getParts().stream()); + Stream streamFlatMap = details.stream().flatMap(detail -> detail.getParts().stream()); assertEquals(streamFlatMap.count(), 4); } - @Test public void checkStreamCount_whenOperationMatch_thenCorrect() { boolean isValid = list.stream().anyMatch(element -> element.contains("h")); @@ -81,7 +77,6 @@ public class Java8StreamsUnitTest { assertFalse(isValidTwo); } - @Test public void checkStreamReducedValue_whenOperationReduce_thenCorrect() { List integers = new ArrayList<>(); @@ -94,20 +89,17 @@ public class Java8StreamsUnitTest { @Test public void checkStreamContains_whenOperationCollect_thenCorrect() { - List resultList = list.stream() - .map(element -> element.toUpperCase()) - .collect(Collectors.toList()); + List resultList = list.stream().map(element -> element.toUpperCase()).collect(Collectors.toList()); assertEquals(resultList.size(), list.size()); assertTrue(resultList.contains("")); } - @Test public void checkParallelStream_whenDoWork() { list.parallelStream().forEach(element -> doWork(element)); } private void doWork(String string) { - assertTrue(true); //just imitate an amount of work + assertTrue(true); // just imitate an amount of work } } diff --git a/core-java/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java b/core-java/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java index fd13a4fd78..550e9dda6f 100644 --- a/core-java/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java @@ -46,9 +46,7 @@ public class GuavaThreadPoolIntegrationTest { ListenableFuture future1 = listeningExecutorService.submit(() -> "Hello"); ListenableFuture future2 = listeningExecutorService.submit(() -> "World"); - String greeting = Futures.allAsList(future1, future2).get() - .stream() - .collect(Collectors.joining(" ")); + String greeting = Futures.allAsList(future1, future2).get().stream().collect(Collectors.joining(" ")); assertEquals("Hello World", greeting); } diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassUnitTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassUnitTest.java index e4866d0078..680a6d57b5 100644 --- a/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassUnitTest.java +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassUnitTest.java @@ -7,6 +7,8 @@ import java.util.List; import org.junit.Assert; import org.junit.Test; +import com.baeldung.equalshashcode.entities.ComplexClass; + public class ComplexClassUnitTest { @Test diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java index 603b0bfbf9..f4e9f2b99f 100644 --- a/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java @@ -3,6 +3,8 @@ package org.baeldung.equalshashcode.entities; import org.junit.Assert; import org.junit.Test; +import com.baeldung.equalshashcode.entities.PrimitiveClass; + public class PrimitiveClassUnitTest { @Test diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java index 0943436883..5c860bd62d 100644 --- a/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java @@ -5,6 +5,8 @@ import java.awt.Color; import org.junit.Assert; import org.junit.Test; +import com.baeldung.equalshashcode.entities.Square; + public class SquareClassUnitTest { @Test diff --git a/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java b/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java index cc042eeca9..bb3abff28d 100644 --- a/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java @@ -77,5 +77,5 @@ public class PizzaUnitTest { pz.deliver(); assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED); } - + } diff --git a/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/AuditFilter.java b/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/AuditFilter.java deleted file mode 100644 index d24c0a94b3..0000000000 --- a/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/AuditFilter.java +++ /dev/null @@ -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); - } -} diff --git a/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/VisitorCounterFilter.java b/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/VisitorCounterFilter.java deleted file mode 100644 index 0ae7cd73fd..0000000000 --- a/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/VisitorCounterFilter.java +++ /dev/null @@ -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); - } -} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LoginCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LoginCommand.java index cbc8ad9498..46a0329112 100644 --- a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LoginCommand.java +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LoginCommand.java @@ -3,6 +3,7 @@ package com.baeldung.patterns.intercepting.filter.commands; import javax.servlet.ServletException; import javax.servlet.http.HttpSession; import java.io.IOException; +import java.util.Optional; public class LoginCommand extends FrontCommand { @Override @@ -12,10 +13,8 @@ public class LoginCommand extends FrontCommand { session.setAttribute("username", request.getParameter("username")); response.sendRedirect(request.getParameter("redirect")); } else { - String queryString = request.getQueryString(); - if (queryString == null) { - queryString = "command=Home"; - } + String queryString = Optional.ofNullable(request.getQueryString()) + .orElse("command=Home"); request.setAttribute("redirect", request.getRequestURL() .append("?").append(queryString).toString()); forward("login"); diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LogoutCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LogoutCommand.java index 3c9475d6af..f309dc5cf3 100644 --- a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LogoutCommand.java +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LogoutCommand.java @@ -3,14 +3,17 @@ package com.baeldung.patterns.intercepting.filter.commands; import javax.servlet.ServletException; import javax.servlet.http.HttpSession; import java.io.IOException; +import java.util.Optional; public class LogoutCommand extends FrontCommand { @Override public void process() throws ServletException, IOException { super.process(); - HttpSession session = request.getSession(false); - session.removeAttribute("username"); - session.removeAttribute("order"); + Optional.ofNullable(request.getSession(false)) + .ifPresent(session -> { + session.removeAttribute("username"); + session.removeAttribute("order"); + }); response.sendRedirect("/?command=Home"); } } diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/OrderCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/OrderCommand.java index e53fcf78dd..a57785669b 100644 --- a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/OrderCommand.java +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/OrderCommand.java @@ -8,6 +8,7 @@ import com.baeldung.patterns.intercepting.filter.data.OrderImpl; import javax.servlet.ServletException; import javax.servlet.http.HttpSession; import java.io.IOException; +import java.util.Optional; public class OrderCommand extends FrontCommand { @Override @@ -15,11 +16,10 @@ public class OrderCommand extends FrontCommand { super.process(); if (request.getMethod().equals("POST")) { HttpSession session = request.getSession(false); - Order order = (Order) session.getAttribute("order"); - if (order == null) { - String username = (String) session.getAttribute("username"); - order = new OrderImpl(username); - } + Order order = Optional + .ofNullable(session.getAttribute("order")) + .map(Order.class::cast) + .orElseGet(() -> new OrderImpl((String) session.getAttribute("username"))); Bookshelf bookshelf = (Bookshelf) request.getServletContext() .getAttribute("bookshelf"); String isbn = request.getParameter("isbn"); diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/EncodingFilter.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/EncodingFilter.java index ef3f95382e..0806aecba3 100644 --- a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/EncodingFilter.java +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/EncodingFilter.java @@ -4,6 +4,7 @@ import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebInitParam; import java.io.IOException; +import java.util.Optional; @WebFilter( servletNames = {"intercepting-filter"}, @@ -24,10 +25,9 @@ public class EncodingFilter extends BaseFilter { ServletResponse response, FilterChain chain ) throws IOException, ServletException { - String encoding = request.getParameter("encoding"); - if (encoding == null) { - encoding = this.encoding; - } + String encoding = Optional + .ofNullable(request.getParameter("encoding")) + .orElse(this.encoding); response.setCharacterEncoding(encoding); chain.doFilter(request, response); } diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/LoggingFilter.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/LoggingFilter.java index 0ebb397938..322592f84e 100644 --- a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/LoggingFilter.java +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/LoggingFilter.java @@ -10,6 +10,7 @@ import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import java.io.IOException; +import java.util.Optional; @WebFilter(servletNames = "intercepting-filter") public class LoggingFilter extends BaseFilter { @@ -23,10 +24,10 @@ public class LoggingFilter extends BaseFilter { ) throws IOException, ServletException { chain.doFilter(request, response); HttpServletRequest httpServletRequest = (HttpServletRequest) request; - String username = (String) httpServletRequest.getAttribute("username"); - if (username == null) { - username = "guest"; - } + String username = Optional + .ofNullable(httpServletRequest.getAttribute("username")) + .map(Object::toString) + .orElse("guest"); log.info("Request from '{}@{}': {}?{}", username, request.getRemoteAddr(), httpServletRequest.getRequestURI(), request.getParameterMap()); } diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/VisitorCounterFilter.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/VisitorCounterFilter.java index 5521b9faee..42551310d3 100644 --- a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/VisitorCounterFilter.java +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/VisitorCounterFilter.java @@ -5,6 +5,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.HashSet; +import java.util.Optional; import java.util.Set; public class VisitorCounterFilter implements Filter { @@ -21,8 +22,9 @@ public class VisitorCounterFilter implements Filter { FilterChain chain ) throws IOException, ServletException { HttpSession session = ((HttpServletRequest) request).getSession(false); - String username = (String) session.getAttribute("username"); - users.add(username); + Optional.ofNullable(session.getAttribute("username")) + .map(Object::toString) + .ifPresent(users::add); request.setAttribute("counter", users.size()); chain.doFilter(request, response); } diff --git a/pdf/.gitignore b/pdf/.gitignore new file mode 100644 index 0000000000..b83d22266a --- /dev/null +++ b/pdf/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/pdf/pom.xml b/pdf/pom.xml new file mode 100644 index 0000000000..311265880d --- /dev/null +++ b/pdf/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + pdf + pdf + http://maven.apache.org + + + UTF-8 + 3.5.1 + + + + + junit + junit + 3.8.1 + test + + + org.apache.pdfbox + pdfbox-tools + 2.0.3 + + + net.sf.cssbox + pdf2dom + 1.6 + + + com.itextpdf + itextpdf + 5.5.10 + + + org.apache.poi + poi + 3.15 + + + org.apache.poi + poi-scratchpad + 3.15 + + + org.apache.xmlgraphics + batik-transcoder + 1.8 + + + org.apache.poi + poi-ooxml + 3.15 + + + + + pdf + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + + diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java b/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java new file mode 100644 index 0000000000..0d38208bab --- /dev/null +++ b/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java @@ -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(); + } + } +} diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java b/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java new file mode 100644 index 0000000000..00778d16c1 --- /dev/null +++ b/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java @@ -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(); + } +} diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java b/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java new file mode 100644 index 0000000000..c5880a4e91 --- /dev/null +++ b/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java @@ -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(); + } + +} diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2WordExample.java b/pdf/src/main/java/com/baeldung/pdf/PDF2WordExample.java new file mode 100644 index 0000000000..1f416592ef --- /dev/null +++ b/pdf/src/main/java/com/baeldung/pdf/PDF2WordExample.java @@ -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(); + } + +} diff --git a/pdf/src/main/resources/pdf.pdf b/pdf/src/main/resources/pdf.pdf new file mode 100644 index 0000000000..f45d226b39 Binary files /dev/null and b/pdf/src/main/resources/pdf.pdf differ diff --git a/pom.xml b/pom.xml index 82aa022269..857922310f 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,5 @@ - + + 4.0.0 com.baeldung parent-modules @@ -95,6 +95,7 @@ spring-data-neo4j spring-data-redis spring-data-rest + spring-dispatcher-servlet spring-exceptions spring-freemarker spring-hibernate3 @@ -131,6 +132,7 @@ spring-security-rest-full spring-security-rest spring-security-x509 + spring-session spring-spel spring-thymeleaf spring-userservice @@ -143,6 +145,7 @@ xml xmlunit2 xstream - + pdf + - + \ No newline at end of file diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 2349613def..455a5b876b 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -11,6 +11,7 @@ spring-cloud-eureka spring-cloud-hystrix spring-cloud-bootstrap + spring-cloud-ribbon-client pom diff --git a/spring-cloud/spring-cloud-ribbon-client/pom.xml b/spring-cloud/spring-cloud-ribbon-client/pom.xml new file mode 100644 index 0000000000..c597c5ab8e --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/pom.xml @@ -0,0 +1,79 @@ + + 4.0.0 + com.baeldung + spring-cloud-ribbon + 0.0.1-SNAPSHOT + jar + spring-cloud-ribbon-client + Introduction to Spring Cloud Rest Client with Netflix Ribbon + + + org.springframework.boot + spring-boot-starter-parent + 1.4.1.RELEASE + + + + + UTF-8 + 1.8 + + + + + org.springframework.cloud + spring-cloud-starter-ribbon + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Camden.SR1 + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-ribbon-client/src/main/java/com/baeldung/spring/cloud/ribbon/client/RibbonConfiguration.java b/spring-cloud/spring-cloud-ribbon-client/src/main/java/com/baeldung/spring/cloud/ribbon/client/RibbonConfiguration.java new file mode 100644 index 0000000000..59998432ad --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/src/main/java/com/baeldung/spring/cloud/ribbon/client/RibbonConfiguration.java @@ -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(); + } + +} diff --git a/spring-cloud/spring-cloud-ribbon-client/src/main/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationApp.java b/spring-cloud/spring-cloud-ribbon-client/src/main/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationApp.java new file mode 100644 index 0000000000..6105e2c489 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/src/main/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationApp.java @@ -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); + } +} diff --git a/spring-cloud/spring-cloud-ribbon-client/src/main/resources/application.yml b/spring-cloud/spring-cloud-ribbon-client/src/main/resources/application.yml new file mode 100644 index 0000000000..189a923c6c --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/src/main/resources/application.yml @@ -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 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-ribbon-client/src/test/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationAppTests.java b/spring-cloud/spring-cloud-ribbon-client/src/test/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationAppTests.java new file mode 100644 index 0000000000..b3606537a2 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/src/test/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationAppTests.java @@ -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 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"); + } +} diff --git a/spring-cloud/spring-cloud-ribbon-client/src/test/java/com/baeldung/spring/cloud/ribbon/client/TestConfig.java b/spring-cloud/spring-cloud-ribbon-client/src/test/java/com/baeldung/spring/cloud/ribbon/client/TestConfig.java new file mode 100644 index 0000000000..886b28a32e --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/src/test/java/com/baeldung/spring/cloud/ribbon/client/TestConfig.java @@ -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"; + } +} diff --git a/spring-dispatcher-servlet/pom.xml b/spring-dispatcher-servlet/pom.xml new file mode 100644 index 0000000000..646db663db --- /dev/null +++ b/spring-dispatcher-servlet/pom.xml @@ -0,0 +1,82 @@ + + + 4.0.0 + + spring-dispatcher-servlet + war + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + org.springframework + spring-webmvc + 4.3.3.RELEASE + + + org.thymeleaf + thymeleaf-spring4 + 3.0.2.RELEASE + + + org.slf4j + slf4j-api + 1.7.21 + + + org.apache.logging.log4j + log4j-core + 2.7 + + + org.apache.logging.log4j + log4j-slf4j-impl + 2.7 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-war-plugin + 3.0.0 + + false + + + + org.eclipse.jetty + jetty-maven-plugin + 9.3.12.v20160915 + + + / + + + + + + diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/RootConfiguration.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/RootConfiguration.java new file mode 100644 index 0000000000..48281c5e5d --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/RootConfiguration.java @@ -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> taskList() { + Map> taskMap = new HashMap<>(); + List taskList = new ArrayList<>(); + taskList.add(new Task("Clean the dishes!", new Date())); + taskMap.put("Cid", taskList); + return taskMap; + } +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/WebApplicationInitializer.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/WebApplicationInitializer.java new file mode 100644 index 0000000000..016e4a8b4c --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/WebApplicationInitializer.java @@ -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); + } +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/WebConfiguration.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/WebConfiguration.java new file mode 100644 index 0000000000..419c1a2908 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/WebConfiguration.java @@ -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(); + } +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/models/Attachment.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/models/Attachment.java new file mode 100644 index 0000000000..1d6248650f --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/models/Attachment.java @@ -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(); + } +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/models/Task.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/models/Task.java new file mode 100644 index 0000000000..1e6a533e3a --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/models/Task.java @@ -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 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 getAttachments() { + return attachments; + } + + public void setAttachments(Set attachments) { + this.attachments = attachments; + } +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/AttachmentController.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/AttachmentController.java new file mode 100644 index 0000000000..2521004ff1 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/AttachmentController.java @@ -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 getAttachment( + @PathVariable("attachmentId") String attachmentId, + @RequestParam(name = "download", required = false, defaultValue = "false") boolean forcedDownload + ); +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/AttachmentControllerImpl.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/AttachmentControllerImpl.java new file mode 100644 index 0000000000..75a15cf657 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/AttachmentControllerImpl.java @@ -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> taskMap; + + @Override + public ResponseEntity 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); + } +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/GlobalDefaultExceptionHandler.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/GlobalDefaultExceptionHandler.java new file mode 100644 index 0000000000..f25eb601a7 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/GlobalDefaultExceptionHandler.java @@ -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; + } +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/HomeController.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/HomeController.java new file mode 100644 index 0000000000..5ac39fadb4 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/HomeController.java @@ -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 + ); +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/HomeControllerImpl.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/HomeControllerImpl.java new file mode 100644 index 0000000000..66d869ca67 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/HomeControllerImpl.java @@ -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> taskMap; + + @Override + public String home(Model model) { + List users = taskMap.keySet().stream() + .sorted() + .collect(Collectors.toList()); + model.addAttribute("users", users); + return "home"; + } +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/TaskController.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/TaskController.java new file mode 100644 index 0000000000..eff93ffb2f --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/TaskController.java @@ -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 + ); +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/TaskControllerImpl.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/TaskControllerImpl.java new file mode 100644 index 0000000000..464e58aa54 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/TaskControllerImpl.java @@ -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> taskMap; + + @Override + public String listTasks( + @PathVariable("username") String username, + Model model + ) { + List 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 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:./"; + } +} diff --git a/spring-dispatcher-servlet/src/main/resources/log4j2.xml b/spring-dispatcher-servlet/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..fb18e8279a --- /dev/null +++ b/spring-dispatcher-servlet/src/main/resources/log4j2.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/spring-dispatcher-servlet/src/main/resources/messages.properties b/spring-dispatcher-servlet/src/main/resources/messages.properties new file mode 100644 index 0000000000..c36eb5aa42 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/resources/messages.properties @@ -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 diff --git a/spring-dispatcher-servlet/src/main/resources/messages_de.properties b/spring-dispatcher-servlet/src/main/resources/messages_de.properties new file mode 100644 index 0000000000..184b72101c --- /dev/null +++ b/spring-dispatcher-servlet/src/main/resources/messages_de.properties @@ -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 diff --git a/spring-dispatcher-servlet/src/main/resources/theme-post_it.properties b/spring-dispatcher-servlet/src/main/resources/theme-post_it.properties new file mode 100644 index 0000000000..d2998e2bdf --- /dev/null +++ b/spring-dispatcher-servlet/src/main/resources/theme-post_it.properties @@ -0,0 +1 @@ +stylesheet=/public/css/themes/post_it.css diff --git a/spring-dispatcher-servlet/src/main/resources/theme-robotask.properties b/spring-dispatcher-servlet/src/main/resources/theme-robotask.properties new file mode 100644 index 0000000000..68fe270b64 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/resources/theme-robotask.properties @@ -0,0 +1 @@ +stylesheet=/public/css/themes/robotask.css diff --git a/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/error.html b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/error.html new file mode 100644 index 0000000000..8f0f6afca7 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/error.html @@ -0,0 +1,13 @@ + + + + Error + + + + +

Error:

+

+

+ + diff --git a/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/home.html b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/home.html new file mode 100644 index 0000000000..6adec7bb12 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/home.html @@ -0,0 +1,16 @@ + + + + + + + + +

TaskTools

+
    +
  • + +
  • +
+ + diff --git a/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-add.html b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-add.html new file mode 100644 index 0000000000..520486f52e --- /dev/null +++ b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-add.html @@ -0,0 +1,16 @@ + + + + + + + + +

+
+ + + +
+ + diff --git a/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-attach.html b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-attach.html new file mode 100644 index 0000000000..23246f330b --- /dev/null +++ b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-attach.html @@ -0,0 +1,17 @@ + + + + + + + + +

+
+ + + +
+ + diff --git a/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-get.html b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-get.html new file mode 100644 index 0000000000..e7b35b6780 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-get.html @@ -0,0 +1,28 @@ + + + + + + + + +

+

+

+
+

+
+
+
+ + +
+
+
+

+ + +

+ + diff --git a/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-list.html b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-list.html new file mode 100644 index 0000000000..0671f24ba3 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-list.html @@ -0,0 +1,22 @@ + + + + + + + + +

+
    +
  • +

    +

    + +
  • +
+

+ + +

+ + diff --git a/spring-dispatcher-servlet/src/main/webapp/public/css/base.css b/spring-dispatcher-servlet/src/main/webapp/public/css/base.css new file mode 100644 index 0000000000..4d3c2597cf --- /dev/null +++ b/spring-dispatcher-servlet/src/main/webapp/public/css/base.css @@ -0,0 +1,8 @@ +a.button { + -webkit-appearance: button; + -moz-appearance: button; + appearance: button; + text-decoration: none; + color: #2196f3; + background-color: #e0e0e0; +} diff --git a/spring-dispatcher-servlet/src/main/webapp/public/css/themes/post_it.css b/spring-dispatcher-servlet/src/main/webapp/public/css/themes/post_it.css new file mode 100644 index 0000000000..578781ec83 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/webapp/public/css/themes/post_it.css @@ -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; +} diff --git a/spring-dispatcher-servlet/src/main/webapp/public/css/themes/robotask.css b/spring-dispatcher-servlet/src/main/webapp/public/css/themes/robotask.css new file mode 100644 index 0000000000..8c0121b536 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/webapp/public/css/themes/robotask.css @@ -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; +} diff --git a/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Bar.java b/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Bar.java index efc6367116..c7f05254cc 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Bar.java +++ b/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Bar.java @@ -80,7 +80,7 @@ public class Bar implements Serializable { @Column(name = "timestamp") private long timestamp; - @Column(name = "created_date") + @Column(name = "created_date", updatable = false, nullable = false) @CreatedDate private long createdDate; diff --git a/spring-integration/pom.xml b/spring-integration/pom.xml index 251322295f..b33f8bd740 100644 --- a/spring-integration/pom.xml +++ b/spring-integration/pom.xml @@ -3,11 +3,11 @@ 4.0.0 com.baeldung.samples.spring.integration - baeldungSIsample + spring-integration 1.0.0.BUILD-SNAPSHOT jar - Baeldung Spring Intro + spring-integration http://www.springsource.org/spring-integration diff --git a/spring-jpa/README.md b/spring-jpa/README.md index bc768bee22..30b39e1a4e 100644 --- a/spring-jpa/README.md +++ b/spring-jpa/README.md @@ -13,5 +13,12 @@ - [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) -To ignore "No persistence xml file found in project", you do: -Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" +### Eclipse Config +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 + diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTestWithoutMockMvc.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTestWithoutMockMvc.java new file mode 100644 index 0000000000..19806e0559 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTestWithoutMockMvc.java @@ -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")); + } + +} diff --git a/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/web.xml b/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/web.xml index 9bebc263be..5c7a0b52d4 100644 --- a/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/web.xml +++ b/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/web.xml @@ -9,11 +9,11 @@ org.springframework.web.servlet.DispatcherServlet - 1 contextConfigLocation classpath*:mvc-configuration.xml + 1 diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ErrorController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ErrorController.java new file mode 100644 index 0000000000..96556bd5b1 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ErrorController.java @@ -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"); + } +} diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/errorPage.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/errorPage.jsp new file mode 100644 index 0000000000..ba8a836285 --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/errorPage.jsp @@ -0,0 +1,10 @@ +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> +<%@ page session="false"%> + + + Home + + +

${errorMsg}

+ + diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml index 29608a17ef..2240ac0a22 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml @@ -43,4 +43,7 @@ index.jsp + + /errors + \ No newline at end of file diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 69ab4ed361..6580f5ecc7 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -332,5 +332,17 @@ 3.4.1 - + + + + org.codehaus.mojo + findbugs-maven-plugin + 3.0.4 + + Max + FindDeadLocalStores,FindNullDeref + + + + diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java index 9a49c8d9a2..9bf57c41b2 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java @@ -1,18 +1,13 @@ package org.baeldung.okhttp; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import okhttp3.*; +import org.junit.Test; import java.io.IOException; -import org.junit.Test; - -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; public class OkHttpGetLiveTest { @@ -54,7 +49,7 @@ public class OkHttpGetLiveTest { } @Test - public void whenAsynchronousGetRequest_thenCorrect() { + public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException { OkHttpClient client = new OkHttpClient(); @@ -71,8 +66,10 @@ public class OkHttpGetLiveTest { } public void onFailure(Call call, IOException e) { - + fail(); } }); + + Thread.sleep(3000); } } diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java index c44500f4be..dcdb4e328c 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java @@ -37,7 +37,7 @@ public class OkHttpMiscLiveTest { response.close(); } - @Test + @Test(expected = IOException.class) public void whenCancelRequest_thenCorrect() throws IOException { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); @@ -49,30 +49,22 @@ public class OkHttpMiscLiveTest { .build(); final int seconds = 1; - final long startNanos = System.nanoTime(); + final Call call = client.newCall(request); // Schedule a job to cancel the call in 1 second. - executor.schedule(new Runnable() { - public void run() { + executor.schedule(() -> { + + logger.debug("Canceling call: " + (System.nanoTime() - startNanos) / 1e9f); + call.cancel(); + logger.debug("Canceled call: " + (System.nanoTime() - startNanos) / 1e9f); - logger.debug("Canceling call: " + (System.nanoTime() - startNanos) / 1e9f); - call.cancel(); - logger.debug("Canceled call: " + (System.nanoTime() - startNanos) / 1e9f); - } }, seconds, TimeUnit.SECONDS); - try { - - logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f); - Response response = call.execute(); - logger.debug("Call was expected to fail, but completed: " + (System.nanoTime() - startNanos) / 1e9f, response); - - } catch (IOException e) { - - logger.debug("Call failed as expected: " + (System.nanoTime() - startNanos) / 1e9f, e); - } + logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f); + Response response = call.execute(); + logger.debug("Call completed: " + (System.nanoTime() - startNanos) / 1e9f, response); } @Test diff --git a/spring-session/jetty-session-demo/pom.xml b/spring-session/jetty-session-demo/pom.xml new file mode 100644 index 0000000000..86a8596862 --- /dev/null +++ b/spring-session/jetty-session-demo/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + + com.baeldung + jetty-session-demo + 1.0.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + + org.springframework.boot + spring-boot-starter-jetty + + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.session + spring-session + + + org.springframework.boot + spring-boot-starter-web + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.RELEASE + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 1.8 + 1.8 + + + + + \ No newline at end of file diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java new file mode 100644 index 0000000000..7bbc776eaa --- /dev/null +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java @@ -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 ""; + } +} diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java new file mode 100644 index 0000000000..6ed7df9218 --- /dev/null +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java @@ -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"); + } +} diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java new file mode 100644 index 0000000000..f261f66f9d --- /dev/null +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java @@ -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(); + } +} diff --git a/spring-session/jetty-session-demo/src/main/resources/application.properties b/spring-session/jetty-session-demo/src/main/resources/application.properties new file mode 100644 index 0000000000..7f81672eda --- /dev/null +++ b/spring-session/jetty-session-demo/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8081 +spring.redis.host=localhost +spring.redis.port=6379 \ No newline at end of file diff --git a/spring-session/pom.xml b/spring-session/pom.xml new file mode 100644 index 0000000000..fec6a46af2 --- /dev/null +++ b/spring-session/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + spring-session + 1.0.0-SNAPSHOT + pom + + + jetty-session-demo + tomcat-session-demo + + \ No newline at end of file diff --git a/spring-session/tomcat-session-demo/pom.xml b/spring-session/tomcat-session-demo/pom.xml new file mode 100644 index 0000000000..805d7bec25 --- /dev/null +++ b/spring-session/tomcat-session-demo/pom.xml @@ -0,0 +1,66 @@ + + + 4.0.0 + + com.baeldung + tomcat-session-demo + 1.0.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.session + spring-session + + + org.springframework.boot + spring-boot-starter-web + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.RELEASE + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 1.8 + 1.8 + + + + + \ No newline at end of file diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java new file mode 100644 index 0000000000..3e419b27a2 --- /dev/null +++ b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java @@ -0,0 +1,31 @@ +package com.baeldung.spring.session.tomcatex; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("user").password("password").roles("USER").and() + .withUser("admin").password("password").roles("ADMIN"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .httpBasic().and() + .authorizeRequests() + .antMatchers("/").permitAll() + .antMatchers("/tomcat").hasRole("USER") + .antMatchers("/tomcat/admin").hasRole("ADMIN") + .anyRequest().authenticated(); + } +} diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java new file mode 100644 index 0000000000..5afac6cb6b --- /dev/null +++ b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java @@ -0,0 +1,10 @@ +package com.baeldung.spring.session.tomcatex; + +import org.springframework.context.annotation.Configuration; +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; +import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; + +@Configuration +@EnableRedisHttpSession +public class SessionConfig extends AbstractHttpSessionApplicationInitializer { +} diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java new file mode 100644 index 0000000000..58c6b807ec --- /dev/null +++ b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.session.tomcatex; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@SpringBootApplication +@RestController +public class TomcatWebApplication { + public static void main(String[] args) { + SpringApplication.run(TomcatWebApplication.class, args); + } + + @RequestMapping + public String helloDefault() { + return "hello default"; + } + + @RequestMapping("/tomcat") + public String helloTomcat() { + return "hello tomcat"; + } + + @RequestMapping("/tomcat/admin") + public String helloTomcatAdmin() { + return "hello tomcat admin"; + } +} diff --git a/spring-session/tomcat-session-demo/src/main/resources/application.properties b/spring-session/tomcat-session-demo/src/main/resources/application.properties new file mode 100644 index 0000000000..49886b3b70 --- /dev/null +++ b/spring-session/tomcat-session-demo/src/main/resources/application.properties @@ -0,0 +1,2 @@ +spring.redis.host=localhost +spring.redis.port=6379 \ No newline at end of file diff --git a/spring-social-login/pom.xml b/spring-social-login/pom.xml new file mode 100644 index 0000000000..6e74b1c3d1 --- /dev/null +++ b/spring-social-login/pom.xml @@ -0,0 +1,169 @@ + + 4.0.0 + spring-social-login + + spring-social-login + war + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + + org.springframework.security + spring-security-web + + + + org.springframework.security + spring-security-config + + + + org.springframework.security + spring-security-taglibs + + + + org.thymeleaf.extras + thymeleaf-extras-springsecurity4 + + + + + org.springframework.social + spring-social-facebook + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + + + + + org.springframework.boot + spring-boot-starter-test + + + + org.springframework + spring-test + test + + + + junit + junit + test + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + + + + spring-social-login + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-war-plugin + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + + + 1.8 + 3.3.2 + + + \ No newline at end of file diff --git a/spring-social-login/src/main/java/org/baeldung/config/Application.java b/spring-social-login/src/main/java/org/baeldung/config/Application.java new file mode 100644 index 0000000000..cf6251a51e --- /dev/null +++ b/spring-social-login/src/main/java/org/baeldung/config/Application.java @@ -0,0 +1,18 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +@SpringBootApplication +@EnableJpaRepositories("org.baeldung.persistence.dao") +@EntityScan("org.baeldung.persistence.model") +public class Application extends SpringBootServletInitializer { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} \ No newline at end of file diff --git a/spring-social-login/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-social-login/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..8e439653a9 --- /dev/null +++ b/spring-social-login/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,61 @@ +package org.baeldung.config; + +import org.baeldung.security.FacebookSignInAdapter; +import org.baeldung.security.FacebookConnectionSignup; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.social.connect.ConnectionFactoryLocator; +import org.springframework.social.connect.UsersConnectionRepository; +import org.springframework.social.connect.mem.InMemoryUsersConnectionRepository; +import org.springframework.social.connect.web.ProviderSignInController; + +@Configuration +@EnableWebSecurity +@ComponentScan(basePackages = { "org.baeldung.security" }) +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private UserDetailsService userDetailsService; + + @Autowired + private ConnectionFactoryLocator connectionFactoryLocator; + + @Autowired + private UsersConnectionRepository usersConnectionRepository; + + @Autowired + private FacebookConnectionSignup facebookConnectionSignup; + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/login*","/signin/**","/signup/**").permitAll() + .anyRequest().authenticated() + .and() + .formLogin().loginPage("/login").permitAll() + .and() + .logout(); + } // @formatter:on + + @Bean + // @Primary + public ProviderSignInController providerSignInController() { + ((InMemoryUsersConnectionRepository) usersConnectionRepository).setConnectionSignUp(facebookConnectionSignup); + return new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, new FacebookSignInAdapter()); + } +} \ No newline at end of file diff --git a/spring-social-login/src/main/java/org/baeldung/config/WebConfig.java b/spring-social-login/src/main/java/org/baeldung/config/WebConfig.java new file mode 100644 index 0000000000..8cfcd6cb41 --- /dev/null +++ b/spring-social-login/src/main/java/org/baeldung/config/WebConfig.java @@ -0,0 +1,39 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +@EnableWebMvc +public class WebConfig extends WebMvcConfigurerAdapter { + + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } + + @Override + public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("forward:/index"); + registry.addViewController("/index"); + registry.addViewController("/login"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } + +} \ No newline at end of file diff --git a/spring-social-login/src/main/java/org/baeldung/persistence/dao/UserRepository.java b/spring-social-login/src/main/java/org/baeldung/persistence/dao/UserRepository.java new file mode 100644 index 0000000000..679dd6c363 --- /dev/null +++ b/spring-social-login/src/main/java/org/baeldung/persistence/dao/UserRepository.java @@ -0,0 +1,10 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.model.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { + + User findByUsername(final String username); + +} diff --git a/spring-social-login/src/main/java/org/baeldung/persistence/model/User.java b/spring-social-login/src/main/java/org/baeldung/persistence/model/User.java new file mode 100644 index 0000000000..a4cffc27d0 --- /dev/null +++ b/spring-social-login/src/main/java/org/baeldung/persistence/model/User.java @@ -0,0 +1,55 @@ +package org.baeldung.persistence.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class User { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(nullable = false, unique = true) + private String username; + + private String password; + + public User() { + super(); + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("User [id=").append(id).append(", username=").append(username).append(", password=").append(password).append("]"); + return builder.toString(); + } + +} diff --git a/spring-social-login/src/main/java/org/baeldung/security/FacebookConnectionSignup.java b/spring-social-login/src/main/java/org/baeldung/security/FacebookConnectionSignup.java new file mode 100644 index 0000000000..6a9e30d7d8 --- /dev/null +++ b/spring-social-login/src/main/java/org/baeldung/security/FacebookConnectionSignup.java @@ -0,0 +1,28 @@ +package org.baeldung.security; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; + +import org.baeldung.persistence.dao.UserRepository; +import org.baeldung.persistence.model.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.social.connect.Connection; +import org.springframework.social.connect.ConnectionSignUp; +import org.springframework.stereotype.Service; + +@Service +public class FacebookConnectionSignup implements ConnectionSignUp { + + @Autowired + private UserRepository userRepository; + + @Override + public String execute(Connection connection) { + System.out.println("signup === "); + final User user = new User(); + user.setUsername(connection.getDisplayName()); + user.setPassword(randomAlphabetic(8)); + userRepository.save(user); + return user.getUsername(); + } + +} diff --git a/spring-social-login/src/main/java/org/baeldung/security/FacebookSignInAdapter.java b/spring-social-login/src/main/java/org/baeldung/security/FacebookSignInAdapter.java new file mode 100644 index 0000000000..b861609a01 --- /dev/null +++ b/spring-social-login/src/main/java/org/baeldung/security/FacebookSignInAdapter.java @@ -0,0 +1,21 @@ +package org.baeldung.security; + +import java.util.Arrays; + +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.social.connect.Connection; +import org.springframework.social.connect.web.SignInAdapter; +import org.springframework.stereotype.Service; +import org.springframework.web.context.request.NativeWebRequest; + +@Service +public class FacebookSignInAdapter implements SignInAdapter { + @Override + public String signIn(String localUserId, Connection connection, NativeWebRequest request) { + System.out.println(" ====== Sign In adapter"); + SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(connection.getDisplayName(), null, Arrays.asList(new SimpleGrantedAuthority("FACEBOOK_USER")))); + return null; + } +} diff --git a/spring-social-login/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-social-login/src/main/java/org/baeldung/security/MyUserDetailsService.java new file mode 100644 index 0000000000..5d0d5d793a --- /dev/null +++ b/spring-social-login/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -0,0 +1,34 @@ +package org.baeldung.security; + +import java.util.Arrays; + +import org.baeldung.persistence.dao.UserRepository; +import org.baeldung.persistence.model.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +@Service +public class MyUserDetailsService implements UserDetailsService { + + @Autowired + private UserRepository userRepository; + + public MyUserDetailsService() { + super(); + } + + // API + + @Override + public UserDetails loadUserByUsername(final String username) { + final User user = userRepository.findByUsername(username); + if (user == null) { + throw new UsernameNotFoundException(username); + } + return new org.springframework.security.core.userdetails.User(username, user.getPassword(), true, true, true, true, Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))); + } +} diff --git a/spring-social-login/src/main/resources/application.properties b/spring-social-login/src/main/resources/application.properties new file mode 100644 index 0000000000..2bd99d8239 --- /dev/null +++ b/spring-social-login/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.social.facebook.appId=1715784745414888 +spring.social.facebook.appSecret=abefd6497e9cc01ad03be28509617bf0 +spring.thymeleaf.cache=false \ No newline at end of file diff --git a/spring-social-login/src/main/resources/data.sql b/spring-social-login/src/main/resources/data.sql new file mode 100644 index 0000000000..3b26afef32 --- /dev/null +++ b/spring-social-login/src/main/resources/data.sql @@ -0,0 +1 @@ +insert into User (id, username, password) values (1,'john', '123'); \ No newline at end of file diff --git a/spring-social-login/src/main/resources/templates/index.html b/spring-social-login/src/main/resources/templates/index.html new file mode 100644 index 0000000000..8e1a8da60f --- /dev/null +++ b/spring-social-login/src/main/resources/templates/index.html @@ -0,0 +1,27 @@ + + + + +Spring Social Login + + + + + + +
+

Welcome, Username

+

User authorities

+
+ + \ No newline at end of file diff --git a/spring-social-login/src/main/resources/templates/login.html b/spring-social-login/src/main/resources/templates/login.html new file mode 100644 index 0000000000..41ad39332c --- /dev/null +++ b/spring-social-login/src/main/resources/templates/login.html @@ -0,0 +1,44 @@ + + + + +Spring Social Login + + + +
+
You have been logged out
+
There was an error, please try again
+ +

Login

+
+
+
+ + +
+
+
+ + +
+ +
+ +
+
+
+
+
+
+
+
+ + +
+
+ + +
+ + \ No newline at end of file diff --git a/spring-social-login/src/test/java/org/baeldung/test/ApplicationIntegrationTest.java b/spring-social-login/src/test/java/org/baeldung/test/ApplicationIntegrationTest.java new file mode 100644 index 0000000000..43aaea18b1 --- /dev/null +++ b/spring-social-login/src/test/java/org/baeldung/test/ApplicationIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung.test; + +import org.baeldung.config.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class ApplicationIntegrationTest { + + @Test + public void whenLoadApplication_thenSuccess() { + + } +} diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md index a8ca755044..98fb4b043b 100644 --- a/spring-thymeleaf/README.md +++ b/spring-thymeleaf/README.md @@ -2,15 +2,16 @@ ## Spring Thymeleaf Example Project - ### Relevant Articles: - [Introduction to Using Thymeleaf in Spring](http://www.baeldung.com/thymeleaf-in-spring-mvc) - [CSRF Protection with Spring MVC and Thymeleaf](http://www.baeldung.com/csrf-thymeleaf-with-spring-security) + ### Build the Project mvn clean install + ### Run the Project mvn cargo:run - **note**: starts on port '8082' diff --git a/testing/README.md b/testing/README.md index f49aeeb881..121472ae13 100644 --- a/testing/README.md +++ b/testing/README.md @@ -5,4 +5,4 @@ ### Relevant Articles: - [Introduction to Mutation Testing Using the PITest Library](http://www.baeldung.com/java-mutation-testing-with-pitest) - [Intro to JaCoCo](http://www.baeldung.com/jacoco) -- [Mutation Testing with PITest](http://www.baeldung.com/java-mutation-testing-with-pitest) +