Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
21e996b300
|
@ -97,6 +97,14 @@
|
|||
<version>8.0.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dbdoclet</groupId>
|
||||
<artifactId>herold</artifactId>
|
||||
<version>6.1.0</version>
|
||||
<scope>system</scope>
|
||||
<systemPath>${basedir}/src/test/resources/jars/herold.jar</systemPath>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.sf.jtidy</groupId>
|
||||
<artifactId>jtidy</artifactId>
|
||||
|
@ -132,7 +140,8 @@
|
|||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
@ -141,6 +150,42 @@
|
|||
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>integration</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
<includes>
|
||||
<include>**/*IntegrationTest.java</include>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<test.mime>json</test.mime>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<!-- persistence -->
|
||||
<hibernate.version>4.3.11.Final</hibernate.version>
|
||||
|
|
|
@ -25,7 +25,7 @@ import org.junit.Test;
|
|||
import org.w3c.dom.Document;
|
||||
import org.w3c.tidy.Tidy;
|
||||
|
||||
public class ApacheFOPConvertHTMLTest {
|
||||
public class ApacheFOPConvertHTMLIntegrationTest {
|
||||
private String inputFile = "src/test/resources/input.html";
|
||||
private String style = "src/test/resources/xhtml2fo.xsl";
|
||||
private String style1 = "src/test/resources/docbook-xsl/fo/docbook.xsl";
|
|
@ -30,7 +30,7 @@ import org.dbdoclet.trafo.script.Script;
|
|||
import org.junit.Test;
|
||||
import org.w3c.dom.Document;
|
||||
|
||||
public class ApacheFOPHeroldTest {
|
||||
public class ApacheFOPHeroldLiveTest {
|
||||
private String[] inputUrls = {// @formatter:off
|
||||
"http://www.baeldung.com/2011/10/20/bootstraping-a-web-application-with-spring-3-1-and-java-based-configuration-part-1/",
|
||||
"http://www.baeldung.com/2011/10/25/building-a-restful-web-service-with-spring-3-1-and-java-based-configuration-part-2/",
|
|
@ -0,0 +1,119 @@
|
|||
package com.baeldung.java9.language.stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.lang.Integer.*;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StreamFeaturesTest {
|
||||
|
||||
public static class TakeAndDropWhileTest {
|
||||
|
||||
public Stream<String> getStreamAfterTakeWhileOperation() {
|
||||
return Stream
|
||||
.iterate("", s -> s + "s")
|
||||
.takeWhile(s -> s.length() < 10);
|
||||
}
|
||||
|
||||
public Stream<String> getStreamAfterDropWhileOperation() {
|
||||
return Stream
|
||||
.iterate("", s -> s + "s")
|
||||
.takeWhile(s -> s.length() < 10)
|
||||
.dropWhile(s -> !s.contains("sssss"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTakeWhileOperation() {
|
||||
List<String> list = getStreamAfterTakeWhileOperation().collect(Collectors.toList());
|
||||
|
||||
assertEquals(10, list.size());
|
||||
|
||||
assertEquals("", list.get(0));
|
||||
assertEquals("ss", list.get(2));
|
||||
assertEquals("sssssssss", list.get(list.size() - 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDropWhileOperation() {
|
||||
List<String> list = getStreamAfterDropWhileOperation().collect(Collectors.toList());
|
||||
|
||||
assertEquals(5, list.size());
|
||||
|
||||
assertEquals("sssss", list.get(0));
|
||||
assertEquals("sssssss", list.get(2));
|
||||
assertEquals("sssssssss", list.get(list.size() - 1));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class IterateTest {
|
||||
|
||||
private Stream<Integer> getStream() {
|
||||
return Stream.iterate(0, i -> i < 10, i -> i + 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIterateOperation() {
|
||||
List<Integer> list = getStream().collect(Collectors.toList());
|
||||
|
||||
assertEquals(10, list.size());
|
||||
|
||||
assertEquals(valueOf(0), list.get(0));
|
||||
assertEquals(valueOf(5), list.get(5));
|
||||
assertEquals(valueOf(9), list.get(list.size() - 1));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class OfNullableTest {
|
||||
|
||||
private List<String> collection = Arrays.asList("A", "B", "C");
|
||||
private Map<String, Integer> map = new HashMap<>() {{
|
||||
put("A", 10);
|
||||
put("C", 30);
|
||||
}};
|
||||
|
||||
private Stream<Integer> getStreamWithOfNullable() {
|
||||
return collection.stream()
|
||||
.flatMap(s -> Stream.ofNullable(map.get(s)));
|
||||
}
|
||||
|
||||
private Stream<Integer> getStream() {
|
||||
return collection.stream()
|
||||
.flatMap(s -> {
|
||||
Integer temp = map.get(s);
|
||||
return temp != null ? Stream.of(temp) : Stream.empty();
|
||||
});
|
||||
}
|
||||
|
||||
private List<Integer> testOfNullableFrom(Stream<Integer> stream) {
|
||||
List<Integer> list = stream.collect(Collectors.toList());
|
||||
|
||||
assertEquals(2, list.size());
|
||||
|
||||
assertEquals(valueOf(10), list.get(0));
|
||||
assertEquals(valueOf(30), list.get(list.size() - 1));
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOfNullable() {
|
||||
|
||||
assertEquals(
|
||||
testOfNullableFrom(getStream()),
|
||||
testOfNullableFrom(getStreamWithOfNullable())
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.equalshashcode.entities;
|
||||
package com.baeldung.equalshashcode.entities;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.equalshashcode.entities;
|
||||
package com.baeldung.equalshashcode.entities;
|
||||
|
||||
public class PrimitiveClass {
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.equalshashcode.entities;
|
||||
package com.baeldung.equalshashcode.entities;
|
||||
|
||||
public class Rectangle extends Shape {
|
||||
private double width;
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.equalshashcode.entities;
|
||||
package com.baeldung.equalshashcode.entities;
|
||||
|
||||
public abstract class Shape {
|
||||
public abstract double area();
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.equalshashcode.entities;
|
||||
package com.baeldung.equalshashcode.entities;
|
||||
|
||||
import java.awt.Color;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.executable;
|
||||
package com.baeldung.executable;
|
||||
|
||||
import javax.swing.JOptionPane;
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
package com.baeldung.java.conversion;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Date;
|
||||
|
||||
import com.baeldung.datetime.UseLocalDateTime;
|
||||
|
||||
public class StringConversion {
|
||||
|
||||
public static int getInt(String str) {
|
||||
return Integer.parseInt(str);
|
||||
}
|
||||
|
||||
public static int getInteger(String str) {
|
||||
return Integer.valueOf(str);
|
||||
}
|
||||
|
||||
public static long getLongPrimitive(String str) {
|
||||
return Long.parseLong(str);
|
||||
}
|
||||
|
||||
public static Long getLong(String str) {
|
||||
return Long.valueOf(str);
|
||||
}
|
||||
|
||||
public static double getDouble(String str) {
|
||||
return Double.parseDouble(str);
|
||||
}
|
||||
|
||||
public static double getDoublePrimitive(String str) {
|
||||
return Double.valueOf(str);
|
||||
}
|
||||
|
||||
public static byte[] getByteArray(String str) {
|
||||
return str.getBytes();
|
||||
}
|
||||
|
||||
public static char[] getCharArray(String str) {
|
||||
return str.toCharArray();
|
||||
}
|
||||
|
||||
public static boolean getBooleanPrimitive(String str) {
|
||||
return Boolean.parseBoolean(str);
|
||||
}
|
||||
|
||||
public static boolean getBoolean(String str) {
|
||||
return Boolean.valueOf(str);
|
||||
}
|
||||
|
||||
public static Date getJava6Date(String str, String format) throws ParseException {
|
||||
SimpleDateFormat formatter = new SimpleDateFormat(format);
|
||||
return formatter.parse(str);
|
||||
}
|
||||
|
||||
public static LocalDateTime getJava8Date(String str) throws ParseException {
|
||||
return new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str);
|
||||
}
|
||||
}
|
|
@ -24,7 +24,7 @@ public class EchoClient {
|
|||
public String sendEcho(String msg) {
|
||||
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);
|
||||
|
|
|
@ -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;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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";
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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")));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
package com.baeldung.enums;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
|
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.hexToAscii;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class HexToAscii {
|
||||
|
||||
@Test
|
||||
public static void whenHexToAscii() {
|
||||
String asciiString = "http://www.baeldung.com/jackson-serialize-dates";
|
||||
String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573";
|
||||
|
||||
assertEquals(asciiString, hexToAscii(hexEquivalent));
|
||||
}
|
||||
|
||||
@Test
|
||||
public static void whenAsciiToHex() {
|
||||
String asciiString = "http://www.baeldung.com/jackson-serialize-dates";
|
||||
String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573";
|
||||
|
||||
assertEquals(hexEquivalent, asciiToHex(asciiString));
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
private static String asciiToHex(String asciiStr) {
|
||||
char[] chars = asciiStr.toCharArray();
|
||||
StringBuilder hex = new StringBuilder();
|
||||
for (char ch : chars) {
|
||||
hex.append(Integer.toHexString((int) ch));
|
||||
}
|
||||
|
||||
return hex.toString();
|
||||
}
|
||||
|
||||
private static String hexToAscii(String hexStr) {
|
||||
StringBuilder output = new StringBuilder("");
|
||||
for (int i = 0; i < hexStr.length(); i += 2) {
|
||||
String str = hexStr.substring(i, i + 2);
|
||||
output.append((char) Integer.parseInt(str, 16));
|
||||
}
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,118 @@
|
|||
package com.baeldung.java.networking.interfaces;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.net.*;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class NetworkInterfaceManualTest {
|
||||
@Test
|
||||
public void givenName_whenReturnsNetworkInterface_thenCorrect() throws SocketException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInExistentName_whenReturnsNull_thenCorrect() throws SocketException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("inexistent_name");
|
||||
assertNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIP_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
byte[] ip = new byte[] { 127, 0, 0, 1 };
|
||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByAddress(ip));
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHostName_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByName("localhost"));
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalHost_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoopBack_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLoopbackAddress());
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIndex_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByIndex(0);
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenReturnsInetAddresses_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
Enumeration<InetAddress> addressEnum = nif.getInetAddresses();
|
||||
InetAddress address = addressEnum.nextElement();
|
||||
assertEquals("127.0.0.1", address.getHostAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenReturnsInterfaceAddresses_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
|
||||
List<InterfaceAddress> addressEnum = nif.getInterfaceAddresses();
|
||||
InterfaceAddress address = addressEnum.get(0);
|
||||
InetAddress localAddress = address.getAddress();
|
||||
InetAddress broadCastAddress = address.getBroadcast();
|
||||
assertEquals("127.0.0.1", localAddress.getHostAddress());
|
||||
assertEquals("127.255.255.255", broadCastAddress.getHostAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksIfLoopback_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertTrue(nif.isLoopback());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksIfUp_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertTrue(nif.isUp());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksIfPointToPoint_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertFalse(nif.isPointToPoint());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksIfVirtual_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertFalse(nif.isVirtual());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksMulticastSupport_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertTrue(nif.supportsMulticast());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenGetsMacAddress_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
byte[] bytes = nif.getHardwareAddress();
|
||||
assertNotNull(bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenGetsMTU_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("net0");
|
||||
int mtu = nif.getMTU();
|
||||
assertEquals(1500, mtu);
|
||||
}
|
||||
}
|
|
@ -1,6 +1,5 @@
|
|||
package com.baeldung.java.networking.udp;
|
||||
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
|
|
@ -1,104 +0,0 @@
|
|||
package com.baeldung.java.networking.url;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class UrlTest {
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCanIdentifyProtocol_thenCorrect() throws MalformedURLException {
|
||||
URL url = new URL("http://baeldung.com");
|
||||
assertEquals("http", url.getProtocol());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCanGetHost_thenCorrect() throws MalformedURLException {
|
||||
URL url = new URL("http://baeldung.com");
|
||||
assertEquals("baeldung.com", url.getHost());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCanGetFileName_thenCorrect2() throws MalformedURLException {
|
||||
URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
|
||||
assertEquals("/articles?topic=java&version=8", url.getFile());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCanGetFileName_thenCorrect1() throws MalformedURLException {
|
||||
URL url = new URL("http://baeldung.com/guidelines.txt");
|
||||
assertEquals("/guidelines.txt", url.getFile());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCanGetPathParams_thenCorrect() throws MalformedURLException {
|
||||
URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
|
||||
assertEquals("/articles", url.getPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCanGetQueryParams_thenCorrect() throws MalformedURLException {
|
||||
URL url = new URL("http://baeldung.com/articles?topic=java");
|
||||
assertEquals("topic=java", url.getQuery());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenGetsDefaultPort_thenCorrect() throws MalformedURLException {
|
||||
URL url = new URL("http://baeldung.com");
|
||||
assertEquals(-1, url.getPort());
|
||||
assertEquals(80, url.getDefaultPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenGetsPort_thenCorrect() throws MalformedURLException {
|
||||
URL url = new URL("http://baeldung.com:8090");
|
||||
assertEquals(8090, url.getPort());
|
||||
assertEquals(80, url.getDefaultPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBaseUrl_whenCreatesRelativeUrl_thenCorrect() throws MalformedURLException {
|
||||
URL baseUrl = new URL("http://baeldung.com");
|
||||
URL relativeUrl = new URL(baseUrl, "a-guide-to-java-sockets");
|
||||
assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsoluteUrl_whenIgnoresBaseUrl_thenCorrect() throws MalformedURLException {
|
||||
URL baseUrl = new URL("http://baeldung.com");
|
||||
URL relativeUrl = new URL(baseUrl, "http://baeldung.com/a-guide-to-java-sockets");
|
||||
assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException {
|
||||
String protocol = "http";
|
||||
String host = "baeldung.com";
|
||||
String file = "/guidelines.txt";
|
||||
URL url = new URL(protocol, host, file);
|
||||
assertEquals("http://baeldung.com/guidelines.txt", url.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect2() throws MalformedURLException {
|
||||
String protocol = "http";
|
||||
String host = "baeldung.com";
|
||||
String file = "/articles?topic=java&version=8";
|
||||
URL url = new URL(protocol, host, file);
|
||||
assertEquals("http://baeldung.com/guidelines.txt", url.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrlComponentsWithPort_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException {
|
||||
String protocol = "http";
|
||||
String host = "baeldung.com";
|
||||
int port = 9000;
|
||||
String file = "/guidelines.txt";
|
||||
URL url = new URL(protocol, host, port, file);
|
||||
assertEquals("http://baeldung.com:9000/guidelines.txt", url.toString());
|
||||
}
|
||||
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -11,54 +11,54 @@ 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;
|
||||
|
||||
public class FileUnitTest {
|
||||
public class FileTest {
|
||||
private static final String HOME = System.getProperty("user.home");
|
||||
|
||||
// checking file or dir
|
||||
@Test
|
||||
public void givenExistentPath_whenConfirmsFileExists_thenCorrect() {
|
||||
final Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(HOME);
|
||||
assertTrue(Files.exists(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonexistentPath_whenConfirmsFileNotExists_thenCorrect() {
|
||||
final Path p = Paths.get(HOME + "/inexistent_file.txt");
|
||||
Path p = Paths.get(HOME + "/inexistent_file.txt");
|
||||
assertTrue(Files.notExists(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsNotRegularFile_thenCorrect() {
|
||||
final Path p = Paths.get(HOME);
|
||||
public void givenDirPath_whenConfirmsNotRegularFile_thenCorrect() {
|
||||
Path p = Paths.get(HOME);
|
||||
assertFalse(Files.isRegularFile(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsReadable_thenCorrect() {
|
||||
final Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(HOME);
|
||||
assertTrue(Files.isReadable(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsWritable_thenCorrect() {
|
||||
final Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(HOME);
|
||||
assertTrue(Files.isWritable(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsExecutable_thenCorrect() {
|
||||
final Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(HOME);
|
||||
assertTrue(Files.isExecutable(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSameFilePaths_whenConfirmsIsSame_thenCorrect() throws IOException {
|
||||
final Path p1 = Paths.get(HOME);
|
||||
final Path p2 = Paths.get(HOME);
|
||||
Path p1 = Paths.get(HOME);
|
||||
Path p2 = Paths.get(HOME);
|
||||
assertTrue(Files.isSameFile(p1, p2));
|
||||
}
|
||||
|
||||
|
@ -66,8 +66,8 @@ public class FileUnitTest {
|
|||
// creating file
|
||||
@Test
|
||||
public void givenFilePath_whenCreatesNewFile_thenCorrect() throws IOException {
|
||||
final String fileName = "myfile_" + new Date().getTime() + ".txt";
|
||||
final Path p = Paths.get(HOME + "/" + fileName);
|
||||
String fileName = "myfile_" + UUID.randomUUID().toString() + ".txt";
|
||||
Path p = Paths.get(HOME + "/" + fileName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createFile(p);
|
||||
assertTrue(Files.exists(p));
|
||||
|
@ -76,8 +76,8 @@ public class FileUnitTest {
|
|||
|
||||
@Test
|
||||
public void givenDirPath_whenCreatesNewDir_thenCorrect() throws IOException {
|
||||
final String dirName = "myDir_" + new Date().getTime();
|
||||
final Path p = Paths.get(HOME + "/" + dirName);
|
||||
String dirName = "myDir_" + UUID.randomUUID().toString();
|
||||
Path p = Paths.get(HOME + "/" + dirName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createDirectory(p);
|
||||
assertTrue(Files.exists(p));
|
||||
|
@ -86,22 +86,19 @@ public class FileUnitTest {
|
|||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() {
|
||||
final String dirName = "myDir_" + new Date().getTime() + "/subdir";
|
||||
final Path p = Paths.get(HOME + "/" + dirName);
|
||||
@Test(expected = NoSuchFileException.class)
|
||||
public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() throws IOException {
|
||||
String dirName = "myDir_" + UUID.randomUUID().toString() + "/subdir";
|
||||
Path p = Paths.get(HOME + "/" + dirName);
|
||||
assertFalse(Files.exists(p));
|
||||
try {
|
||||
Files.createDirectory(p);
|
||||
} catch (final IOException e) {
|
||||
assertTrue(e instanceof NoSuchFileException);
|
||||
}
|
||||
Files.createDirectory(p);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDirPath_whenCreatesRecursively_thenCorrect() throws IOException {
|
||||
final Path dir = Paths.get(HOME + "/myDir_" + new Date().getTime());
|
||||
final Path subdir = dir.resolve("subdir");
|
||||
Path dir = Paths.get(HOME + "/myDir_" + UUID.randomUUID().toString());
|
||||
Path subdir = dir.resolve("subdir");
|
||||
assertFalse(Files.exists(dir));
|
||||
assertFalse(Files.exists(subdir));
|
||||
Files.createDirectories(subdir);
|
||||
|
@ -111,8 +108,8 @@ public class FileUnitTest {
|
|||
|
||||
@Test
|
||||
public void givenFilePath_whenCreatesTempFile_thenCorrect() throws IOException {
|
||||
final String prefix = "log_";
|
||||
final String suffix = ".txt";
|
||||
String prefix = "log_";
|
||||
String suffix = ".txt";
|
||||
Path p = Paths.get(HOME + "/");
|
||||
p = Files.createTempFile(p, prefix, suffix);
|
||||
// like log_8821081429012075286.txt
|
||||
|
@ -121,17 +118,16 @@ public class FileUnitTest {
|
|||
}
|
||||
|
||||
@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
|
||||
System.out.println(p);
|
||||
assertTrue(Files.exists(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNoFilePath_whenCreatesTempFileInTempDir_thenCorrect() throws IOException {
|
||||
final Path p = Files.createTempFile(null, null);
|
||||
Path p = Files.createTempFile(null, null);
|
||||
// like C:\Users\new\AppData\Local\Temp\6100927974988978748.tmp
|
||||
assertTrue(Files.exists(p));
|
||||
|
||||
|
@ -140,7 +136,7 @@ public class FileUnitTest {
|
|||
// delete file
|
||||
@Test
|
||||
public void givenPath_whenDeletes_thenCorrect() throws IOException {
|
||||
final Path p = Paths.get(HOME + "/fileToDelete.txt");
|
||||
Path p = Paths.get(HOME + "/fileToDelete.txt");
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createFile(p);
|
||||
assertTrue(Files.exists(p));
|
||||
|
@ -149,37 +145,30 @@ public class FileUnitTest {
|
|||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Test(expected = DirectoryNotEmptyException.class)
|
||||
public void givenPath_whenFailsToDeleteNonEmptyDir_thenCorrect() throws IOException {
|
||||
final 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));
|
||||
final Path file = dir.resolve("file.txt");
|
||||
Path file = dir.resolve("file.txt");
|
||||
Files.createFile(file);
|
||||
try {
|
||||
Files.delete(dir);
|
||||
} catch (final IOException e) {
|
||||
assertTrue(e instanceof DirectoryNotEmptyException);
|
||||
}
|
||||
Files.delete(dir);
|
||||
|
||||
assertTrue(Files.exists(dir));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Test(expected = NoSuchFileException.class)
|
||||
public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException {
|
||||
final Path p = Paths.get(HOME + "/inexistentFile.txt");
|
||||
Path p = Paths.get(HOME + "/inexistentFile.txt");
|
||||
assertFalse(Files.exists(p));
|
||||
try {
|
||||
Files.delete(p);
|
||||
} catch (final IOException e) {
|
||||
assertTrue(e instanceof NoSuchFileException);
|
||||
}
|
||||
Files.delete(p);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInexistentFile_whenDeleteIfExistsWorks_thenCorrect() throws IOException {
|
||||
final Path p = Paths.get(HOME + "/inexistentFile.txt");
|
||||
Path p = Paths.get(HOME + "/inexistentFile.txt");
|
||||
assertFalse(Files.exists(p));
|
||||
Files.deleteIfExists(p);
|
||||
|
||||
|
@ -188,12 +177,12 @@ public class FileUnitTest {
|
|||
// copy file
|
||||
@Test
|
||||
public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException {
|
||||
final Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
|
||||
final 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);
|
||||
final Path file1 = dir1.resolve("filetocopy.txt");
|
||||
final Path file2 = dir2.resolve("filetocopy.txt");
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
Path file2 = dir2.resolve("filetocopy.txt");
|
||||
Files.createFile(file1);
|
||||
assertTrue(Files.exists(file1));
|
||||
assertFalse(Files.exists(file2));
|
||||
|
@ -202,35 +191,31 @@ public class FileUnitTest {
|
|||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Test(expected = FileAlreadyExistsException.class)
|
||||
public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||
final Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
|
||||
final 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);
|
||||
final Path file1 = dir1.resolve("filetocopy.txt");
|
||||
final Path file2 = dir2.resolve("filetocopy.txt");
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
Path file2 = dir2.resolve("filetocopy.txt");
|
||||
Files.createFile(file1);
|
||||
Files.createFile(file2);
|
||||
assertTrue(Files.exists(file1));
|
||||
assertTrue(Files.exists(file2));
|
||||
try {
|
||||
Files.copy(file1, file2);
|
||||
} catch (final IOException e) {
|
||||
assertTrue(e instanceof FileAlreadyExistsException);
|
||||
}
|
||||
Files.copy(file1, file2);
|
||||
Files.copy(file1, file2, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
|
||||
// moving files
|
||||
@Test
|
||||
public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException {
|
||||
final Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
|
||||
final 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);
|
||||
final Path file1 = dir1.resolve("filetocopy.txt");
|
||||
final Path file2 = dir2.resolve("filetocopy.txt");
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
Path file2 = dir2.resolve("filetocopy.txt");
|
||||
Files.createFile(file1);
|
||||
assertTrue(Files.exists(file1));
|
||||
assertFalse(Files.exists(file2));
|
||||
|
@ -240,25 +225,22 @@ public class FileUnitTest {
|
|||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Test(expected = FileAlreadyExistsException.class)
|
||||
public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||
final Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
|
||||
final 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);
|
||||
final Path file1 = dir1.resolve("filetocopy.txt");
|
||||
final Path file2 = dir2.resolve("filetocopy.txt");
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
Path file2 = dir2.resolve("filetocopy.txt");
|
||||
Files.createFile(file1);
|
||||
Files.createFile(file2);
|
||||
assertTrue(Files.exists(file1));
|
||||
assertTrue(Files.exists(file2));
|
||||
try {
|
||||
Files.move(file1, file2);
|
||||
} catch (final IOException e) {
|
||||
assertTrue(e instanceof FileAlreadyExistsException);
|
||||
}
|
||||
Files.move(file1, file2);
|
||||
Files.move(file1, file2, StandardCopyOption.REPLACE_EXISTING);
|
||||
assertTrue(Files.exists(file2));
|
||||
assertFalse(Files.exists(file1));
|
||||
}
|
||||
|
||||
}
|
|
@ -6,8 +6,10 @@ import static org.junit.Assert.assertTrue;
|
|||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
|
@ -18,14 +20,14 @@ public class PathManualTest {
|
|||
// creating a path
|
||||
@Test
|
||||
public void givenPathString_whenCreatesPathObject_thenCorrect() {
|
||||
final Path p = Paths.get("/articles/baeldung");
|
||||
Path p = Paths.get("/articles/baeldung");
|
||||
assertEquals("\\articles\\baeldung", p.toString());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathParts_whenCreatesPathObject_thenCorrect() {
|
||||
final Path p = Paths.get("/articles", "baeldung");
|
||||
Path p = Paths.get("/articles", "baeldung");
|
||||
assertEquals("\\articles\\baeldung", p.toString());
|
||||
|
||||
}
|
||||
|
@ -33,13 +35,13 @@ public class PathManualTest {
|
|||
// retrieving path info
|
||||
@Test
|
||||
public void givenPath_whenRetrievesFileName_thenCorrect() {
|
||||
final Path p = Paths.get("/articles/baeldung/logs");
|
||||
Path p = Paths.get("/articles/baeldung/logs");
|
||||
assertEquals("logs", p.getFileName().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenRetrievesNameByIndex_thenCorrect() {
|
||||
final Path p = Paths.get("/articles/baeldung/logs");
|
||||
Path p = Paths.get("/articles/baeldung/logs");
|
||||
assertEquals("articles", p.getName(0).toString());
|
||||
assertEquals("baeldung", p.getName(1).toString());
|
||||
assertEquals("logs", p.getName(2).toString());
|
||||
|
@ -47,13 +49,13 @@ public class PathManualTest {
|
|||
|
||||
@Test
|
||||
public void givenPath_whenCountsParts_thenCorrect() {
|
||||
final Path p = Paths.get("/articles/baeldung/logs");
|
||||
Path p = Paths.get("/articles/baeldung/logs");
|
||||
assertEquals(3, p.getNameCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenCanRetrieveSubsequenceByIndex_thenCorrect() {
|
||||
final Path p = Paths.get("/articles/baeldung/logs");
|
||||
Path p = Paths.get("/articles/baeldung/logs");
|
||||
assertEquals("articles", p.subpath(0, 1).toString());
|
||||
assertEquals("articles\\baeldung", p.subpath(0, 2).toString());
|
||||
assertEquals("articles\\baeldung\\logs", p.subpath(0, 3).toString());
|
||||
|
@ -64,10 +66,10 @@ public class PathManualTest {
|
|||
|
||||
@Test
|
||||
public void givenPath_whenRetrievesParent_thenCorrect() {
|
||||
final Path p1 = Paths.get("/articles/baeldung/logs");
|
||||
final Path p2 = Paths.get("/articles/baeldung");
|
||||
final Path p3 = Paths.get("/articles");
|
||||
final Path p4 = Paths.get("/");
|
||||
Path p1 = Paths.get("/articles/baeldung/logs");
|
||||
Path p2 = Paths.get("/articles/baeldung");
|
||||
Path p3 = Paths.get("/articles");
|
||||
Path p4 = Paths.get("/");
|
||||
|
||||
assertEquals("\\articles\\baeldung", p1.getParent().toString());
|
||||
assertEquals("\\articles", p2.getParent().toString());
|
||||
|
@ -77,8 +79,8 @@ public class PathManualTest {
|
|||
|
||||
@Test
|
||||
public void givenPath_whenRetrievesRoot_thenCorrect() {
|
||||
final Path p1 = Paths.get("/articles/baeldung/logs");
|
||||
final Path p2 = Paths.get("c:/articles/baeldung/logs");
|
||||
Path p1 = Paths.get("/articles/baeldung/logs");
|
||||
Path p2 = Paths.get("c:/articles/baeldung/logs");
|
||||
|
||||
assertEquals("\\", p1.getRoot().toString());
|
||||
assertEquals("c:\\", p2.getRoot().toString());
|
||||
|
@ -102,71 +104,68 @@ public class PathManualTest {
|
|||
// converting a path
|
||||
@Test
|
||||
public void givenPath_whenConvertsToBrowseablePath_thenCorrect() {
|
||||
final Path p = Paths.get("/home/baeldung/articles.html");
|
||||
final URI uri = p.toUri();
|
||||
Path p = Paths.get("/home/baeldung/articles.html");
|
||||
URI uri = p.toUri();
|
||||
assertEquals("file:///E:/home/baeldung/articles.html", uri.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenConvertsToAbsolutePath_thenCorrect() {
|
||||
final Path p = Paths.get("/home/baeldung/articles.html");
|
||||
Path p = Paths.get("/home/baeldung/articles.html");
|
||||
assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePath_whenRetainsAsAbsolute_thenCorrect() {
|
||||
final Path p = Paths.get("E:\\home\\baeldung\\articles.html");
|
||||
Path p = Paths.get("E:\\home\\baeldung\\articles.html");
|
||||
assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingPath_whenGetsRealPathToFile_thenCorrect() throws IOException {
|
||||
final Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(HOME);
|
||||
assertEquals(HOME, p.toRealPath().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInExistentPath_whenFailsToConvert_thenCorrect() {
|
||||
final Path p = Paths.get("E:\\home\\baeldung\\articles.html");
|
||||
try {
|
||||
p.toRealPath();
|
||||
} catch (final IOException e) {
|
||||
assertTrue(true);
|
||||
}
|
||||
@Test(expected = NoSuchFileException.class)
|
||||
public void givenInExistentPath_whenFailsToConvert_thenCorrect() throws IOException {
|
||||
Path p = Paths.get("E:\\home\\baeldung\\articles.html");
|
||||
|
||||
p.toRealPath();
|
||||
}
|
||||
|
||||
// joining paths
|
||||
@Test
|
||||
public void givenTwoPaths_whenJoinsAndResolves_thenCorrect() throws IOException {
|
||||
final Path p = Paths.get("/baeldung/articles");
|
||||
Path p = Paths.get("/baeldung/articles");
|
||||
assertEquals("\\baeldung\\articles\\java", p.resolve("java").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePath_whenResolutionRetainsIt_thenCorrect() throws IOException {
|
||||
final Path p = Paths.get("/baeldung/articles");
|
||||
Path p = Paths.get("/baeldung/articles");
|
||||
assertEquals("C:\\baeldung\\articles\\java", p.resolve("C:\\baeldung\\articles\\java").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathWithRoot_whenResolutionRetainsIt_thenCorrect2() throws IOException {
|
||||
final Path p = Paths.get("/baeldung/articles");
|
||||
Path p = Paths.get("/baeldung/articles");
|
||||
assertEquals("\\java", p.resolve("/java").toString());
|
||||
}
|
||||
|
||||
// creating a path between 2 paths
|
||||
@Test
|
||||
public void givenSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException {
|
||||
final Path p1 = Paths.get("articles");
|
||||
final Path p2 = Paths.get("authors");
|
||||
Path p1 = Paths.get("articles");
|
||||
Path p2 = Paths.get("authors");
|
||||
assertEquals("..\\authors", p1.relativize(p2).toString());
|
||||
assertEquals("..\\articles", p2.relativize(p1).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException {
|
||||
final Path p1 = Paths.get("/baeldung");
|
||||
final Path p2 = Paths.get("/baeldung/authors/articles");
|
||||
Path p1 = Paths.get("/baeldung");
|
||||
Path p2 = Paths.get("/baeldung/authors/articles");
|
||||
assertEquals("authors\\articles", p1.relativize(p2).toString());
|
||||
assertEquals("..\\..", p2.relativize(p1).toString());
|
||||
}
|
||||
|
@ -174,9 +173,9 @@ public class PathManualTest {
|
|||
// comparing 2 paths
|
||||
@Test
|
||||
public void givenTwoPaths_whenTestsEquality_thenCorrect() throws IOException {
|
||||
final Path p1 = Paths.get("/baeldung/articles");
|
||||
final Path p2 = Paths.get("/baeldung/articles");
|
||||
final Path p3 = Paths.get("/baeldung/authors");
|
||||
Path p1 = Paths.get("/baeldung/articles");
|
||||
Path p2 = Paths.get("/baeldung/articles");
|
||||
Path p3 = Paths.get("/baeldung/authors");
|
||||
|
||||
assertTrue(p1.equals(p2));
|
||||
assertFalse(p1.equals(p3));
|
||||
|
@ -184,13 +183,13 @@ public class PathManualTest {
|
|||
|
||||
@Test
|
||||
public void givenPath_whenInspectsStart_thenCorrect() {
|
||||
final Path p1 = Paths.get("/baeldung/articles");
|
||||
Path p1 = Paths.get("/baeldung/articles");
|
||||
assertTrue(p1.startsWith("/baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenInspectsEnd_thenCorrect() {
|
||||
final Path p1 = Paths.get("/baeldung/articles");
|
||||
Path p1 = Paths.get("/baeldung/articles");
|
||||
assertTrue(p1.endsWith("articles"));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,52 @@
|
|||
package com.baeldung.java8;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class Java8ForEachTest {
|
||||
|
||||
@Test
|
||||
public void compareForEachMethods_thenPrintResults() {
|
||||
|
||||
List<String> names = new ArrayList<>();
|
||||
names.add("Larry");
|
||||
names.add("Steve");
|
||||
names.add("James");
|
||||
names.add("Conan");
|
||||
names.add("Ellen");
|
||||
|
||||
// Java 5 - for-loop
|
||||
System.out.println("--- Enhanced for-loop ---");
|
||||
for (String name : names) {
|
||||
System.out.println(name);
|
||||
}
|
||||
|
||||
// Java 8 - forEach
|
||||
System.out.println("--- forEach method ---");
|
||||
names.forEach(name -> System.out.println(name));
|
||||
|
||||
// Anonymous inner class that implements Consumer interface
|
||||
System.out.println("--- Anonymous inner class ---");
|
||||
names.forEach(new Consumer<String>() {
|
||||
public void accept(String name) {
|
||||
System.out.println(name);
|
||||
}
|
||||
});
|
||||
|
||||
// Create a Consumer implementation to then use in a forEach method
|
||||
Consumer<String> consumerNames = name -> {
|
||||
System.out.println(name);
|
||||
};
|
||||
System.out.println("--- Implementation of Consumer interface ---");
|
||||
names.forEach(consumerNames);
|
||||
|
||||
// Print elements using a Method Reference
|
||||
System.out.println("--- Method Reference ---");
|
||||
names.forEach(System.out::println);
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -27,18 +27,14 @@ public class Java8StreamApiUnitTest {
|
|||
|
||||
@Before
|
||||
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<String> 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<String> 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<String> 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<String> streamOfArrayPart = Arrays.stream(arr, 1, 3);
|
||||
assertEquals(2, streamOfArrayPart.count());
|
||||
|
||||
|
@ -112,7 +107,7 @@ public class Java8StreamApiUnitTest {
|
|||
}
|
||||
assertEquals("a", streamOfStrings.findFirst().get());
|
||||
|
||||
Stream<String> streamBuilder = Stream.<String>builder().add("a").add("b").add("c").build();
|
||||
Stream<String> streamBuilder = Stream.<String> builder().add("a").add("b").add("c").build();
|
||||
assertEquals(3, streamBuilder.count());
|
||||
|
||||
Stream<String> streamGenerated = Stream.generate(() -> "element").limit(10);
|
||||
|
@ -126,14 +121,13 @@ public class Java8StreamApiUnitTest {
|
|||
public void runStreamPipeline_whenOrderIsRight_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||
Optional<String> 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<String> 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<String> collectorCollection = productList.stream()
|
||||
.map(Product::getName).collect(Collectors.toList());
|
||||
List<String> 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<Integer, List<Product>> collectorMapOfLists = productList.stream()
|
||||
.collect(Collectors.groupingBy(Product::getPrice));
|
||||
Map<Integer, List<Product>> collectorMapOfLists = productList.stream().collect(Collectors.groupingBy(Product::getPrice));
|
||||
assertEquals(3, collectorMapOfLists.keySet().size());
|
||||
|
||||
Map<Boolean, List<Product>> mapPartioned = productList.stream()
|
||||
.collect(Collectors.partitioningBy(element -> element.getPrice() > 15));
|
||||
Map<Boolean, List<Product>> 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<Product> unmodifiableSet = productList.stream()
|
||||
.collect(Collectors.collectingAndThen(Collectors.toSet(),
|
||||
Collections::unmodifiableSet));
|
||||
Set<Product> unmodifiableSet = productList.stream().collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
|
||||
unmodifiableSet.add(new Product(4, "tea"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void customCollector_whenResultContainsAllElementsFrSource_thenCorrect() {
|
||||
Collector<Product, ?, LinkedList<Product>> toLinkedList =
|
||||
Collector.of(LinkedList::new, LinkedList::add,
|
||||
(first, second) -> {
|
||||
first.addAll(second);
|
||||
return first;
|
||||
});
|
||||
Collector<Product, ?, LinkedList<Product>> toLinkedList = Collector.of(LinkedList::new, LinkedList::add, (first, second) -> {
|
||||
first.addAll(second);
|
||||
return first;
|
||||
});
|
||||
|
||||
LinkedList<Product> linkedListOfPersons = productList.stream().collect(toLinkedList);
|
||||
assertTrue(linkedListOfPersons.containsAll(productList));
|
||||
|
@ -219,23 +202,20 @@ public class Java8StreamApiUnitTest {
|
|||
public void parallelStream_whenWorks_thenCorrect() {
|
||||
Stream<Product> 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);
|
||||
|
|
|
@ -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<String> 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<String> streamFilter = list.stream().filter(element -> element.isEmpty());
|
||||
assertEquals(streamFilter.count(), 2);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenOperationMap_thanCorrect() {
|
||||
List<String> uris = new ArrayList<>();
|
||||
|
@ -65,12 +63,10 @@ public class Java8StreamsUnitTest {
|
|||
List<Detail> details = new ArrayList<>();
|
||||
details.add(new Detail());
|
||||
details.add(new Detail());
|
||||
Stream<String> streamFlatMap = details.stream()
|
||||
.flatMap(detail -> detail.getParts().stream());
|
||||
Stream<String> 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<Integer> integers = new ArrayList<>();
|
||||
|
@ -94,20 +89,17 @@ public class Java8StreamsUnitTest {
|
|||
|
||||
@Test
|
||||
public void checkStreamContains_whenOperationCollect_thenCorrect() {
|
||||
List<String> resultList = list.stream()
|
||||
.map(element -> element.toUpperCase())
|
||||
.collect(Collectors.toList());
|
||||
List<String> 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
|
||||
}
|
||||
}
|
||||
|
|
|
@ -46,9 +46,7 @@ public class GuavaThreadPoolIntegrationTest {
|
|||
ListenableFuture<String> future1 = listeningExecutorService.submit(() -> "Hello");
|
||||
ListenableFuture<String> 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);
|
||||
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -90,7 +90,6 @@ public class JavaTimerLongRunningUnitTest {
|
|||
@Override
|
||||
public void run() {
|
||||
System.out.println("Task performed on " + new Date());
|
||||
// TODO: stop the thread
|
||||
}
|
||||
};
|
||||
final Timer timer = new Timer("Timer");
|
||||
|
|
|
@ -77,5 +77,5 @@ public class PizzaUnitTest {
|
|||
pz.deliver();
|
||||
assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -1,25 +0,0 @@
|
|||
package com.baeldung.enterprise.patterns.front.controller.filters;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import java.io.IOException;
|
||||
|
||||
public class AuditFilter extends BaseFilter {
|
||||
@Override
|
||||
public void doFilter(
|
||||
ServletRequest request,
|
||||
ServletResponse response,
|
||||
FilterChain chain
|
||||
) throws IOException, ServletException {
|
||||
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
|
||||
HttpSession session = httpServletRequest.getSession(false);
|
||||
if (session != null && session.getAttribute("username") != null) {
|
||||
request.setAttribute("username", session.getAttribute("username"));
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
|
@ -1,23 +0,0 @@
|
|||
package com.baeldung.enterprise.patterns.front.controller.filters;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.annotation.WebFilter;
|
||||
import java.io.IOException;
|
||||
|
||||
@WebFilter(servletNames = "front-controller")
|
||||
public class VisitorCounterFilter extends BaseFilter {
|
||||
private int counter;
|
||||
|
||||
@Override
|
||||
public void doFilter(
|
||||
ServletRequest request,
|
||||
ServletResponse response,
|
||||
FilterChain chain
|
||||
) throws IOException, ServletException {
|
||||
request.setAttribute("counter", ++counter);
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
|
@ -27,10 +27,11 @@ import org.apache.http.impl.auth.BasicScheme;
|
|||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
@Ignore("need spring-rest module running")
|
||||
/*
|
||||
* NOTE : Need module spring-rest to be running
|
||||
*/
|
||||
public class HttpClientPostingLiveTest {
|
||||
private static final String SAMPLE_URL = "http://localhost:8080/spring-rest/users";
|
||||
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";
|
||||
|
|
|
@ -1,28 +1,35 @@
|
|||
package org.baeldung.httpclient;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.conn.ClientConnectionManager;
|
||||
import org.apache.http.conn.scheme.Scheme;
|
||||
import org.apache.http.conn.scheme.SchemeRegistry;
|
||||
import org.apache.http.conn.ssl.*;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.DefaultHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.impl.conn.PoolingClientConnectionManager;
|
||||
import org.junit.Test;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLException;
|
||||
import java.io.IOException;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLException;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.conn.ClientConnectionManager;
|
||||
import org.apache.http.conn.scheme.Scheme;
|
||||
import org.apache.http.conn.scheme.SchemeRegistry;
|
||||
import org.apache.http.conn.ssl.NoopHostnameVerifier;
|
||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.http.conn.ssl.SSLContextBuilder;
|
||||
import org.apache.http.conn.ssl.SSLContexts;
|
||||
import org.apache.http.conn.ssl.SSLSocketFactory;
|
||||
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
|
||||
import org.apache.http.conn.ssl.TrustStrategy;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.DefaultHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.impl.conn.PoolingClientConnectionManager;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* This test requires a localhost server over HTTPS <br>
|
||||
|
@ -96,7 +103,7 @@ public class HttpsClientSslLiveTest {
|
|||
@Test
|
||||
public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws IOException {
|
||||
|
||||
TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
|
||||
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
|
||||
|
||||
SSLContext sslContext = null;
|
||||
try {
|
||||
|
@ -106,8 +113,8 @@ public class HttpsClientSslLiveTest {
|
|||
e.printStackTrace();
|
||||
}
|
||||
|
||||
CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
|
||||
final HttpGet httpGet = new HttpGet("https://sesar3.geoinfogeochem.org/sample/igsn/ODP000002");
|
||||
final CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
|
||||
final HttpGet httpGet = new HttpGet(HOST_WITH_SSL);
|
||||
httpGet.setHeader("Accept", "application/xml");
|
||||
|
||||
final HttpResponse response = client.execute(httpGet);
|
||||
|
|
|
@ -1,5 +1,8 @@
|
|||
package org.baeldung.httpclient.base;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.auth.AuthScope;
|
||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||
|
@ -11,9 +14,9 @@ import org.apache.http.impl.client.CloseableHttpClient;
|
|||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
/*
|
||||
* NOTE : Need module spring-security-rest-basic-auth to be running
|
||||
*/
|
||||
public class HttpClientSandboxLiveTest {
|
||||
|
||||
@Test
|
||||
|
@ -22,10 +25,10 @@ public class HttpClientSandboxLiveTest {
|
|||
final AuthScope authscp = new AuthScope("localhost", 8080);
|
||||
credentialsProvider.setCredentials(authscp, new UsernamePasswordCredentials("user1", "user1Pass"));
|
||||
|
||||
CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
|
||||
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
|
||||
|
||||
final HttpGet httpGet = new HttpGet("http://localhost:8080/spring-security-rest-basic-auth/api/foos/1");
|
||||
CloseableHttpResponse response = client.execute(httpGet);
|
||||
final CloseableHttpResponse response = client.execute(httpGet);
|
||||
|
||||
System.out.println(response.getStatusLine());
|
||||
|
||||
|
|
|
@ -30,6 +30,10 @@ import org.junit.After;
|
|||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
/*
|
||||
* NOTE : Need module spring-security-rest-basic-auth to be running
|
||||
*/
|
||||
|
||||
public class HttpClientAuthLiveTest {
|
||||
|
||||
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://localhost:8081/spring-security-rest-basic-auth/api/foos/1";
|
||||
|
|
|
@ -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");
|
||||
|
|
|
@ -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");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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");
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
/target/
|
|
@ -0,0 +1,87 @@
|
|||
<?xml version="1.0"?>
|
||||
<project
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>pdf</artifactId>
|
||||
<name>pdf</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.pdfbox</groupId>
|
||||
<artifactId>pdfbox-tools</artifactId>
|
||||
<version>2.0.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.sf.cssbox</groupId>
|
||||
<artifactId>pdf2dom</artifactId>
|
||||
<version>1.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.itextpdf</groupId>
|
||||
<artifactId>itextpdf</artifactId>
|
||||
<version>5.5.10</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi</artifactId>
|
||||
<version>3.15</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-scratchpad</artifactId>
|
||||
<version>3.15</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.xmlgraphics</groupId>
|
||||
<artifactId>batik-transcoder</artifactId>
|
||||
<version>1.8</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-ooxml</artifactId>
|
||||
<version>3.15</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>pdf</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,35 @@
|
|||
package com.baeldung.pdf;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.Writer;
|
||||
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.fit.pdfdom.PDFDomTree;
|
||||
|
||||
public class PDF2HTMLExample {
|
||||
|
||||
private static final String FILENAME = "src/main/resources/pdf.pdf";
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
generateHTMLFromPDF(FILENAME);
|
||||
} catch (IOException | ParserConfigurationException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static void generateHTMLFromPDF(String filename) throws ParserConfigurationException, IOException {
|
||||
PDDocument pdf = PDDocument.load(new File(filename));
|
||||
PDFDomTree parser = new PDFDomTree();
|
||||
Writer output = new PrintWriter("src/output/pdf.html", "utf-8");
|
||||
parser.writeText(pdf, output);
|
||||
output.close();
|
||||
if (pdf != null) {
|
||||
pdf.close();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package com.baeldung.pdf;
|
||||
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.rendering.ImageType;
|
||||
import org.apache.pdfbox.rendering.PDFRenderer;
|
||||
import org.apache.pdfbox.tools.imageio.ImageIOUtil;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
public class PDF2ImageExample {
|
||||
|
||||
private static final String FILENAME = "src/main/resources/pdf.pdf";
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
generateImageFromPDF(FILENAME, "png");
|
||||
generateImageFromPDF(FILENAME, "jpeg");
|
||||
generateImageFromPDF(FILENAME, "gif");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static void generateImageFromPDF(String filename, String extension) throws IOException {
|
||||
PDDocument document = PDDocument.load(new File(filename));
|
||||
PDFRenderer pdfRenderer = new PDFRenderer(document);
|
||||
for (int page = 0; page < document.getNumberOfPages(); ++page) {
|
||||
BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);
|
||||
ImageIOUtil.writeImage(bim, String.format("src/output/pdf-%d.%s", page + 1, extension), 300);
|
||||
}
|
||||
document.close();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
package com.baeldung.pdf;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
import org.apache.pdfbox.cos.COSDocument;
|
||||
import org.apache.pdfbox.io.RandomAccessFile;
|
||||
import org.apache.pdfbox.pdfparser.PDFParser;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.text.PDFTextStripper;
|
||||
|
||||
public class PDF2TextExample {
|
||||
|
||||
private static final String FILENAME = "src/main/resources/pdf.pdf";
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
generateTxtFromPDF(FILENAME);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static void generateTxtFromPDF(String filename) throws IOException {
|
||||
File f = new File(filename);
|
||||
String parsedText;
|
||||
PDFParser parser = new PDFParser(new RandomAccessFile(f, "r"));
|
||||
parser.parse();
|
||||
|
||||
COSDocument cosDoc = parser.getDocument();
|
||||
|
||||
PDFTextStripper pdfStripper = new PDFTextStripper();
|
||||
PDDocument pdDoc = new PDDocument(cosDoc);
|
||||
|
||||
parsedText = pdfStripper.getText(pdDoc);
|
||||
|
||||
if (cosDoc != null)
|
||||
cosDoc.close();
|
||||
if (pdDoc != null)
|
||||
pdDoc.close();
|
||||
|
||||
PrintWriter pw = new PrintWriter("src/output/pdf.txt");
|
||||
pw.print(parsedText);
|
||||
pw.close();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package com.baeldung.pdf;
|
||||
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.poi.xwpf.usermodel.BreakType;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFRun;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfReader;
|
||||
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
|
||||
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
|
||||
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;
|
||||
|
||||
public class PDF2WordExample {
|
||||
|
||||
private static final String FILENAME = "src/main/resources/pdf.pdf";
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
generateDocFromPDF(FILENAME);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static void generateDocFromPDF(String filename) throws IOException {
|
||||
XWPFDocument doc = new XWPFDocument();
|
||||
|
||||
String pdf = filename;
|
||||
PdfReader reader = new PdfReader(pdf);
|
||||
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
|
||||
|
||||
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
|
||||
TextExtractionStrategy strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
|
||||
String text = strategy.getResultantText();
|
||||
XWPFParagraph p = doc.createParagraph();
|
||||
XWPFRun run = p.createRun();
|
||||
run.setText(text);
|
||||
run.addBreak(BreakType.PAGE);
|
||||
}
|
||||
FileOutputStream out = new FileOutputStream("src/output/pdf.docx");
|
||||
doc.write(out);
|
||||
out.close();
|
||||
reader.close();
|
||||
doc.close();
|
||||
}
|
||||
|
||||
}
|
Binary file not shown.
87
pom.xml
87
pom.xml
|
@ -1,5 +1,5 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
|
@ -14,24 +14,25 @@
|
|||
</properties>
|
||||
|
||||
<modules>
|
||||
<module>assertj</module>
|
||||
<module>annotations</module>
|
||||
<module>apache-cxf</module>
|
||||
<!-- <module>apache-fop</module> --> <!-- TODO: has a compilation issue -->
|
||||
<module>apache-fop</module> <!-- TODO: has a compilation issue -->
|
||||
<module>assertj</module>
|
||||
<module>autovalue</module>
|
||||
|
||||
<module>cdi</module>
|
||||
<!-- <module>core-java-9</module> -->
|
||||
<module>core-java</module>
|
||||
<module>couchbase-sdk</module>
|
||||
<!-- <module>core-java-9</module> -->
|
||||
|
||||
<module>dozer</module>
|
||||
<module>deltaspike</module>
|
||||
<module>dozer</module>
|
||||
|
||||
<module>patterns</module>
|
||||
<module>feign</module>
|
||||
<module>flyway</module>
|
||||
|
||||
<!-- <module>gatling</module> --> <!-- not meant to run as part of the standard build -->
|
||||
|
||||
<module>flyway</module>
|
||||
|
||||
<module>gson</module>
|
||||
<module>guava</module>
|
||||
|
@ -39,56 +40,68 @@
|
|||
<module>guava19</module>
|
||||
|
||||
<module>handling-spring-static-resources</module>
|
||||
<module>hazelcast</module>
|
||||
<module>httpclient</module>
|
||||
<module>hystrix</module>
|
||||
|
||||
<module>immutables</module>
|
||||
|
||||
<module>jackson</module>
|
||||
<module>java-cassandra</module>
|
||||
<module>javaxval</module>
|
||||
<module>jjwt</module>
|
||||
|
||||
<module>jpa-storedprocedure</module>
|
||||
<module>json</module>
|
||||
<module>json-path</module>
|
||||
<module>junit5</module>
|
||||
<module>jee7</module>
|
||||
<!-- <module>jpa-storedprocedure</module> -->
|
||||
|
||||
<module>jjwt</module>
|
||||
<module>jpa-storedprocedure</module>
|
||||
<module>jsf</module>
|
||||
<module>json-path</module>
|
||||
<module>json</module>
|
||||
<module>junit5</module>
|
||||
|
||||
<module>log4j</module>
|
||||
<module>lombok</module>
|
||||
|
||||
<module>mapstruct</module>
|
||||
<module>mockito</module>
|
||||
<module>mocks</module>
|
||||
<module>testing</module>
|
||||
|
||||
<module>orika</module>
|
||||
|
||||
<module>patterns</module>
|
||||
|
||||
<module>querydsl</module>
|
||||
|
||||
<!-- <module>raml</module> -->
|
||||
<module>redis</module>
|
||||
<module>rest-assured</module>
|
||||
<module>rest-testing</module>
|
||||
<module>resteasy</module>
|
||||
|
||||
<module>selenium-junit-testng</module>
|
||||
<module>spring-akka</module>
|
||||
<module>spring-all</module>
|
||||
<module>spring-akka</module>
|
||||
<module>spring-apache-camel</module>
|
||||
<module>spring-autowire</module>
|
||||
<module>spring-batch</module>
|
||||
<module>spring-boot</module>
|
||||
<module>spring-cloud-data-flow</module>
|
||||
<module>spring-cloud</module>
|
||||
<module>spring-core</module>
|
||||
<module>spring-cucumber</module>
|
||||
<module>spring-data-cassandra</module>
|
||||
<module>spring-data-couchbase-2</module>
|
||||
<module>spring-data-dynamodb</module>
|
||||
<module>spring-data-elasticsearch</module>
|
||||
<module>spring-data-neo4j</module>
|
||||
<module>spring-data-mongodb</module>
|
||||
<module>spring-data-neo4j</module>
|
||||
<module>spring-data-redis</module>
|
||||
<module>spring-data-rest</module>
|
||||
<!--<module>spring-dispatcher-servlet</module>-->
|
||||
<module>spring-data-solr</module>
|
||||
<module>spring-dispatcher-servlet</module>
|
||||
<module>spring-exceptions</module>
|
||||
<module>spring-freemarker</module>
|
||||
<module>spring-hibernate3</module>
|
||||
<module>spring-hibernate4</module>
|
||||
<module>spring-integration</module>
|
||||
<module>spring-jms</module>
|
||||
<module>spring-jooq</module>
|
||||
<module>spring-jpa</module>
|
||||
|
@ -96,18 +109,16 @@
|
|||
<module>spring-mockito</module>
|
||||
<module>spring-mvc-java</module>
|
||||
<module>spring-mvc-no-xml</module>
|
||||
<module>spring-mvc-xml</module>
|
||||
<module>spring-mvc-tiles</module>
|
||||
<module>spring-mvc-velocity</module>
|
||||
<module>spring-mvc-web-vs-initializer</module>
|
||||
<module>spring-mvc-xml</module>
|
||||
<module>spring-openid</module>
|
||||
<module>spring-protobuf</module>
|
||||
<module>spring-quartz</module>
|
||||
<module>spring-spel</module>
|
||||
<module>spring-rest</module>
|
||||
<module>spring-rest-angular</module>
|
||||
<module>spring-rest-docs</module>
|
||||
<module>spring-cloud</module>
|
||||
<module>spring-cloud-data-flow</module>
|
||||
|
||||
<module>spring-rest</module>
|
||||
<module>spring-security-basic-auth</module>
|
||||
<module>spring-security-custom-permission</module>
|
||||
<module>spring-security-mvc-custom</module>
|
||||
|
@ -116,26 +127,26 @@
|
|||
<module>spring-security-mvc-login</module>
|
||||
<module>spring-security-mvc-persisted-remember-me</module>
|
||||
<module>spring-security-mvc-session</module>
|
||||
<module>spring-security-rest</module>
|
||||
<module>spring-security-rest-basic-auth</module>
|
||||
<module>spring-security-rest-custom</module>
|
||||
<module>spring-security-rest-digest-auth</module>
|
||||
<module>spring-security-rest-full</module>
|
||||
<module>spring-security-rest</module>
|
||||
<module>spring-security-x509</module>
|
||||
<module>spring-session</module>
|
||||
<module>spring-spel</module>
|
||||
<module>spring-thymeleaf</module>
|
||||
<module>spring-userservice</module>
|
||||
<module>spring-zuul</module>
|
||||
<module>spring-mvc-velocity</module>
|
||||
|
||||
<module>jsf</module>
|
||||
<module>xml</module>
|
||||
<module>xmlunit2</module>
|
||||
<module>lombok</module>
|
||||
<module>redis</module>
|
||||
<module>testing</module>
|
||||
|
||||
<module>wicket</module>
|
||||
<module>xstream</module>
|
||||
<module>java-cassandra</module>
|
||||
<module>annotations</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
<module>xml</module>
|
||||
<module>xmlunit2</module>
|
||||
<module>xstream</module>
|
||||
<module>pdf</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
|
@ -9,11 +9,11 @@
|
|||
<servlet-class>
|
||||
org.springframework.web.servlet.DispatcherServlet
|
||||
</servlet-class>
|
||||
<load-on-startup>1</load-on-startup>
|
||||
<init-param>
|
||||
<param-name>contextConfigLocation</param-name>
|
||||
<param-value>/WEB-INF/test-mvc.xml</param-value>
|
||||
</init-param>
|
||||
<load-on-startup>1</load-on-startup>
|
||||
</servlet>
|
||||
|
||||
<servlet-mapping>
|
||||
|
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.camel.file;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
import org.apache.camel.Exchange;
|
||||
import org.apache.camel.Processor;
|
||||
|
||||
public class FileProcessor implements Processor {
|
||||
|
||||
public void process(Exchange exchange) throws Exception {
|
||||
String originalFileName = (String) exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
|
||||
|
||||
Date date = new Date();
|
||||
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
|
||||
String changedFileName = dateFormat.format(date) + originalFileName;
|
||||
exchange.getIn().setHeader(Exchange.FILE_NAME, changedFileName);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.camel.file;
|
||||
|
||||
import org.apache.camel.builder.RouteBuilder;
|
||||
|
||||
public class FileRouter extends RouteBuilder {
|
||||
|
||||
private static final String SOURCE_FOLDER = "src/test/source-folder";
|
||||
private static final String DESTINATION_FOLDER = "src/test/destination-folder";
|
||||
|
||||
@Override
|
||||
public void configure() throws Exception {
|
||||
from("file://" + SOURCE_FOLDER + "?delete=true").process(new FileProcessor()).to("file://" + DESTINATION_FOLDER);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
|
||||
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
|
||||
|
||||
<bean id="fileRouter" class="com.baeldung.camel.file.FileRouter" />
|
||||
<bean id="fileProcessor" class="com.baeldung.camel.file.FileProcessor" />
|
||||
|
||||
<camelContext xmlns="http://camel.apache.org/schema/spring">
|
||||
<routeBuilder ref="fileRouter" />
|
||||
</camelContext>
|
||||
|
||||
</beans>
|
|
@ -1,39 +1,39 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
|
||||
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
|
||||
|
||||
<camelContext xmlns="http://camel.apache.org/schema/spring">
|
||||
<camelContext xmlns="http://camel.apache.org/schema/spring">
|
||||
|
||||
<route customId="true" id="route1">
|
||||
<route customId="true" id="route1">
|
||||
|
||||
<!-- Read files from input directory -->
|
||||
<from uri="file://src/test/data/input"/>
|
||||
<!-- Read files from input directory -->
|
||||
<from uri="file://src/test/data/input" />
|
||||
|
||||
<!-- Transform content to UpperCase -->
|
||||
<process ref="myFileProcessor"/>
|
||||
<!-- Transform content to UpperCase -->
|
||||
<process ref="myFileProcessor" />
|
||||
|
||||
<!-- Write converted file content -->
|
||||
<to uri="file://src/test/data/outputUpperCase"/>
|
||||
<!-- Write converted file content -->
|
||||
<to uri="file://src/test/data/outputUpperCase" />
|
||||
|
||||
<!-- Transform content to LowerCase -->
|
||||
<transform>
|
||||
<simple>${body.toLowerCase()}</simple>
|
||||
</transform>
|
||||
<!-- Transform content to LowerCase -->
|
||||
<transform>
|
||||
<simple>${body.toLowerCase()}</simple>
|
||||
</transform>
|
||||
|
||||
<!-- Write converted file content -->
|
||||
<to uri="file://src/test/data/outputLowerCase"/>
|
||||
<!-- Write converted file content -->
|
||||
<to uri="file://src/test/data/outputLowerCase" />
|
||||
|
||||
<!-- Display process completion message on console -->
|
||||
<transform>
|
||||
<simple>.......... File content conversion completed ..........</simple>
|
||||
</transform>
|
||||
<to uri="stream:out"/>
|
||||
<!-- Display process completion message on console -->
|
||||
<transform>
|
||||
<simple>.......... File content conversion completed ..........</simple>
|
||||
</transform>
|
||||
<to uri="stream:out" />
|
||||
|
||||
</route>
|
||||
</route>
|
||||
|
||||
</camelContext>
|
||||
</camelContext>
|
||||
|
||||
<bean id="myFileProcessor" class="com.baeldung.camel.processor.FileProcessor"/>
|
||||
<bean id="myFileProcessor" class="com.baeldung.camel.processor.FileProcessor" />
|
||||
</beans>
|
|
@ -0,0 +1,68 @@
|
|||
package org.apache.camel.file.processor;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import org.apache.camel.CamelContext;
|
||||
import org.apache.camel.builder.RouteBuilder;
|
||||
import org.apache.camel.impl.DefaultCamelContext;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
|
||||
import com.baeldung.camel.file.FileProcessor;
|
||||
|
||||
|
||||
public class FileProcessorTest {
|
||||
|
||||
private static final long DURATION_MILIS = 10000;
|
||||
private static final String SOURCE_FOLDER = "src/test/source-folder";
|
||||
private static final String DESTINATION_FOLDER = "src/test/destination-folder";
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
File sourceFolder = new File(SOURCE_FOLDER);
|
||||
File destinationFolder = new File(DESTINATION_FOLDER);
|
||||
|
||||
cleanFolder(sourceFolder);
|
||||
cleanFolder(destinationFolder);
|
||||
|
||||
sourceFolder.mkdirs();
|
||||
File file1 = new File(SOURCE_FOLDER + "/File1.txt");
|
||||
File file2 = new File(SOURCE_FOLDER + "/File2.txt");
|
||||
file1.createNewFile();
|
||||
file2.createNewFile();
|
||||
}
|
||||
|
||||
private void cleanFolder(File folder) {
|
||||
File[] files = folder.listFiles();
|
||||
if (files != null) {
|
||||
for (File file : files) {
|
||||
if (file.isFile()) {
|
||||
file.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void moveFolderContentJavaDSLTest() throws Exception {
|
||||
final CamelContext camelContext = new DefaultCamelContext();
|
||||
camelContext.addRoutes(new RouteBuilder() {
|
||||
@Override
|
||||
public void configure() throws Exception {
|
||||
from("file://" + SOURCE_FOLDER + "?delete=true").process(new FileProcessor()).to("file://" + DESTINATION_FOLDER);
|
||||
}
|
||||
});
|
||||
camelContext.start();
|
||||
Thread.sleep(DURATION_MILIS);
|
||||
camelContext.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void moveFolderContentSpringDSLTest() throws InterruptedException {
|
||||
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("camel-context-test.xml");
|
||||
Thread.sleep(DURATION_MILIS);
|
||||
applicationContext.close();
|
||||
|
||||
}
|
||||
}
|
|
@ -11,6 +11,7 @@
|
|||
<module>spring-cloud-eureka</module>
|
||||
<module>spring-cloud-hystrix</module>
|
||||
<module>spring-cloud-bootstrap</module>
|
||||
<module>spring-cloud-ribbon-client</module>
|
||||
</modules>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
user.role=User
|
|
@ -6,49 +6,30 @@
|
|||
<parent>
|
||||
<groupId>com.baeldung.spring.cloud</groupId>
|
||||
<artifactId>spring-cloud-config</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>client</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>client</name>
|
||||
<description>Demo project for Spring Cloud Config Client</description>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-config</artifactId>
|
||||
<version>1.2.0.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<version>${org.springframework.boot.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<version>${org.springframework.boot.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>Brixton.BUILD-SNAPSHOT</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -57,23 +38,4 @@
|
|||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
<url>https://repo.spring.io/milestone</url>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
</project>
|
||||
|
|
|
@ -3,3 +3,4 @@ spring.profiles.active=development
|
|||
spring.cloud.config.uri=http://localhost:8888
|
||||
spring.cloud.config.username=root
|
||||
spring.cloud.config.password=s3cr3t
|
||||
spring.cloud.config.fail-fast=true
|
||||
|
|
|
@ -0,0 +1,2 @@
|
|||
user.role=User
|
||||
user.password=pass
|
|
@ -5,7 +5,7 @@
|
|||
|
||||
<groupId>com.baeldung.spring.cloud</groupId>
|
||||
<artifactId>spring-cloud-config</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<modules>
|
||||
|
@ -16,9 +16,22 @@
|
|||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.3.5.RELEASE</version>
|
||||
<version>1.4.1.RELEASE</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>Camden.SR1</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -36,7 +49,10 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<org.springframework.boot.version>1.3.5.RELEASE</org.springframework.boot.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<org.springframework.boot.version>1.4.1.RELEASE</org.springframework.boot.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
|
@ -6,77 +6,42 @@
|
|||
<parent>
|
||||
<groupId>com.baeldung.spring.cloud</groupId>
|
||||
<artifactId>spring-cloud-config</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>server</artifactId>
|
||||
|
||||
<name>server</name>
|
||||
<description>Demo project for Spring Cloud Config Server</description>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-config-server</artifactId>
|
||||
<version>1.2.0.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
<version>${org.springframework.boot.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<version>${org.springframework.boot.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<version>${org.springframework.boot.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>Brixton.BUILD-SNAPSHOT</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${org.springframework.boot.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
<url>https://repo.spring.io/milestone</url>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
</project>
|
||||
|
|
|
@ -3,11 +3,9 @@ package com.baeldung.spring.cloud.config.server;
|
|||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.cloud.config.server.EnableConfigServer;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableConfigServer
|
||||
@EnableWebSecurity
|
||||
public class ConfigServer {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ConfigServer.class, args);
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
server.port=8888
|
||||
spring.cloud.config.server.git.uri=https://github.com/spring-cloud-samples/config-repo
|
||||
spring.cloud.config.server.git.uri=
|
||||
spring.cloud.config.server.git.clone-on-start=true
|
||||
security.user.name=root
|
||||
security.user.password=s3cr3t
|
||||
|
|
|
@ -0,0 +1,79 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-cloud-ribbon</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>spring-cloud-ribbon-client</name>
|
||||
<description>Introduction to Spring Cloud Rest Client with Netflix Ribbon</description>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.4.1.RELEASE</version>
|
||||
<relativePath /> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-ribbon</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>Camden.SR1</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
<url>https://repo.spring.io/milestone</url>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
</project>
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.spring.cloud.ribbon.client;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
import com.netflix.client.config.IClientConfig;
|
||||
import com.netflix.loadbalancer.IPing;
|
||||
import com.netflix.loadbalancer.IRule;
|
||||
import com.netflix.loadbalancer.PingUrl;
|
||||
import com.netflix.loadbalancer.WeightedResponseTimeRule;
|
||||
import com.netflix.loadbalancer.AvailabilityFilteringRule;
|
||||
|
||||
public class RibbonConfiguration {
|
||||
|
||||
@Autowired
|
||||
IClientConfig ribbonClientConfig;
|
||||
|
||||
@Bean
|
||||
public IPing ribbonPing(IClientConfig config) {
|
||||
return new PingUrl();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IRule ribbonRule(IClientConfig config) {
|
||||
return new WeightedResponseTimeRule();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.spring.cloud.ribbon.client;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
|
||||
import org.springframework.cloud.netflix.ribbon.RibbonClient;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@SpringBootApplication
|
||||
@RestController
|
||||
@RibbonClient(name = "ping-a-server", configuration = RibbonConfiguration.class)
|
||||
public class ServerLocationApp {
|
||||
|
||||
@LoadBalanced
|
||||
@Bean
|
||||
RestTemplate getRestTemplate() {
|
||||
return new RestTemplate();
|
||||
}
|
||||
|
||||
@Autowired
|
||||
RestTemplate restTemplate;
|
||||
|
||||
@RequestMapping("/server-location")
|
||||
public String serverLocation() {
|
||||
String servLoc = this.restTemplate.getForObject("http://ping-server/locaus", String.class);
|
||||
return servLoc;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ServerLocationApp.class, args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
spring:
|
||||
application:
|
||||
name: spring-cloud-ribbon
|
||||
|
||||
server:
|
||||
port: 8888
|
||||
|
||||
ping-server:
|
||||
ribbon:
|
||||
eureka:
|
||||
enabled: false
|
||||
listOfServers: localhost:9092,localhost:9999
|
||||
ServerListRefreshInterval: 15000
|
|
@ -0,0 +1,54 @@
|
|||
package com.baeldung.spring.cloud.ribbon.client;
|
||||
|
||||
import static org.assertj.core.api.BDDAssertions.then;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.context.embedded.LocalServerPort;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = ServerLocationApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
public class ServerLocationAppTests {
|
||||
ConfigurableApplicationContext application2;
|
||||
ConfigurableApplicationContext application3;
|
||||
|
||||
@Before
|
||||
public void startApps() {
|
||||
this.application2 = startApp(9092);
|
||||
this.application3 = startApp(9999);
|
||||
}
|
||||
|
||||
@After
|
||||
public void closeApps() {
|
||||
this.application2.close();
|
||||
this.application3.close();
|
||||
}
|
||||
|
||||
@LocalServerPort
|
||||
private int port;
|
||||
|
||||
@Autowired
|
||||
private TestRestTemplate testRestTemplate;
|
||||
|
||||
@Test
|
||||
public void loadBalancingServersTest() throws InterruptedException {
|
||||
ResponseEntity<String> response = this.testRestTemplate.getForEntity("http://localhost:" + this.port + "/server-location", String.class);
|
||||
assertEquals(response.getBody(), "Australia");
|
||||
}
|
||||
|
||||
private ConfigurableApplicationContext startApp(int port) {
|
||||
return SpringApplication.run(TestConfig.class, "--server.port=" + port, "--spring.jmx.enabled=false");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.spring.cloud.ribbon.client;
|
||||
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@RestController
|
||||
public class TestConfig {
|
||||
|
||||
@RequestMapping(value = "/locaus")
|
||||
public String locationAUSDetails() {
|
||||
return "Australia";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,69 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-data-solr</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>spring-data-solr</name>
|
||||
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<spring.version>4.2.5.RELEASE</spring.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<spring-data-solr>2.0.4.RELEASE</spring-data-solr>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-solr</artifactId>
|
||||
<version>${spring-data-solr}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>1.2.16</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<includes>
|
||||
<include>**/*IntegrationTest.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.spring.data.solr.config;
|
||||
|
||||
import org.apache.solr.client.solrj.SolrClient;
|
||||
import org.apache.solr.client.solrj.impl.HttpSolrClient;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.solr.core.SolrTemplate;
|
||||
import org.springframework.data.solr.repository.config.EnableSolrRepositories;
|
||||
|
||||
@Configuration
|
||||
@EnableSolrRepositories(basePackages = "com.baeldung.spring.data.solr.repository", namedQueriesLocation = "classpath:solr-named-queries.properties", multicoreSupport = true)
|
||||
@ComponentScan
|
||||
public class SolrConfig {
|
||||
|
||||
@Bean
|
||||
public SolrClient solrClient() {
|
||||
return new HttpSolrClient("http://localhost:8983/solr");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SolrTemplate solrTemplate(SolrClient client) throws Exception {
|
||||
return new SolrTemplate(client);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
package com.baeldung.spring.data.solr.model;
|
||||
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.solr.core.mapping.Indexed;
|
||||
import org.springframework.data.solr.core.mapping.SolrDocument;
|
||||
|
||||
@SolrDocument(solrCoreName = "product")
|
||||
public class Product {
|
||||
|
||||
@Id
|
||||
@Indexed(name = "id", type = "string")
|
||||
private String id;
|
||||
|
||||
@Indexed(name = "name", type = "string")
|
||||
private String name;
|
||||
|
||||
@Indexed(name = "category", type = "string")
|
||||
private String category;
|
||||
|
||||
@Indexed(name = "description", type = "string")
|
||||
private String 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 getCategory() {
|
||||
return category;
|
||||
}
|
||||
|
||||
public void setCategory(String category) {
|
||||
this.category = category;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.spring.data.solr.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.solr.repository.Query;
|
||||
import org.springframework.data.solr.repository.SolrCrudRepository;
|
||||
|
||||
import com.baeldung.spring.data.solr.model.Product;
|
||||
|
||||
public interface ProductRepository extends SolrCrudRepository<Product, String> {
|
||||
|
||||
public List<Product> findByName(String name);
|
||||
|
||||
@Query("name:*?0* OR category:*?0* OR description:*?0*")
|
||||
public Page<Product> findByCustomQuery(String searchTerm, Pageable pageable);
|
||||
|
||||
@Query(name = "Product.findByNamedQuery")
|
||||
public Page<Product> findByNamedQuery(String searchTerm, Pageable pageable);
|
||||
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
Product.findByNamedQuery=name:*?0* OR category:*?0* OR description:*?0*
|
|
@ -0,0 +1,144 @@
|
|||
package com.baeldung.spring.data.solr.repo;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import com.baeldung.spring.data.solr.config.SolrConfig;
|
||||
import com.baeldung.spring.data.solr.model.Product;
|
||||
import com.baeldung.spring.data.solr.repository.ProductRepository;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = SolrConfig.class)
|
||||
public class ProductRepositoryIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private ProductRepository productRepository;
|
||||
|
||||
@Before
|
||||
public void clearSolrData() {
|
||||
productRepository.deleteAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSavingProduct_thenAvailableOnRetrieval() throws Exception {
|
||||
final Product product = new Product();
|
||||
product.setId("P000089998");
|
||||
product.setName("Desk");
|
||||
product.setCategory("Furniture");
|
||||
product.setDescription("New Desk");
|
||||
productRepository.save(product);
|
||||
final Product retrievedProduct = productRepository.findOne(product.getId());
|
||||
assertEquals(product.getId(), retrievedProduct.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpdatingProduct_thenChangeAvailableOnRetrieval() throws Exception {
|
||||
final Product product = new Product();
|
||||
product.setId("P0001");
|
||||
product.setName("T-Shirt");
|
||||
product.setCategory("Kitchen");
|
||||
product.setDescription("New T-Shirt");
|
||||
productRepository.save(product);
|
||||
|
||||
product.setCategory("Clothes");
|
||||
productRepository.save(product);
|
||||
|
||||
final Product retrievedProduct = productRepository.findOne(product.getId());
|
||||
assertEquals(product.getCategory(), retrievedProduct.getCategory());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeletingProduct_thenNotAvailableOnRetrieval() throws Exception {
|
||||
final Product product = new Product();
|
||||
product.setId("P0001");
|
||||
product.setName("Desk");
|
||||
product.setCategory("Furniture");
|
||||
product.setDescription("New Desk");
|
||||
productRepository.save(product);
|
||||
|
||||
productRepository.delete(product);
|
||||
|
||||
Product retrievedProduct = productRepository.findOne(product.getId());
|
||||
assertNull(retrievedProduct);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFindByName_thenAvailableOnRetrieval() throws Exception {
|
||||
Product phone = new Product();
|
||||
phone.setId("P0001");
|
||||
phone.setName("Phone");
|
||||
phone.setCategory("Electronics");
|
||||
phone.setDescription("New Phone");
|
||||
productRepository.save(phone);
|
||||
|
||||
List<Product> retrievedProducts = productRepository.findByName("Phone");
|
||||
assertEquals(phone.getId(), retrievedProducts.get(0).getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSearchingProductsByQuery_thenAllMatchingProductsShouldAvialble() throws Exception {
|
||||
final Product phone = new Product();
|
||||
phone.setId("P0001");
|
||||
phone.setName("Smart Phone");
|
||||
phone.setCategory("Electronics");
|
||||
phone.setDescription("New Item");
|
||||
productRepository.save(phone);
|
||||
|
||||
final Product phoneCover = new Product();
|
||||
phoneCover.setId("P0002");
|
||||
phoneCover.setName("Cover");
|
||||
phoneCover.setCategory("Phone");
|
||||
phoneCover.setDescription("New Product");
|
||||
productRepository.save(phoneCover);
|
||||
|
||||
final Product wirelessCharger = new Product();
|
||||
wirelessCharger.setId("P0003");
|
||||
wirelessCharger.setName("Charging Cable");
|
||||
wirelessCharger.setCategory("Cable");
|
||||
wirelessCharger.setDescription("Wireless Charger for Phone");
|
||||
productRepository.save(wirelessCharger);
|
||||
|
||||
Page<Product> result = productRepository.findByCustomQuery("Phone", new PageRequest(0, 10));
|
||||
assertEquals(3, result.getNumberOfElements());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSearchingProductsByNamedQuery_thenAllMatchingProductsShouldAvialble() throws Exception {
|
||||
final Product phone = new Product();
|
||||
phone.setId("P0001");
|
||||
phone.setName("Smart Phone");
|
||||
phone.setCategory("Electronics");
|
||||
phone.setDescription("New Item");
|
||||
productRepository.save(phone);
|
||||
|
||||
final Product phoneCover = new Product();
|
||||
phoneCover.setId("P0002");
|
||||
phoneCover.setName("Cover");
|
||||
phoneCover.setCategory("Phone");
|
||||
phoneCover.setDescription("New Product");
|
||||
productRepository.save(phoneCover);
|
||||
|
||||
final Product wirelessCharger = new Product();
|
||||
wirelessCharger.setId("P0003");
|
||||
wirelessCharger.setName("Charging Cable");
|
||||
wirelessCharger.setCategory("Cable");
|
||||
wirelessCharger.setDescription("Wireless Charger for Phone");
|
||||
productRepository.save(wirelessCharger);
|
||||
|
||||
Page<Product> result = productRepository.findByNamedQuery("one", new PageRequest(0, 10));
|
||||
assertEquals(3, result.getNumberOfElements());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,82 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>spring-dispatcher-servlet</artifactId>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>..</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<version>4.3.3.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.thymeleaf</groupId>
|
||||
<artifactId>thymeleaf-spring4</artifactId>
|
||||
<version>3.0.2.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>1.7.21</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>2.7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-slf4j-impl</artifactId>
|
||||
<version>2.7</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>3.0.0</version>
|
||||
<configuration>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-maven-plugin</artifactId>
|
||||
<version>9.3.12.v20160915</version>
|
||||
<configuration>
|
||||
<webApp>
|
||||
<contextPath>/</contextPath>
|
||||
</webApp>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.spring.dispatcher.servlet;
|
||||
|
||||
import com.baeldung.spring.dispatcher.servlet.models.Task;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
@Configuration
|
||||
public class RootConfiguration {
|
||||
@Bean
|
||||
public Map<String, List<Task>> taskList() {
|
||||
Map<String, List<Task>> taskMap = new HashMap<>();
|
||||
List<Task> taskList = new ArrayList<>();
|
||||
taskList.add(new Task("Clean the dishes!", new Date()));
|
||||
taskMap.put("Cid", taskList);
|
||||
return taskMap;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.spring.dispatcher.servlet;
|
||||
|
||||
import org.springframework.web.context.ContextLoaderListener;
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
import org.springframework.web.servlet.DispatcherServlet;
|
||||
|
||||
import javax.servlet.MultipartConfigElement;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRegistration;
|
||||
|
||||
public class WebApplicationInitializer implements org.springframework.web.WebApplicationInitializer {
|
||||
@Override
|
||||
public void onStartup(ServletContext servletContext) throws ServletException {
|
||||
AnnotationConfigWebApplicationContext rootContext =
|
||||
new AnnotationConfigWebApplicationContext();
|
||||
rootContext.register(RootConfiguration.class);
|
||||
servletContext.addListener(new ContextLoaderListener(rootContext));
|
||||
AnnotationConfigWebApplicationContext webContext =
|
||||
new AnnotationConfigWebApplicationContext();
|
||||
webContext.register(WebConfiguration.class);
|
||||
DispatcherServlet dispatcherServlet = new DispatcherServlet(webContext);
|
||||
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher",
|
||||
dispatcherServlet);
|
||||
servlet.addMapping("/*");
|
||||
MultipartConfigElement multipartConfigElement =
|
||||
new MultipartConfigElement("/tmp");
|
||||
servlet.setMultipartConfig(multipartConfigElement);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,129 @@
|
|||
package com.baeldung.spring.dispatcher.servlet;
|
||||
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.support.ResourceBundleMessageSource;
|
||||
import org.springframework.ui.context.support.ResourceBundleThemeSource;
|
||||
import org.springframework.web.multipart.MultipartResolver;
|
||||
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
|
||||
import org.springframework.web.servlet.HandlerExceptionResolver;
|
||||
import org.springframework.web.servlet.LocaleResolver;
|
||||
import org.springframework.web.servlet.ThemeResolver;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
|
||||
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
|
||||
import org.springframework.web.servlet.theme.CookieThemeResolver;
|
||||
import org.springframework.web.servlet.theme.ThemeChangeInterceptor;
|
||||
import org.thymeleaf.spring4.SpringTemplateEngine;
|
||||
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
|
||||
import org.thymeleaf.templatemode.TemplateMode;
|
||||
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import java.util.Locale;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan("com.baeldung.spring.dispatcher.servlet.web")
|
||||
@EnableWebMvc
|
||||
public class WebConfiguration extends WebMvcConfigurerAdapter {
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry
|
||||
.addResourceHandler("/public/**")
|
||||
.addResourceLocations("/public/");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(localeChangeInterceptor());
|
||||
registry.addInterceptor(themeChangeInterceptor());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ServletContextTemplateResolver templateResolver(ServletContext servletContext) {
|
||||
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext);
|
||||
templateResolver.setPrefix("/WEB-INF/views/");
|
||||
templateResolver.setSuffix(".html");
|
||||
templateResolver.setTemplateMode(TemplateMode.HTML);
|
||||
return templateResolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SpringTemplateEngine templateEngine(ServletContextTemplateResolver templateResolver) {
|
||||
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
|
||||
templateEngine.setTemplateResolver(templateResolver);
|
||||
return templateEngine;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ThymeleafViewResolver viewResolver(SpringTemplateEngine templateEngine) {
|
||||
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
|
||||
viewResolver.setTemplateEngine(templateEngine);
|
||||
return viewResolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MessageSource messageSource() {
|
||||
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
|
||||
messageSource.setBasename("messages");
|
||||
messageSource.setFallbackToSystemLocale(false);
|
||||
return messageSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocaleResolver localeResolver() {
|
||||
CookieLocaleResolver localeResolver = new CookieLocaleResolver();
|
||||
localeResolver.setDefaultLocale(Locale.ENGLISH);
|
||||
localeResolver.setCookieName("locale");
|
||||
localeResolver.setCookieMaxAge(-1);
|
||||
return localeResolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocaleChangeInterceptor localeChangeInterceptor() {
|
||||
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
|
||||
localeChangeInterceptor.setParamName("lang");
|
||||
localeChangeInterceptor.setIgnoreInvalidLocale(true);
|
||||
return localeChangeInterceptor;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ResourceBundleThemeSource themeSource() {
|
||||
ResourceBundleThemeSource themeSource = new ResourceBundleThemeSource();
|
||||
themeSource.setBasenamePrefix("theme-");
|
||||
themeSource.setFallbackToSystemLocale(false);
|
||||
return themeSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ThemeResolver themeResolver() {
|
||||
CookieThemeResolver themeResolver = new CookieThemeResolver();
|
||||
themeResolver.setDefaultThemeName("robotask");
|
||||
themeResolver.setCookieName("theme");
|
||||
themeResolver.setCookieMaxAge(-1);
|
||||
return themeResolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ThemeChangeInterceptor themeChangeInterceptor() {
|
||||
ThemeChangeInterceptor themeChangeInterceptor = new ThemeChangeInterceptor();
|
||||
themeChangeInterceptor.setParamName("theme");
|
||||
return themeChangeInterceptor;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MultipartResolver multipartResolver() {
|
||||
return new StandardServletMultipartResolver();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public HandlerExceptionResolver handlerExceptionResolver() {
|
||||
return new ExceptionHandlerExceptionResolver();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
package com.baeldung.spring.dispatcher.servlet.models;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class Attachment {
|
||||
private String id;
|
||||
|
||||
private String name;
|
||||
|
||||
private String description;
|
||||
|
||||
public Attachment() {
|
||||
this.id = UUID.randomUUID().toString();
|
||||
}
|
||||
|
||||
public Attachment(String name, String description) {
|
||||
this();
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Attachment that = (Attachment) o;
|
||||
return id.equals(that.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return id.hashCode();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package com.baeldung.spring.dispatcher.servlet.models;
|
||||
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class Task {
|
||||
private String description;
|
||||
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd'T'hh:mm")
|
||||
private Date due;
|
||||
|
||||
private Set<Attachment> attachments = new HashSet<>();
|
||||
|
||||
public Task() {
|
||||
}
|
||||
|
||||
public Task(Date due) {
|
||||
this.due = due;
|
||||
}
|
||||
|
||||
public Task(String description, Date due) {
|
||||
this.description = description;
|
||||
this.due = due;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Date getDue() {
|
||||
return due;
|
||||
}
|
||||
|
||||
public void setDue(Date due) {
|
||||
this.due = due;
|
||||
}
|
||||
|
||||
public Set<Attachment> getAttachments() {
|
||||
return attachments;
|
||||
}
|
||||
|
||||
public void setAttachments(Set<Attachment> attachments) {
|
||||
this.attachments = attachments;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.spring.dispatcher.servlet.web;
|
||||
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
@RequestMapping("/attachments")
|
||||
public interface AttachmentController {
|
||||
@GetMapping("/{attachmentId}")
|
||||
ResponseEntity<FileSystemResource> getAttachment(
|
||||
@PathVariable("attachmentId") String attachmentId,
|
||||
@RequestParam(name = "download", required = false, defaultValue = "false") boolean forcedDownload
|
||||
);
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.spring.dispatcher.servlet.web;
|
||||
|
||||
import com.baeldung.spring.dispatcher.servlet.models.Task;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import java.net.URLConnection;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Controller
|
||||
public class AttachmentControllerImpl implements AttachmentController {
|
||||
@Autowired
|
||||
private Map<String, List<Task>> taskMap;
|
||||
|
||||
@Override
|
||||
public ResponseEntity<FileSystemResource> getAttachment(
|
||||
@PathVariable("attachmentId") String attachmentId,
|
||||
@RequestParam(name = "download", required = false, defaultValue = "false") boolean forcedDownload
|
||||
) {
|
||||
FileSystemResource resource = new FileSystemResource("/tmp/" + attachmentId);
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
taskMap.values().stream()
|
||||
.flatMap(Collection::stream)
|
||||
.flatMap(t -> t.getAttachments().stream())
|
||||
.filter(a -> a.getId().equals(attachmentId))
|
||||
.findFirst()
|
||||
.ifPresent(a -> {
|
||||
headers.add("Content-Disposition",
|
||||
"attachment; filename=" + a.getName());
|
||||
headers.add("Content-Type", forcedDownload ?
|
||||
MediaType.APPLICATION_OCTET_STREAM_VALUE :
|
||||
URLConnection.guessContentTypeFromName(a.getName()));
|
||||
});
|
||||
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.spring.dispatcher.servlet.web;
|
||||
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@ControllerAdvice
|
||||
public class GlobalDefaultExceptionHandler {
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception e) throws Exception {
|
||||
ModelAndView modelAndView = new ModelAndView();
|
||||
modelAndView.addObject("exception", e);
|
||||
modelAndView.addObject("url", request.getRequestURL());
|
||||
modelAndView.setViewName("error");
|
||||
return modelAndView;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.spring.dispatcher.servlet.web;
|
||||
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
@RequestMapping("/")
|
||||
public interface HomeController {
|
||||
@GetMapping("/*")
|
||||
String home(
|
||||
Model model
|
||||
);
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.spring.dispatcher.servlet.web;
|
||||
|
||||
import com.baeldung.spring.dispatcher.servlet.models.Task;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Controller
|
||||
public class HomeControllerImpl implements HomeController {
|
||||
@Autowired
|
||||
private Map<String, List<Task>> taskMap;
|
||||
|
||||
@Override
|
||||
public String home(Model model) {
|
||||
List<String> users = taskMap.keySet().stream()
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
model.addAttribute("users", users);
|
||||
return "home";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
package com.baeldung.spring.dispatcher.servlet.web;
|
||||
|
||||
import com.baeldung.spring.dispatcher.servlet.models.Task;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@RequestMapping("/tasks")
|
||||
public interface TaskController {
|
||||
@GetMapping("/{username}/list")
|
||||
String listTasks(
|
||||
@PathVariable("username") String username,
|
||||
Model model
|
||||
);
|
||||
|
||||
@GetMapping("/{username}/add")
|
||||
String addTask(
|
||||
@PathVariable("username") String username,
|
||||
Model model
|
||||
);
|
||||
|
||||
@PostMapping("/{username}/add")
|
||||
String addTask(
|
||||
@PathVariable("username") String username,
|
||||
@ModelAttribute Task task
|
||||
);
|
||||
|
||||
@GetMapping("/{username}/get/{id}")
|
||||
String getTask(
|
||||
@PathVariable("username") String username,
|
||||
@PathVariable("id") int id,
|
||||
Model model
|
||||
);
|
||||
|
||||
@GetMapping("/{username}/get/{id}/attach")
|
||||
String attachToTask(
|
||||
@PathVariable("username") String username,
|
||||
@PathVariable("id") int id,
|
||||
Model model
|
||||
);
|
||||
|
||||
@PostMapping("/{username}/get/{id}/attach")
|
||||
String attachToTask(
|
||||
@PathVariable("username") String username,
|
||||
@PathVariable("id") int id,
|
||||
@RequestParam("attachment") MultipartFile attachment,
|
||||
@RequestParam("description") String description
|
||||
);
|
||||
}
|
|
@ -0,0 +1,111 @@
|
|||
package com.baeldung.spring.dispatcher.servlet.web;
|
||||
|
||||
import com.baeldung.spring.dispatcher.servlet.models.Attachment;
|
||||
import com.baeldung.spring.dispatcher.servlet.models.Task;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Controller
|
||||
public class TaskControllerImpl implements TaskController {
|
||||
@Autowired
|
||||
private Map<String, List<Task>> taskMap;
|
||||
|
||||
@Override
|
||||
public String listTasks(
|
||||
@PathVariable("username") String username,
|
||||
Model model
|
||||
) {
|
||||
List<Task> tasks = taskMap.get(username).stream()
|
||||
.sorted(Comparator.comparing(Task::getDue))
|
||||
.collect(Collectors.toList());
|
||||
model.addAttribute("username", username);
|
||||
model.addAttribute("tasks", tasks);
|
||||
return "task-list";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String addTask(
|
||||
@PathVariable("username") String username,
|
||||
Model model
|
||||
) {
|
||||
model.addAttribute("username", username);
|
||||
model.addAttribute("task", new Task(new Date()));
|
||||
return "task-add";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String addTask(
|
||||
@PathVariable("username") String username,
|
||||
@ModelAttribute Task task
|
||||
) {
|
||||
List<Task> taskList = taskMap.get(username);
|
||||
if (taskList == null) {
|
||||
taskList = new ArrayList<>();
|
||||
}
|
||||
taskList.add(task);
|
||||
taskMap.put(username, taskList);
|
||||
return "redirect:list";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTask(
|
||||
@PathVariable("username") String username,
|
||||
@PathVariable("id") int id,
|
||||
Model model
|
||||
) {
|
||||
Task task = taskMap.get(username).get(id);
|
||||
model.addAttribute("username", username);
|
||||
model.addAttribute("id", id);
|
||||
model.addAttribute("task", task);
|
||||
return "task-get";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String attachToTask(
|
||||
@PathVariable("username") String username,
|
||||
@PathVariable("id") int id,
|
||||
Model model
|
||||
) {
|
||||
model.addAttribute("username", username);
|
||||
model.addAttribute("id", id);
|
||||
return "task-attach";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String attachToTask(
|
||||
@PathVariable("username") String username,
|
||||
@PathVariable("id") int id,
|
||||
@RequestParam("attachment") MultipartFile multipartFile,
|
||||
@RequestParam("description") String description
|
||||
) {
|
||||
Task task = taskMap.get(username).get(id);
|
||||
Attachment attachment = new Attachment(multipartFile.getOriginalFilename(),
|
||||
description);
|
||||
task.getAttachments().add(attachment);
|
||||
try (InputStream inputStream =
|
||||
new BufferedInputStream(multipartFile.getInputStream());
|
||||
OutputStream outputStream =
|
||||
new BufferedOutputStream(Files.newOutputStream(
|
||||
Paths.get("/tmp", attachment.getId())))) {
|
||||
byte[] buf = new byte[1024 * 16];
|
||||
int len;
|
||||
while ((len = inputStream.read(buf)) != -1) {
|
||||
outputStream.write(buf, 0, len);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to upload file!", e);
|
||||
}
|
||||
return "redirect:./";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="WARN">
|
||||
<Appenders>
|
||||
<Console name="Console" target="SYSTEM_OUT">
|
||||
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36}:%n[+] %msg%n"/>
|
||||
</Console>
|
||||
</Appenders>
|
||||
|
||||
<Loggers>
|
||||
<Root level="info">
|
||||
<AppenderRef ref="Console"/>
|
||||
</Root>
|
||||
</Loggers>
|
||||
</Configuration>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue