Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
c05945bfb4
|
@ -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;
|
||||
|
|
@ -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;
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,7 +4,6 @@ import static org.junit.Assert.assertFalse;
|
|||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.CopyOption;
|
||||
import java.nio.file.DirectoryNotEmptyException;
|
||||
import java.nio.file.FileAlreadyExistsException;
|
||||
import java.nio.file.Files;
|
||||
|
@ -12,7 +11,7 @@ import java.nio.file.NoSuchFileException;
|
|||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Date;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
|
@ -33,7 +32,7 @@ public class FileTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsNotRegularFile_thenCorrect() {
|
||||
public void givenDirPath_whenConfirmsNotRegularFile_thenCorrect() {
|
||||
Path p = Paths.get(HOME);
|
||||
assertFalse(Files.isRegularFile(p));
|
||||
}
|
||||
|
@ -67,7 +66,7 @@ public class FileTest {
|
|||
// creating file
|
||||
@Test
|
||||
public void givenFilePath_whenCreatesNewFile_thenCorrect() throws IOException {
|
||||
String fileName = "myfile_" + new Date().getTime() + ".txt";
|
||||
String fileName = "myfile_" + UUID.randomUUID().toString() + ".txt";
|
||||
Path p = Paths.get(HOME + "/" + fileName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createFile(p);
|
||||
|
@ -77,7 +76,7 @@ public class FileTest {
|
|||
|
||||
@Test
|
||||
public void givenDirPath_whenCreatesNewDir_thenCorrect() throws IOException {
|
||||
String dirName = "myDir_" + new Date().getTime();
|
||||
String dirName = "myDir_" + UUID.randomUUID().toString();
|
||||
Path p = Paths.get(HOME + "/" + dirName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createDirectory(p);
|
||||
|
@ -89,7 +88,7 @@ public class FileTest {
|
|||
|
||||
@Test(expected = NoSuchFileException.class)
|
||||
public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() throws IOException {
|
||||
String dirName = "myDir_" + new Date().getTime() + "/subdir";
|
||||
String dirName = "myDir_" + UUID.randomUUID().toString() + "/subdir";
|
||||
Path p = Paths.get(HOME + "/" + dirName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createDirectory(p);
|
||||
|
@ -98,7 +97,7 @@ public class FileTest {
|
|||
|
||||
@Test
|
||||
public void givenDirPath_whenCreatesRecursively_thenCorrect() throws IOException {
|
||||
Path dir = Paths.get(HOME + "/myDir_" + new Date().getTime());
|
||||
Path dir = Paths.get(HOME + "/myDir_" + UUID.randomUUID().toString());
|
||||
Path subdir = dir.resolve("subdir");
|
||||
assertFalse(Files.exists(dir));
|
||||
assertFalse(Files.exists(subdir));
|
||||
|
@ -119,7 +118,7 @@ public class FileTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void givenFilePath_whenCreatesTempFileWithDefaultsNaming_thenCorrect() throws IOException {
|
||||
public void givenPath_whenCreatesTempFileWithDefaults_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(HOME + "/");
|
||||
p = Files.createTempFile(p, null, null);
|
||||
// like 8600179353689423985.tmp
|
||||
|
@ -148,7 +147,7 @@ public class FileTest {
|
|||
|
||||
@Test(expected = DirectoryNotEmptyException.class)
|
||||
public void givenPath_whenFailsToDeleteNonEmptyDir_thenCorrect() throws IOException {
|
||||
Path dir = Paths.get(HOME + "/emptyDir" + new Date().getTime());
|
||||
Path dir = Paths.get(HOME + "/emptyDir" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir);
|
||||
assertTrue(Files.exists(dir));
|
||||
Path file = dir.resolve("file.txt");
|
||||
|
@ -159,15 +158,11 @@ public class FileTest {
|
|||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Test(expected = NoSuchFileException.class)
|
||||
public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(HOME + "/inexistentFile.txt");
|
||||
assertFalse(Files.exists(p));
|
||||
try {
|
||||
Files.delete(p);
|
||||
} catch (IOException e) {
|
||||
assertTrue(e instanceof NoSuchFileException);
|
||||
}
|
||||
Files.delete(p);
|
||||
|
||||
}
|
||||
|
||||
|
@ -182,8 +177,8 @@ public class FileTest {
|
|||
// copy file
|
||||
@Test
|
||||
public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime());
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
|
@ -198,8 +193,8 @@ public class FileTest {
|
|||
|
||||
@Test(expected = FileAlreadyExistsException.class)
|
||||
public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime());
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
|
@ -215,8 +210,8 @@ public class FileTest {
|
|||
// moving files
|
||||
@Test
|
||||
public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime());
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
|
@ -232,8 +227,8 @@ public class FileTest {
|
|||
|
||||
@Test(expected = FileAlreadyExistsException.class)
|
||||
public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime());
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
|
@ -247,4 +242,5 @@ public class FileTest {
|
|||
assertTrue(Files.exists(file2));
|
||||
assertFalse(Files.exists(file1));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -13,7 +13,7 @@ import java.util.Date;
|
|||
|
||||
import org.junit.Test;
|
||||
|
||||
public class PathTest {
|
||||
public class PathManualTest {
|
||||
|
||||
private static final String HOME = System.getProperty("user.home");
|
||||
|
|
@ -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
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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,100 @@
|
|||
<?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>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
|
||||
<dependency>
|
||||
<groupId>org.apache.pdfbox</groupId>
|
||||
<artifactId>pdfbox</artifactId>
|
||||
<version>2.0.3</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox-tools -->
|
||||
<dependency>
|
||||
<groupId>org.apache.pdfbox</groupId>
|
||||
<artifactId>pdfbox-tools</artifactId>
|
||||
<version>2.0.3</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/net.sf.cssbox/pdf2dom -->
|
||||
<dependency>
|
||||
<groupId>net.sf.cssbox</groupId>
|
||||
<artifactId>pdf2dom</artifactId>
|
||||
<version>1.6</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
|
||||
<dependency>
|
||||
<groupId>com.itextpdf</groupId>
|
||||
<artifactId>itextpdf</artifactId>
|
||||
<version>5.5.10</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi</artifactId>
|
||||
<version>3.15</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-ooxml</artifactId>
|
||||
<version>3.15</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-scratchpad</artifactId>
|
||||
<version>3.15</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.xmlgraphics/batik-transcoder -->
|
||||
<dependency>
|
||||
<groupId>org.apache.xmlgraphics</groupId>
|
||||
<artifactId>batik-transcoder</artifactId>
|
||||
<version>1.8</version>
|
||||
</dependency>
|
||||
</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,39 @@
|
|||
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 {
|
||||
try {
|
||||
PDDocument pdf = PDDocument.load(new File(filename));
|
||||
PDFDomTree parser = new PDFDomTree();
|
||||
Writer output = new PrintWriter("src/output/pdf.html", "utf-8");
|
||||
parser.writeText(pdf, output);
|
||||
output.close();
|
||||
if (pdf != null) {
|
||||
pdf.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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,52 @@
|
|||
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 {
|
||||
try {
|
||||
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();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -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.
10
pom.xml
10
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>
|
||||
|
@ -95,6 +95,7 @@
|
|||
<module>spring-data-neo4j</module>
|
||||
<module>spring-data-redis</module>
|
||||
<module>spring-data-rest</module>
|
||||
<module>spring-dispatcher-servlet</module>
|
||||
<module>spring-exceptions</module>
|
||||
<module>spring-freemarker</module>
|
||||
<module>spring-hibernate3</module>
|
||||
|
@ -143,6 +144,7 @@
|
|||
<module>xml</module>
|
||||
<module>xmlunit2</module>
|
||||
<module>xstream</module>
|
||||
</modules>
|
||||
<module>pdf</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
</project>
|
|
@ -0,0 +1,82 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>spring-dispatcher-servlet</artifactId>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>..</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<version>4.3.3.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.thymeleaf</groupId>
|
||||
<artifactId>thymeleaf-spring4</artifactId>
|
||||
<version>3.0.2.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>1.7.21</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>2.7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-slf4j-impl</artifactId>
|
||||
<version>2.7</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>3.0.0</version>
|
||||
<configuration>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-maven-plugin</artifactId>
|
||||
<version>9.3.12.v20160915</version>
|
||||
<configuration>
|
||||
<webApp>
|
||||
<contextPath>/</contextPath>
|
||||
</webApp>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.spring.dispatcher.servlet;
|
||||
|
||||
import com.baeldung.spring.dispatcher.servlet.models.Task;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
@Configuration
|
||||
public class RootConfiguration {
|
||||
@Bean
|
||||
public Map<String, List<Task>> taskList() {
|
||||
Map<String, List<Task>> taskMap = new HashMap<>();
|
||||
List<Task> taskList = new ArrayList<>();
|
||||
taskList.add(new Task("Clean the dishes!", new Date()));
|
||||
taskMap.put("Cid", taskList);
|
||||
return taskMap;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.spring.dispatcher.servlet;
|
||||
|
||||
import org.springframework.web.context.ContextLoaderListener;
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
import org.springframework.web.servlet.DispatcherServlet;
|
||||
|
||||
import javax.servlet.MultipartConfigElement;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRegistration;
|
||||
|
||||
public class WebApplicationInitializer implements org.springframework.web.WebApplicationInitializer {
|
||||
@Override
|
||||
public void onStartup(ServletContext servletContext) throws ServletException {
|
||||
AnnotationConfigWebApplicationContext rootContext =
|
||||
new AnnotationConfigWebApplicationContext();
|
||||
rootContext.register(RootConfiguration.class);
|
||||
servletContext.addListener(new ContextLoaderListener(rootContext));
|
||||
AnnotationConfigWebApplicationContext webContext =
|
||||
new AnnotationConfigWebApplicationContext();
|
||||
webContext.register(WebConfiguration.class);
|
||||
DispatcherServlet dispatcherServlet = new DispatcherServlet(webContext);
|
||||
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher",
|
||||
dispatcherServlet);
|
||||
servlet.addMapping("/*");
|
||||
MultipartConfigElement multipartConfigElement =
|
||||
new MultipartConfigElement("/tmp");
|
||||
servlet.setMultipartConfig(multipartConfigElement);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,129 @@
|
|||
package com.baeldung.spring.dispatcher.servlet;
|
||||
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.support.ResourceBundleMessageSource;
|
||||
import org.springframework.ui.context.support.ResourceBundleThemeSource;
|
||||
import org.springframework.web.multipart.MultipartResolver;
|
||||
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
|
||||
import org.springframework.web.servlet.HandlerExceptionResolver;
|
||||
import org.springframework.web.servlet.LocaleResolver;
|
||||
import org.springframework.web.servlet.ThemeResolver;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
|
||||
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
|
||||
import org.springframework.web.servlet.theme.CookieThemeResolver;
|
||||
import org.springframework.web.servlet.theme.ThemeChangeInterceptor;
|
||||
import org.thymeleaf.spring4.SpringTemplateEngine;
|
||||
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
|
||||
import org.thymeleaf.templatemode.TemplateMode;
|
||||
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import java.util.Locale;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan("com.baeldung.spring.dispatcher.servlet.web")
|
||||
@EnableWebMvc
|
||||
public class WebConfiguration extends WebMvcConfigurerAdapter {
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry
|
||||
.addResourceHandler("/public/**")
|
||||
.addResourceLocations("/public/");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(localeChangeInterceptor());
|
||||
registry.addInterceptor(themeChangeInterceptor());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ServletContextTemplateResolver templateResolver(ServletContext servletContext) {
|
||||
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext);
|
||||
templateResolver.setPrefix("/WEB-INF/views/");
|
||||
templateResolver.setSuffix(".html");
|
||||
templateResolver.setTemplateMode(TemplateMode.HTML);
|
||||
return templateResolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SpringTemplateEngine templateEngine(ServletContextTemplateResolver templateResolver) {
|
||||
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
|
||||
templateEngine.setTemplateResolver(templateResolver);
|
||||
return templateEngine;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ThymeleafViewResolver viewResolver(SpringTemplateEngine templateEngine) {
|
||||
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
|
||||
viewResolver.setTemplateEngine(templateEngine);
|
||||
return viewResolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MessageSource messageSource() {
|
||||
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
|
||||
messageSource.setBasename("messages");
|
||||
messageSource.setFallbackToSystemLocale(false);
|
||||
return messageSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocaleResolver localeResolver() {
|
||||
CookieLocaleResolver localeResolver = new CookieLocaleResolver();
|
||||
localeResolver.setDefaultLocale(Locale.ENGLISH);
|
||||
localeResolver.setCookieName("locale");
|
||||
localeResolver.setCookieMaxAge(-1);
|
||||
return localeResolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocaleChangeInterceptor localeChangeInterceptor() {
|
||||
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
|
||||
localeChangeInterceptor.setParamName("lang");
|
||||
localeChangeInterceptor.setIgnoreInvalidLocale(true);
|
||||
return localeChangeInterceptor;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ResourceBundleThemeSource themeSource() {
|
||||
ResourceBundleThemeSource themeSource = new ResourceBundleThemeSource();
|
||||
themeSource.setBasenamePrefix("theme-");
|
||||
themeSource.setFallbackToSystemLocale(false);
|
||||
return themeSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ThemeResolver themeResolver() {
|
||||
CookieThemeResolver themeResolver = new CookieThemeResolver();
|
||||
themeResolver.setDefaultThemeName("robotask");
|
||||
themeResolver.setCookieName("theme");
|
||||
themeResolver.setCookieMaxAge(-1);
|
||||
return themeResolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ThemeChangeInterceptor themeChangeInterceptor() {
|
||||
ThemeChangeInterceptor themeChangeInterceptor = new ThemeChangeInterceptor();
|
||||
themeChangeInterceptor.setParamName("theme");
|
||||
return themeChangeInterceptor;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MultipartResolver multipartResolver() {
|
||||
return new StandardServletMultipartResolver();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public HandlerExceptionResolver handlerExceptionResolver() {
|
||||
return new ExceptionHandlerExceptionResolver();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
package com.baeldung.spring.dispatcher.servlet.models;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class Attachment {
|
||||
private String id;
|
||||
|
||||
private String name;
|
||||
|
||||
private String description;
|
||||
|
||||
public Attachment() {
|
||||
this.id = UUID.randomUUID().toString();
|
||||
}
|
||||
|
||||
public Attachment(String name, String description) {
|
||||
this();
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Attachment that = (Attachment) o;
|
||||
return id.equals(that.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return id.hashCode();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package com.baeldung.spring.dispatcher.servlet.models;
|
||||
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class Task {
|
||||
private String description;
|
||||
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd'T'hh:mm")
|
||||
private Date due;
|
||||
|
||||
private Set<Attachment> attachments = new HashSet<>();
|
||||
|
||||
public Task() {
|
||||
}
|
||||
|
||||
public Task(Date due) {
|
||||
this.due = due;
|
||||
}
|
||||
|
||||
public Task(String description, Date due) {
|
||||
this.description = description;
|
||||
this.due = due;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Date getDue() {
|
||||
return due;
|
||||
}
|
||||
|
||||
public void setDue(Date due) {
|
||||
this.due = due;
|
||||
}
|
||||
|
||||
public Set<Attachment> getAttachments() {
|
||||
return attachments;
|
||||
}
|
||||
|
||||
public void setAttachments(Set<Attachment> attachments) {
|
||||
this.attachments = attachments;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.spring.dispatcher.servlet.web;
|
||||
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
@RequestMapping("/attachments")
|
||||
public interface AttachmentController {
|
||||
@GetMapping("/{attachmentId}")
|
||||
ResponseEntity<FileSystemResource> getAttachment(
|
||||
@PathVariable("attachmentId") String attachmentId,
|
||||
@RequestParam(name = "download", required = false, defaultValue = "false") boolean forcedDownload
|
||||
);
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.spring.dispatcher.servlet.web;
|
||||
|
||||
import com.baeldung.spring.dispatcher.servlet.models.Task;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import java.net.URLConnection;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Controller
|
||||
public class AttachmentControllerImpl implements AttachmentController {
|
||||
@Autowired
|
||||
private Map<String, List<Task>> taskMap;
|
||||
|
||||
@Override
|
||||
public ResponseEntity<FileSystemResource> getAttachment(
|
||||
@PathVariable("attachmentId") String attachmentId,
|
||||
@RequestParam(name = "download", required = false, defaultValue = "false") boolean forcedDownload
|
||||
) {
|
||||
FileSystemResource resource = new FileSystemResource("/tmp/" + attachmentId);
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
taskMap.values().stream()
|
||||
.flatMap(Collection::stream)
|
||||
.flatMap(t -> t.getAttachments().stream())
|
||||
.filter(a -> a.getId().equals(attachmentId))
|
||||
.findFirst()
|
||||
.ifPresent(a -> {
|
||||
headers.add("Content-Disposition",
|
||||
"attachment; filename=" + a.getName());
|
||||
headers.add("Content-Type", forcedDownload ?
|
||||
MediaType.APPLICATION_OCTET_STREAM_VALUE :
|
||||
URLConnection.guessContentTypeFromName(a.getName()));
|
||||
});
|
||||
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.spring.dispatcher.servlet.web;
|
||||
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@ControllerAdvice
|
||||
public class GlobalDefaultExceptionHandler {
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception e) throws Exception {
|
||||
ModelAndView modelAndView = new ModelAndView();
|
||||
modelAndView.addObject("exception", e);
|
||||
modelAndView.addObject("url", request.getRequestURL());
|
||||
modelAndView.setViewName("error");
|
||||
return modelAndView;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.spring.dispatcher.servlet.web;
|
||||
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
@RequestMapping("/")
|
||||
public interface HomeController {
|
||||
@GetMapping("/*")
|
||||
String home(
|
||||
Model model
|
||||
);
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.spring.dispatcher.servlet.web;
|
||||
|
||||
import com.baeldung.spring.dispatcher.servlet.models.Task;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Controller
|
||||
public class HomeControllerImpl implements HomeController {
|
||||
@Autowired
|
||||
private Map<String, List<Task>> taskMap;
|
||||
|
||||
@Override
|
||||
public String home(Model model) {
|
||||
List<String> users = taskMap.keySet().stream()
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
model.addAttribute("users", users);
|
||||
return "home";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
package com.baeldung.spring.dispatcher.servlet.web;
|
||||
|
||||
import com.baeldung.spring.dispatcher.servlet.models.Task;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@RequestMapping("/tasks")
|
||||
public interface TaskController {
|
||||
@GetMapping("/{username}/list")
|
||||
String listTasks(
|
||||
@PathVariable("username") String username,
|
||||
Model model
|
||||
);
|
||||
|
||||
@GetMapping("/{username}/add")
|
||||
String addTask(
|
||||
@PathVariable("username") String username,
|
||||
Model model
|
||||
);
|
||||
|
||||
@PostMapping("/{username}/add")
|
||||
String addTask(
|
||||
@PathVariable("username") String username,
|
||||
@ModelAttribute Task task
|
||||
);
|
||||
|
||||
@GetMapping("/{username}/get/{id}")
|
||||
String getTask(
|
||||
@PathVariable("username") String username,
|
||||
@PathVariable("id") int id,
|
||||
Model model
|
||||
);
|
||||
|
||||
@GetMapping("/{username}/get/{id}/attach")
|
||||
String attachToTask(
|
||||
@PathVariable("username") String username,
|
||||
@PathVariable("id") int id,
|
||||
Model model
|
||||
);
|
||||
|
||||
@PostMapping("/{username}/get/{id}/attach")
|
||||
String attachToTask(
|
||||
@PathVariable("username") String username,
|
||||
@PathVariable("id") int id,
|
||||
@RequestParam("attachment") MultipartFile attachment,
|
||||
@RequestParam("description") String description
|
||||
);
|
||||
}
|
|
@ -0,0 +1,111 @@
|
|||
package com.baeldung.spring.dispatcher.servlet.web;
|
||||
|
||||
import com.baeldung.spring.dispatcher.servlet.models.Attachment;
|
||||
import com.baeldung.spring.dispatcher.servlet.models.Task;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Controller
|
||||
public class TaskControllerImpl implements TaskController {
|
||||
@Autowired
|
||||
private Map<String, List<Task>> taskMap;
|
||||
|
||||
@Override
|
||||
public String listTasks(
|
||||
@PathVariable("username") String username,
|
||||
Model model
|
||||
) {
|
||||
List<Task> tasks = taskMap.get(username).stream()
|
||||
.sorted(Comparator.comparing(Task::getDue))
|
||||
.collect(Collectors.toList());
|
||||
model.addAttribute("username", username);
|
||||
model.addAttribute("tasks", tasks);
|
||||
return "task-list";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String addTask(
|
||||
@PathVariable("username") String username,
|
||||
Model model
|
||||
) {
|
||||
model.addAttribute("username", username);
|
||||
model.addAttribute("task", new Task(new Date()));
|
||||
return "task-add";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String addTask(
|
||||
@PathVariable("username") String username,
|
||||
@ModelAttribute Task task
|
||||
) {
|
||||
List<Task> taskList = taskMap.get(username);
|
||||
if (taskList == null) {
|
||||
taskList = new ArrayList<>();
|
||||
}
|
||||
taskList.add(task);
|
||||
taskMap.put(username, taskList);
|
||||
return "redirect:list";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTask(
|
||||
@PathVariable("username") String username,
|
||||
@PathVariable("id") int id,
|
||||
Model model
|
||||
) {
|
||||
Task task = taskMap.get(username).get(id);
|
||||
model.addAttribute("username", username);
|
||||
model.addAttribute("id", id);
|
||||
model.addAttribute("task", task);
|
||||
return "task-get";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String attachToTask(
|
||||
@PathVariable("username") String username,
|
||||
@PathVariable("id") int id,
|
||||
Model model
|
||||
) {
|
||||
model.addAttribute("username", username);
|
||||
model.addAttribute("id", id);
|
||||
return "task-attach";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String attachToTask(
|
||||
@PathVariable("username") String username,
|
||||
@PathVariable("id") int id,
|
||||
@RequestParam("attachment") MultipartFile multipartFile,
|
||||
@RequestParam("description") String description
|
||||
) {
|
||||
Task task = taskMap.get(username).get(id);
|
||||
Attachment attachment = new Attachment(multipartFile.getOriginalFilename(),
|
||||
description);
|
||||
task.getAttachments().add(attachment);
|
||||
try (InputStream inputStream =
|
||||
new BufferedInputStream(multipartFile.getInputStream());
|
||||
OutputStream outputStream =
|
||||
new BufferedOutputStream(Files.newOutputStream(
|
||||
Paths.get("/tmp", attachment.getId())))) {
|
||||
byte[] buf = new byte[1024 * 16];
|
||||
int len;
|
||||
while ((len = inputStream.read(buf)) != -1) {
|
||||
outputStream.write(buf, 0, len);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to upload file!", e);
|
||||
}
|
||||
return "redirect:./";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="WARN">
|
||||
<Appenders>
|
||||
<Console name="Console" target="SYSTEM_OUT">
|
||||
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36}:%n[+] %msg%n"/>
|
||||
</Console>
|
||||
</Appenders>
|
||||
|
||||
<Loggers>
|
||||
<Root level="info">
|
||||
<AppenderRef ref="Console"/>
|
||||
</Root>
|
||||
</Loggers>
|
||||
</Configuration>
|
|
@ -0,0 +1,22 @@
|
|||
home.title=Welcome to TaskTools!
|
||||
task.add.description=description
|
||||
task.add.due=due
|
||||
task.add.header=Adding a task to {0}''s list:
|
||||
task.add.submit=Submit
|
||||
task.add.title={0}: task add
|
||||
task.attach.attachment=attached file
|
||||
task.attach.description=description
|
||||
task.attach.header=task #{0}: attach file
|
||||
task.attach.submit=Submit
|
||||
task.attach.title=#{0}: Attach file
|
||||
task.get.attach=Attach file
|
||||
task.get.attachments=attachments:
|
||||
task.get.download=Download
|
||||
task.get.header=task #{0}:
|
||||
task.get.list=Back
|
||||
task.get.title={0}: task details
|
||||
task.list.add-new=Add new
|
||||
task.list.details=Details
|
||||
task.list.header={0}''s tasks:
|
||||
task.list.home=Home
|
||||
task.list.title={0}: task list
|
|
@ -0,0 +1,22 @@
|
|||
home.title=Willkommen bei TaskTools!
|
||||
task.add.description=Beschreibung
|
||||
task.add.due=f\u00e4llig
|
||||
task.add.header=F\u00fcge eine Aufgabe zu {0}''s Liste hinzu:
|
||||
task.add.submit=Senden
|
||||
task.add.title={0}: Task hinzuf\u00fcgen
|
||||
task.attach.attachment=Angeh\u00e4ngte Datei
|
||||
task.attach.description=Beschreibung
|
||||
task.attach.header=Task #{0}: Datei anh\u00e4ngen
|
||||
task.attach.submit=Senden
|
||||
task.attach.title=#{0}: Datei anh\u00e4ngen
|
||||
task.get.attach=Datei anh\u00e4ngen
|
||||
task.get.attachments=Anh\u00e4nge:
|
||||
task.get.download=Download
|
||||
task.get.header=Task #{0}:
|
||||
task.get.list=Zur\u00fcck
|
||||
task.get.title={0}: Task Details
|
||||
task.list.add-new=Neuer Task
|
||||
task.list.details=Details
|
||||
task.list.header={0}''s Tasks:
|
||||
task.list.home=Startseite
|
||||
task.list.title={0}: Task Liste
|
|
@ -0,0 +1 @@
|
|||
stylesheet=/public/css/themes/post_it.css
|
|
@ -0,0 +1 @@
|
|||
stylesheet=/public/css/themes/robotask.css
|
|
@ -0,0 +1,13 @@
|
|||
<!DOCTYPE html>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title>Error</title>
|
||||
<link rel="stylesheet" type="text/css" href="/public/css/base.css">
|
||||
<link rel="stylesheet" type="text/css" th:href="${#themes.code('stylesheet')}">
|
||||
</head>
|
||||
<body>
|
||||
<h2>Error:</h2>
|
||||
<p th:text="|URL: ${url}|"></p>
|
||||
<p th:text="${exception}"></p>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,16 @@
|
|||
<!DOCTYPE html>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title th:text="#{home.title}"></title>
|
||||
<link rel="stylesheet" type="text/css" href="/public/css/base.css">
|
||||
<link rel="stylesheet" type="text/css" th:href="${#themes.code('stylesheet')}">
|
||||
</head>
|
||||
<body>
|
||||
<h2>TaskTools</h2>
|
||||
<ul>
|
||||
<li th:each="username : ${users}">
|
||||
<a th:href="@{/tasks/{username}/list(username=${username})}" th:text="${username}"></a>
|
||||
</li>
|
||||
</ul>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,16 @@
|
|||
<!DOCTYPE html>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title th:text="#{task.add.title(${username})}"></title>
|
||||
<link rel="stylesheet" type="text/css" href="/public/css/base.css">
|
||||
<link rel="stylesheet" type="text/css" th:href="${#themes.code('stylesheet')}">
|
||||
</head>
|
||||
<body>
|
||||
<h2 th:text="#{task.add.header(${username})}"></h2>
|
||||
<form method="post" action="#" th:action="@{/tasks/{username}/add(username=${username})}" th:object="${task}">
|
||||
<input type="text" th:field="*{description}" th:placeholder="#{task.add.description}"/>
|
||||
<input type="datetime-local" th:field="*{due}" th:placeholder="#{task.add.due}"/>
|
||||
<input type="submit" th:value="#{task.add.submit}"/>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,17 @@
|
|||
<!DOCTYPE html>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title th:text="#{task.attach.title(${id})}"></title>
|
||||
<link rel="stylesheet" type="text/css" href="/public/css/base.css">
|
||||
<link rel="stylesheet" type="text/css" th:href="${#themes.code('stylesheet')}">
|
||||
</head>
|
||||
<body>
|
||||
<h2 th:text="#{task.attach.header(${id})}"></h2>
|
||||
<form method="post" action="#" enctype="multipart/form-data"
|
||||
th:action="@{/tasks/{username}/get/{id}/attach(username=${username},id=${id})}">
|
||||
<input type="file" name="attachment" th:placeholder="#{task.attach.attachment}"/>
|
||||
<input type="text" name="description" th:placeholder="#{task.attach.description}"/>
|
||||
<input type="submit" th:value="#{task.attach.submit}"/>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,28 @@
|
|||
<!DOCTYPE html>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title th:text="#{task.get.title(${task.description})}"></title>
|
||||
<link rel="stylesheet" type="text/css" href="/public/css/base.css">
|
||||
<link rel="stylesheet" type="text/css" th:href="${#themes.code('stylesheet')}">
|
||||
</head>
|
||||
<body>
|
||||
<h2 th:text="#{task.get.header(${id})}"></h2>
|
||||
<p th:text="${task.due}"></p>
|
||||
<p th:text="${task.description}"></p>
|
||||
<hr/>
|
||||
<p th:text="#{task.get.attachments}"></p>
|
||||
<dl th:each="attachment : ${task.attachments}">
|
||||
<dt><img src="#" th:src="@{/attachments/{id}(id=${attachment.id})}"></dt>
|
||||
<dt>
|
||||
<span th:text="${attachment.name}"></span>
|
||||
<a class="button" th:href="@{/attachments/{id}(id=${attachment.id},download=true)}"
|
||||
th:text="#{task.get.download}"></a>
|
||||
</dt>
|
||||
<dd th:text="${attachment.description}"></dd>
|
||||
</dl>
|
||||
<p>
|
||||
<a th:href="@{/tasks/{username}/list(username=${username})}" th:text="#{task.get.list}"></a>
|
||||
<a th:href="@{/tasks/{username}/get/{id}/attach(username=${username},id=${id})}" th:text="#{task.get.attach}"></a>
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,22 @@
|
|||
<!DOCTYPE html>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title th:text="#{task.list.title(${username})}"></title>
|
||||
<link rel="stylesheet" type="text/css" href="/public/css/base.css">
|
||||
<link rel="stylesheet" type="text/css" th:href="${#themes.code('stylesheet')}">
|
||||
</head>
|
||||
<body>
|
||||
<h2 th:text="#{task.list.header(${username})}"></h2>
|
||||
<ul>
|
||||
<li th:each="task : ${tasks}">
|
||||
<p th:text="*{task.due}"></p>
|
||||
<p th:text="*{task.description}"></p>
|
||||
<a th:href="@{/tasks/{username}/get/{id}(username=${username},id=${taskStat.index})}" th:text="#{task.list.details}"></a>
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
<a th:href="@{/}" th:text="#{task.list.home}"></a>
|
||||
<a th:href="@{/tasks/{username}/add(username=${username})}" th:text="#{task.list.add-new}"></a>
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,8 @@
|
|||
a.button {
|
||||
-webkit-appearance: button;
|
||||
-moz-appearance: button;
|
||||
appearance: button;
|
||||
text-decoration: none;
|
||||
color: #2196f3;
|
||||
background-color: #e0e0e0;
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
@import url('https://fonts.googleapis.com/css?family=Indie+Flower');
|
||||
|
||||
* {
|
||||
font-family: 'Indie Flower', sans-serif;
|
||||
font-size: 18px;
|
||||
color: #ffeb3b;
|
||||
background-color: #212121;
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
@import url('https://fonts.googleapis.com/css?family=Roboto');
|
||||
|
||||
* {
|
||||
font-family: Roboto, sans-serif;
|
||||
font-size: 1em;
|
||||
color: #212121;
|
||||
background-color: #fafafa;
|
||||
}
|
|
@ -3,11 +3,11 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung.samples.spring.integration</groupId>
|
||||
<artifactId>baeldungSIsample</artifactId>
|
||||
<artifactId>spring-integration</artifactId>
|
||||
<version>1.0.0.BUILD-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>Baeldung Spring Intro</name>
|
||||
<name>spring-integration</name>
|
||||
<url>http://www.springsource.org/spring-integration</url>
|
||||
|
||||
<prerequisites>
|
||||
|
|
|
@ -13,5 +13,12 @@
|
|||
- [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache)
|
||||
- [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource)
|
||||
|
||||
To ignore "No persistence xml file found in project", you do:
|
||||
Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project"
|
||||
### Eclipse Config
|
||||
After importing the project into Eclipse, you may see the following error:
|
||||
"No persistence xml file found in project"
|
||||
|
||||
This can be ignored:
|
||||
- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project"
|
||||
Or:
|
||||
- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator
|
||||
|
||||
|
|
|
@ -0,0 +1,51 @@
|
|||
package com.baeldung.web.controller;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
|
||||
import com.baeldung.model.Employee;
|
||||
import com.baeldung.spring.web.config.WebConfig;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = WebConfig.class)
|
||||
public class EmployeeTestWithoutMockMvc {
|
||||
|
||||
@Autowired
|
||||
private EmployeeController employeeController;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
employeeController.initEmployees();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInitEmployees_thenVerifyValuesInitiation() {
|
||||
|
||||
Employee employee1 = employeeController.employeeMap.get(1L);
|
||||
Employee employee2 = employeeController.employeeMap.get(2L);
|
||||
Employee employee3 = employeeController.employeeMap.get(3L);
|
||||
|
||||
Assert.assertTrue(employee1.getId() == 1L);
|
||||
Assert.assertTrue(employee1.getName().equals("John"));
|
||||
Assert.assertTrue(employee1.getContactNumber().equals("223334411"));
|
||||
Assert.assertTrue(employee1.getWorkingArea().equals("rh"));
|
||||
|
||||
Assert.assertTrue(employee2.getId() == 2L);
|
||||
Assert.assertTrue(employee2.getName().equals("Peter"));
|
||||
Assert.assertTrue(employee2.getContactNumber().equals("22001543"));
|
||||
Assert.assertTrue(employee2.getWorkingArea().equals("informatics"));
|
||||
|
||||
Assert.assertTrue(employee3.getId() == 3L);
|
||||
Assert.assertTrue(employee3.getName().equals("Mike"));
|
||||
Assert.assertTrue(employee3.getContactNumber().equals("223334411"));
|
||||
Assert.assertTrue(employee3.getWorkingArea().equals("admin"));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package com.baeldung.spring.controller;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
@Controller
|
||||
public class ErrorController {
|
||||
|
||||
@RequestMapping(value = "500Error", method = RequestMethod.GET)
|
||||
public void throwRuntimeException() {
|
||||
throw new NullPointerException("Throwing a null pointer exception");
|
||||
}
|
||||
|
||||
@RequestMapping(value = "errors", method = RequestMethod.GET)
|
||||
public ModelAndView renderErrorPage(HttpServletRequest httpRequest) {
|
||||
ModelAndView errorPage = new ModelAndView("errorPage");
|
||||
String errorMsg = "";
|
||||
int httpErrorCode = getErrorCode(httpRequest);
|
||||
|
||||
switch (httpErrorCode) {
|
||||
case 400: {
|
||||
errorMsg = "Http Error Code : 400 . Bad Request";
|
||||
break;
|
||||
}
|
||||
case 401: {
|
||||
errorMsg = "Http Error Code : 401. Unauthorized";
|
||||
break;
|
||||
}
|
||||
case 404: {
|
||||
errorMsg = "Http Error Code : 404. Resource not found";
|
||||
break;
|
||||
}
|
||||
// Handle other 4xx error codes.
|
||||
case 500: {
|
||||
errorMsg = "Http Error Code : 500. Internal Server Error";
|
||||
break;
|
||||
}
|
||||
// Handle other 5xx error codes.
|
||||
}
|
||||
errorPage.addObject("errorMsg", errorMsg);
|
||||
return errorPage;
|
||||
}
|
||||
|
||||
private int getErrorCode(HttpServletRequest httpRequest) {
|
||||
return (Integer) httpRequest
|
||||
.getAttribute("javax.servlet.error.status_code");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
|
||||
<%@ page session="false"%>
|
||||
<html>
|
||||
<head>
|
||||
<title>Home</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>${errorMsg}</h1>
|
||||
</body>
|
||||
</html>
|
|
@ -43,4 +43,7 @@
|
|||
<welcome-file>index.jsp</welcome-file>
|
||||
</welcome-file-list>
|
||||
|
||||
<error-page>
|
||||
<location>/errors</location>
|
||||
</error-page>
|
||||
</web-app>
|
|
@ -332,5 +332,17 @@
|
|||
<com.squareup.okhttp3.version>3.4.1</com.squareup.okhttp3.version>
|
||||
|
||||
</properties>
|
||||
|
||||
<reporting>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>findbugs-maven-plugin</artifactId>
|
||||
<version>3.0.4</version>
|
||||
<configuration>
|
||||
<effort>Max</effort>
|
||||
<omitVisitors>FindDeadLocalStores,FindNullDeref</omitVisitors>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</reporting>
|
||||
</project>
|
||||
|
|
|
@ -2,15 +2,16 @@
|
|||
|
||||
## Spring Thymeleaf Example Project
|
||||
|
||||
|
||||
### Relevant Articles:
|
||||
- [Introduction to Using Thymeleaf in Spring](http://www.baeldung.com/thymeleaf-in-spring-mvc)
|
||||
- [CSRF Protection with Spring MVC and Thymeleaf](http://www.baeldung.com/csrf-thymeleaf-with-spring-security)
|
||||
|
||||
|
||||
### Build the Project
|
||||
|
||||
mvn clean install
|
||||
|
||||
|
||||
### Run the Project
|
||||
mvn cargo:run
|
||||
- **note**: starts on port '8082'
|
||||
|
|
|
@ -5,4 +5,4 @@
|
|||
### Relevant Articles:
|
||||
- [Introduction to Mutation Testing Using the PITest Library](http://www.baeldung.com/java-mutation-testing-with-pitest)
|
||||
- [Intro to JaCoCo](http://www.baeldung.com/jacoco)
|
||||
- [Mutation Testing with PITest](http://www.baeldung.com/java-mutation-testing-with-pitest)
|
||||
|
||||
|
|
Loading…
Reference in New Issue