diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java similarity index 98% rename from apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java rename to apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java index 9dd63cf3ac..a2fd6be435 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java @@ -9,7 +9,7 @@ import java.util.Map; @Path("baeldung") @Produces("text/xml") -public class Baeldung { +public class CourseRepository { private Map courses = new HashMap<>(); { @@ -69,4 +69,4 @@ public class Baeldung { } return null; } -} \ No newline at end of file +} diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java index bb35bab3f8..d3ed2eb70e 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java @@ -7,8 +7,8 @@ import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider; public class RestfulServer { public static void main(String args[]) throws Exception { JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean(); - factoryBean.setResourceClasses(Baeldung.class); - factoryBean.setResourceProvider(new SingletonResourceProvider(new Baeldung())); + factoryBean.setResourceClasses(CourseRepository.class); + factoryBean.setResourceProvider(new SingletonResourceProvider(new CourseRepository())); factoryBean.setAddress("http://localhost:8080/"); Server server = factoryBean.create(); @@ -18,4 +18,4 @@ public class RestfulServer { server.destroy(); System.exit(0); } -} \ No newline at end of file +} diff --git a/core-java/pom.xml b/core-java/pom.xml index 75608b59ba..b39e356977 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -162,6 +162,8 @@ **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java diff --git a/core-java/src/main/java/com/baeldung/datetime/UseDuration.java b/core-java/src/main/java/com/baeldung/datetime/UseDuration.java index 125b6fbe38..31b45aab84 100644 --- a/core-java/src/main/java/com/baeldung/datetime/UseDuration.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseDuration.java @@ -5,12 +5,12 @@ import java.time.LocalTime; import java.time.Period; public class UseDuration { - - public LocalTime modifyDates(LocalTime localTime,Duration duration){ + + public LocalTime modifyDates(LocalTime localTime, Duration duration) { return localTime.plus(duration); } - - public Duration getDifferenceBetweenDates(LocalTime localTime1,LocalTime localTime2){ + + public Duration getDifferenceBetweenDates(LocalTime localTime1, LocalTime localTime2) { return Duration.between(localTime1, localTime2); } } diff --git a/core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java b/core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java index 47b1b3f67d..82f5745b3c 100644 --- a/core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java @@ -7,39 +7,39 @@ import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalAdjusters; public class UseLocalDate { - - public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth){ + + public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) { return LocalDate.of(year, month, dayOfMonth); } - - public LocalDate getLocalDateUsingParseMethod(String representation){ + + public LocalDate getLocalDateUsingParseMethod(String representation) { return LocalDate.parse(representation); } - - public LocalDate getLocalDateFromClock(){ + + public LocalDate getLocalDateFromClock() { LocalDate localDate = LocalDate.now(); return localDate; } - - public LocalDate getNextDay(LocalDate localDate){ + + public LocalDate getNextDay(LocalDate localDate) { return localDate.plusDays(1); } - - public LocalDate getPreviousDay(LocalDate localDate){ + + public LocalDate getPreviousDay(LocalDate localDate) { return localDate.minus(1, ChronoUnit.DAYS); } - - public DayOfWeek getDayOfWeek(LocalDate localDate){ + + public DayOfWeek getDayOfWeek(LocalDate localDate) { DayOfWeek day = localDate.getDayOfWeek(); return day; } - - public LocalDate getFirstDayOfMonth(){ + + public LocalDate getFirstDayOfMonth() { LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()); return firstDayOfMonth; } - - public LocalDateTime getStartOfDay(LocalDate localDate){ + + public LocalDateTime getStartOfDay(LocalDate localDate) { LocalDateTime startofDay = localDate.atStartOfDay(); return startofDay; } diff --git a/core-java/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/core-java/src/main/java/com/baeldung/datetime/UseLocalDateTime.java index 7aa1eaa276..7f39ac2f91 100644 --- a/core-java/src/main/java/com/baeldung/datetime/UseLocalDateTime.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseLocalDateTime.java @@ -3,8 +3,8 @@ package com.baeldung.datetime; import java.time.LocalDateTime; public class UseLocalDateTime { - - public LocalDateTime getLocalDateTimeUsingParseMethod(String representation){ + + public LocalDateTime getLocalDateTimeUsingParseMethod(String representation) { return LocalDateTime.parse(representation); } diff --git a/core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java b/core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java index e13fd10d6f..9bd8f9706c 100644 --- a/core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java @@ -4,32 +4,32 @@ import java.time.LocalTime; import java.time.temporal.ChronoUnit; public class UseLocalTime { - - public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds){ + + public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) { LocalTime localTime = LocalTime.of(hour, min, seconds); return localTime; } - - public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation){ + + public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) { LocalTime localTime = LocalTime.parse(timeRepresentation); return localTime; } - - public LocalTime getLocalTimeFromClock(){ + + public LocalTime getLocalTimeFromClock() { LocalTime localTime = LocalTime.now(); return localTime; } - - public LocalTime addAnHour(LocalTime localTime){ - LocalTime newTime = localTime.plus(1,ChronoUnit.HOURS); + + public LocalTime addAnHour(LocalTime localTime) { + LocalTime newTime = localTime.plus(1, ChronoUnit.HOURS); return newTime; } - - public int getHourFromLocalTime(LocalTime localTime){ + + public int getHourFromLocalTime(LocalTime localTime) { return localTime.getHour(); } - - public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute){ + + public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) { return localTime.withMinute(minute); } } diff --git a/core-java/src/main/java/com/baeldung/datetime/UsePeriod.java b/core-java/src/main/java/com/baeldung/datetime/UsePeriod.java index 326cfad650..5a42ef83b4 100644 --- a/core-java/src/main/java/com/baeldung/datetime/UsePeriod.java +++ b/core-java/src/main/java/com/baeldung/datetime/UsePeriod.java @@ -4,12 +4,12 @@ import java.time.LocalDate; import java.time.Period; public class UsePeriod { - - public LocalDate modifyDates(LocalDate localDate,Period period){ + + public LocalDate modifyDates(LocalDate localDate, Period period) { return localDate.plus(period); } - - public Period getDifferenceBetweenDates(LocalDate localDate1,LocalDate localDate2){ + + public Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) { return Period.between(localDate1, localDate2); } } diff --git a/core-java/src/main/java/com/baeldung/datetime/UseToInstant.java b/core-java/src/main/java/com/baeldung/datetime/UseToInstant.java index 1ddb096cf6..94154ce5c0 100644 --- a/core-java/src/main/java/com/baeldung/datetime/UseToInstant.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseToInstant.java @@ -6,13 +6,13 @@ import java.util.Calendar; import java.util.Date; public class UseToInstant { - - public LocalDateTime convertDateToLocalDate(Date date){ + + public LocalDateTime convertDateToLocalDate(Date date) { LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); return localDateTime; } - - public LocalDateTime convertDateToLocalDate(Calendar calendar){ + + public LocalDateTime convertDateToLocalDate(Calendar calendar) { LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault()); return localDateTime; } diff --git a/core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java b/core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java index 0369de9835..2d1b17484b 100644 --- a/core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java @@ -5,8 +5,8 @@ import java.time.ZoneId; import java.time.ZonedDateTime; public class UseZonedDateTime { - - public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime,ZoneId zoneId){ + + public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) { ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId); return zonedDateTime; } diff --git a/core-java/src/main/java/com/baeldung/enums/Pizza.java b/core-java/src/main/java/com/baeldung/enums/Pizza.java index 5bc2d9a9eb..bad134bf00 100644 --- a/core-java/src/main/java/com/baeldung/enums/Pizza.java +++ b/core-java/src/main/java/com/baeldung/enums/Pizza.java @@ -7,8 +7,7 @@ import java.util.stream.Collectors; public class Pizza { - private static EnumSet deliveredPizzaStatuses = - EnumSet.of(PizzaStatusEnum.DELIVERED); + private static EnumSet deliveredPizzaStatuses = EnumSet.of(PizzaStatusEnum.DELIVERED); private PizzaStatusEnum status; @@ -76,9 +75,7 @@ public class Pizza { } public static EnumMap> groupPizzaByStatus(List pzList) { - return pzList.stream().collect( - Collectors.groupingBy(Pizza::getStatus, - () -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList())); + return pzList.stream().collect(Collectors.groupingBy(Pizza::getStatus, () -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList())); } public void deliver() { diff --git a/core-java/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java b/core-java/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java index 5ccff5e959..a276b3c000 100644 --- a/core-java/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java +++ b/core-java/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java @@ -1,6 +1,5 @@ package com.baeldung.enums; - public enum PizzaDeliverySystemConfiguration { INSTANCE; diff --git a/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java index f1ab2d8d09..ae79787570 100644 --- a/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java +++ b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java @@ -30,8 +30,7 @@ public class CustomRecursiveAction extends RecursiveAction { private Collection createSubtasks() { - List subtasks = - new ArrayList<>(); + List subtasks = new ArrayList<>(); String partOne = workLoad.substring(0, workLoad.length() / 2); String partTwo = workLoad.substring(workLoad.length() / 2, workLoad.length()); diff --git a/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java index 5d4d97b805..af9805c33f 100644 --- a/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java +++ b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java @@ -1,6 +1,5 @@ package com.baeldung.forkjoin; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -23,10 +22,7 @@ public class CustomRecursiveTask extends RecursiveTask { if (arr.length > THRESHOLD) { - return ForkJoinTask.invokeAll(createSubtasks()) - .stream() - .mapToInt(ForkJoinTask::join) - .sum(); + return ForkJoinTask.invokeAll(createSubtasks()).stream().mapToInt(ForkJoinTask::join).sum(); } else { return processing(arr); @@ -35,17 +31,12 @@ public class CustomRecursiveTask extends RecursiveTask { private Collection createSubtasks() { List dividedTasks = new ArrayList<>(); - dividedTasks.add(new CustomRecursiveTask( - Arrays.copyOfRange(arr, 0, arr.length / 2))); - dividedTasks.add(new CustomRecursiveTask( - Arrays.copyOfRange(arr, arr.length / 2, arr.length))); + dividedTasks.add(new CustomRecursiveTask(Arrays.copyOfRange(arr, 0, arr.length / 2))); + dividedTasks.add(new CustomRecursiveTask(Arrays.copyOfRange(arr, arr.length / 2, arr.length))); return dividedTasks; } private Integer processing(int[] arr) { - return Arrays.stream(arr) - .filter(a -> a > 10 && a < 27) - .map(a -> a * 10) - .sum(); + return Arrays.stream(arr).filter(a -> a > 10 && a < 27).map(a -> a * 10).sum(); } } diff --git a/core-java/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java b/core-java/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java index 521616600f..fd24a6fc66 100644 --- a/core-java/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java +++ b/core-java/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java @@ -1,6 +1,5 @@ package com.baeldung.forkjoin.util; - import java.util.concurrent.ForkJoinPool; public class PoolUtil { diff --git a/core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java b/core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java new file mode 100644 index 0000000000..0d66406ac2 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java @@ -0,0 +1,56 @@ +package com.baeldung.java.networking.cookies; + +import java.net.*; +import java.util.List; + +public class PersistentCookieStore implements CookieStore, Runnable { + CookieStore store; + + public PersistentCookieStore() { + store = new CookieManager().getCookieStore(); + // deserialize cookies into store + Runtime.getRuntime().addShutdownHook(new Thread(this)); + } + + @Override + public void run() { + // serialize cookies to persistent storage + } + + @Override + public void add(URI uri, HttpCookie cookie) { + store.add(uri, cookie); + + } + + @Override + public List get(URI uri) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getCookies() { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getURIs() { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean remove(URI uri, HttpCookie cookie) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean removeAll() { + // TODO Auto-generated method stub + return false; + } + +} diff --git a/core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java b/core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java new file mode 100644 index 0000000000..6d6371bfe0 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java @@ -0,0 +1,26 @@ +package com.baeldung.java.networking.cookies; + +import java.net.*; + +public class ProxyAcceptCookiePolicy implements CookiePolicy { + String acceptedProxy; + + public ProxyAcceptCookiePolicy(String acceptedProxy) { + this.acceptedProxy = acceptedProxy; + } + + public boolean shouldAccept(URI uri, HttpCookie cookie) { + String host; + try { + host = InetAddress.getByName(uri.getHost()).getCanonicalHostName(); + } catch (UnknownHostException e) { + host = uri.getHost(); + } + + if (!HttpCookie.domainMatches(acceptedProxy, host)) { + return false; + } + + return CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(uri, cookie); + } +} diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java new file mode 100644 index 0000000000..1fb9af3a9d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java @@ -0,0 +1,42 @@ +package com.baeldung.java.networking.udp; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; + +public class EchoClient { + private DatagramSocket socket; + private InetAddress address; + + private byte[] buf; + + public EchoClient() { + try { + socket = new DatagramSocket(); + address = InetAddress.getByName("localhost"); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public String sendEcho(String msg) { + DatagramPacket packet = null; + try { + buf=msg.getBytes(); + packet = new DatagramPacket(buf, buf.length, address, 4445); + socket.send(packet); + packet = new DatagramPacket(buf, buf.length); + socket.receive(packet); + } catch (IOException e) { + e.printStackTrace(); + } + String received = new String(packet.getData(), 0, packet.getLength()); + return received; + } + + public void close() { + socket.close(); + } +} diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java new file mode 100644 index 0000000000..900d330786 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java @@ -0,0 +1,42 @@ +package com.baeldung.java.networking.udp; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; + +public class EchoServer extends Thread { + + protected DatagramSocket socket = null; + protected boolean running; + protected byte[] buf = new byte[256]; + + public EchoServer() throws IOException { + socket = new DatagramSocket(4445); + } + + public void run() { + running = true; + + while (running) { + try { + + DatagramPacket packet = new DatagramPacket(buf, buf.length); + socket.receive(packet); + InetAddress address = packet.getAddress(); + int port = packet.getPort(); + packet = new DatagramPacket(buf, buf.length, address, port); + String received = new String(packet.getData(), 0, packet.getLength()); + if (received.equals("end")) { + running = false; + continue; + } + socket.send(packet); + } catch (IOException e) { + e.printStackTrace(); + running = false; + } + } + socket.close(); + } +} diff --git a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java index 285d4e51fc..1d4e01bbc3 100644 --- a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java +++ b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java @@ -1,21 +1,21 @@ 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.util.Iterator; +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; public class EchoServer { public static void main(String[] args) - throws IOException { + throws IOException { Selector selector = Selector.open(); ServerSocketChannel serverSocket = ServerSocketChannel.open(); serverSocket.bind(new InetSocketAddress("localhost", 5454)); @@ -49,6 +49,7 @@ 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"; @@ -59,4 +60,4 @@ public class EchoServer { return builder.start(); } -} \ No newline at end of file +} diff --git a/core-java/src/main/java/com/baeldung/java_8_features/Vehicle.java b/core-java/src/main/java/com/baeldung/java_8_features/Vehicle.java index 011173bcaf..045fc90590 100644 --- a/core-java/src/main/java/com/baeldung/java_8_features/Vehicle.java +++ b/core-java/src/main/java/com/baeldung/java_8_features/Vehicle.java @@ -9,7 +9,7 @@ public interface Vehicle { } default long[] startPosition() { - return new long[]{23, 15}; + return new long[] { 23, 15 }; } default String getOverview() { diff --git a/core-java/src/main/java/com/baeldung/java_8_features/VehicleImpl.java b/core-java/src/main/java/com/baeldung/java_8_features/VehicleImpl.java index 83e55f5f4d..64bec0246d 100644 --- a/core-java/src/main/java/com/baeldung/java_8_features/VehicleImpl.java +++ b/core-java/src/main/java/com/baeldung/java_8_features/VehicleImpl.java @@ -1,9 +1,9 @@ package com.baeldung.java_8_features; -public class VehicleImpl implements Vehicle { +public class VehicleImpl implements Vehicle { @Override public void moveTo(long altitude, long longitude) { - //do nothing + // do nothing } } diff --git a/core-java/src/main/java/com/baeldung/socket/EchoClient.java b/core-java/src/main/java/com/baeldung/socket/EchoClient.java index 1ddf752a03..570bd60b2d 100644 --- a/core-java/src/main/java/com/baeldung/socket/EchoClient.java +++ b/core-java/src/main/java/com/baeldung/socket/EchoClient.java @@ -4,39 +4,38 @@ import java.io.*; import java.net.*; public class EchoClient { - private Socket clientSocket; - private PrintWriter out; - private BufferedReader in; + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; - public void startConnection(String ip, int port) { - try { - clientSocket = new Socket(ip, port); - out = new PrintWriter(clientSocket.getOutputStream(), true); - in = new BufferedReader(new InputStreamReader( - clientSocket.getInputStream())); - } catch (IOException e) { - System.out.print(e); - } + public void startConnection(String ip, int port) { + try { + clientSocket = new Socket(ip, port); + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + } catch (IOException e) { + System.out.print(e); + } - } + } - public String sendMessage(String msg) { - try { - out.println(msg); - return in.readLine(); - } catch (Exception e) { - return null; - } - } + public String sendMessage(String msg) { + try { + out.println(msg); + return in.readLine(); + } catch (Exception e) { + return null; + } + } - public void stopConnection() { - try { - in.close(); - out.close(); - clientSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } + public void stopConnection() { + try { + in.close(); + out.close(); + clientSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } - } + } } diff --git a/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java b/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java index 2ece1ceebe..b920967545 100644 --- a/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java +++ b/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java @@ -4,68 +4,67 @@ import java.net.*; import java.io.*; public class EchoMultiServer { - private ServerSocket serverSocket; + private ServerSocket serverSocket; - public void start(int port) { - try { - serverSocket = new ServerSocket(port); - while (true) - new EchoClientHandler(serverSocket.accept()).run(); + public void start(int port) { + try { + serverSocket = new ServerSocket(port); + while (true) + new EchoClientHandler(serverSocket.accept()).run(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - stop(); - } + } catch (IOException e) { + e.printStackTrace(); + } finally { + stop(); + } - } + } - public void stop() { - try { + public void stop() { + try { - serverSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } + serverSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } - } + } - private static class EchoClientHandler extends Thread { - private Socket clientSocket; - private PrintWriter out; - private BufferedReader in; + private static class EchoClientHandler extends Thread { + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; - public EchoClientHandler(Socket socket) { - this.clientSocket = socket; - } + public EchoClientHandler(Socket socket) { + this.clientSocket = socket; + } - public void run() { - try { - out = new PrintWriter(clientSocket.getOutputStream(), true); - in = new BufferedReader(new InputStreamReader( - clientSocket.getInputStream())); - String inputLine; - while ((inputLine = in.readLine()) != null) { - if (".".equals(inputLine)) { - out.println("bye"); - break; - } - out.println(inputLine); - } + public void run() { + try { + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + if (".".equals(inputLine)) { + out.println("bye"); + break; + } + out.println(inputLine); + } - in.close(); - out.close(); - clientSocket.close(); + in.close(); + out.close(); + clientSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } + } catch (IOException e) { + e.printStackTrace(); + } + } + } - public static void main(String[] args) { - EchoMultiServer server = new EchoMultiServer(); - server.start(5555); - } + public static void main(String[] args) { + EchoMultiServer server = new EchoMultiServer(); + server.start(5555); + } } diff --git a/core-java/src/main/java/com/baeldung/socket/EchoServer.java b/core-java/src/main/java/com/baeldung/socket/EchoServer.java index 3607afa7f5..dfd281d51c 100644 --- a/core-java/src/main/java/com/baeldung/socket/EchoServer.java +++ b/core-java/src/main/java/com/baeldung/socket/EchoServer.java @@ -4,47 +4,46 @@ import java.net.*; import java.io.*; public class EchoServer { - private ServerSocket serverSocket; - private Socket clientSocket; - private PrintWriter out; - private BufferedReader in; + private ServerSocket serverSocket; + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; - public void start(int port) { - try { - serverSocket = new ServerSocket(port); - clientSocket = serverSocket.accept(); - out = new PrintWriter(clientSocket.getOutputStream(), true); - in = new BufferedReader(new InputStreamReader( - clientSocket.getInputStream())); - String inputLine; - while ((inputLine = in.readLine()) != null) { - if (".".equals(inputLine)) { - out.println("good bye"); - break; - } - out.println(inputLine); - } - } catch (IOException e) { - e.printStackTrace(); - } + public void start(int port) { + try { + serverSocket = new ServerSocket(port); + clientSocket = serverSocket.accept(); + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + if (".".equals(inputLine)) { + out.println("good bye"); + break; + } + out.println(inputLine); + } + } catch (IOException e) { + e.printStackTrace(); + } - } + } - public void stop() { - try { - in.close(); - out.close(); - clientSocket.close(); - serverSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } + public void stop() { + try { + in.close(); + out.close(); + clientSocket.close(); + serverSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } - } + } - public static void main(String[] args) { - EchoServer server = new EchoServer(); - server.start(4444); - } + public static void main(String[] args) { + EchoServer server = new EchoServer(); + server.start(4444); + } } diff --git a/core-java/src/main/java/com/baeldung/socket/GreetClient.java b/core-java/src/main/java/com/baeldung/socket/GreetClient.java index 21959c7469..e6f14bb2b6 100644 --- a/core-java/src/main/java/com/baeldung/socket/GreetClient.java +++ b/core-java/src/main/java/com/baeldung/socket/GreetClient.java @@ -7,39 +7,38 @@ import java.io.PrintWriter; import java.net.Socket; public class GreetClient { - private Socket clientSocket; - private PrintWriter out; - private BufferedReader in; + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; - public void startConnection(String ip, int port) { - try { - clientSocket = new Socket(ip, port); - out = new PrintWriter(clientSocket.getOutputStream(), true); - in = new BufferedReader(new InputStreamReader( - clientSocket.getInputStream())); - } catch (IOException e) { - - } + public void startConnection(String ip, int port) { + try { + clientSocket = new Socket(ip, port); + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + } catch (IOException e) { - } + } - public String sendMessage(String msg) { - try { - out.println(msg); - return in.readLine(); - } catch (Exception e) { - return null; - } - } + } - public void stopConnection() { - try { - in.close(); - out.close(); - clientSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } + public String sendMessage(String msg) { + try { + out.println(msg); + return in.readLine(); + } catch (Exception e) { + return null; + } + } + + public void stopConnection() { + try { + in.close(); + out.close(); + clientSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } } diff --git a/core-java/src/main/java/com/baeldung/socket/GreetServer.java b/core-java/src/main/java/com/baeldung/socket/GreetServer.java index 8bf675c7b9..05bc65a65e 100644 --- a/core-java/src/main/java/com/baeldung/socket/GreetServer.java +++ b/core-java/src/main/java/com/baeldung/socket/GreetServer.java @@ -4,44 +4,43 @@ import java.net.*; import java.io.*; public class GreetServer { - private ServerSocket serverSocket; - private Socket clientSocket; - private PrintWriter out; - private BufferedReader in; + private ServerSocket serverSocket; + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; + public void start(int port) { + try { + serverSocket = new ServerSocket(port); + clientSocket = serverSocket.accept(); + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + String greeting = in.readLine(); + if ("hello server".equals(greeting)) + out.println("hello client"); + else + out.println("unrecognised greeting"); + } catch (IOException e) { + e.printStackTrace(); + } - public void start(int port) { - try { - serverSocket = new ServerSocket(port); - clientSocket = serverSocket.accept(); - out = new PrintWriter(clientSocket.getOutputStream(), true); - in = new BufferedReader(new InputStreamReader( - clientSocket.getInputStream())); - String greeting = in.readLine(); - if ("hello server".equals(greeting)) - out.println("hello client"); - else - out.println("unrecognised greeting"); - } catch (IOException e) { - e.printStackTrace(); - } + } - } + public void stop() { + try { + in.close(); + out.close(); + clientSocket.close(); + serverSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } - public void stop() { - try { - in.close(); - out.close(); - clientSocket.close(); - serverSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } + } - } - public static void main(String[] args) { - GreetServer server=new GreetServer(); - server.start(6666); - } + public static void main(String[] args) { + GreetServer server = new GreetServer(); + server.start(6666); + } } diff --git a/core-java/src/main/java/com/baeldung/streamApi/Product.java b/core-java/src/main/java/com/baeldung/streamApi/Product.java index 18f3a61904..26b8bd6fed 100644 --- a/core-java/src/main/java/com/baeldung/streamApi/Product.java +++ b/core-java/src/main/java/com/baeldung/streamApi/Product.java @@ -44,7 +44,6 @@ public class Product { this.name = name; } - public static Stream streamOf(List list) { return (list == null || list.isEmpty()) ? Stream.empty() : list.stream(); } diff --git a/core-java/src/main/java/com/baeldung/threadpool/CountingTask.java b/core-java/src/main/java/com/baeldung/threadpool/CountingTask.java index 05aa14c5ae..effdf54916 100644 --- a/core-java/src/main/java/com/baeldung/threadpool/CountingTask.java +++ b/core-java/src/main/java/com/baeldung/threadpool/CountingTask.java @@ -14,9 +14,7 @@ public class CountingTask extends RecursiveTask { @Override protected Integer compute() { - return node.value + node.children.stream() - .map(childNode -> new CountingTask(childNode).fork()) - .collect(Collectors.summingInt(ForkJoinTask::join)); + return node.value + node.children.stream().map(childNode -> new CountingTask(childNode).fork()).collect(Collectors.summingInt(ForkJoinTask::join)); } } diff --git a/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java b/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java index 2c52a17904..09344902b7 100644 --- a/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java +++ b/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java @@ -4,8 +4,8 @@ import javax.swing.JOptionPane; public class ExecutableMavenJar { - public static void main(String[] args) { - JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1); - } + public static void main(String[] args) { + JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1); + } } diff --git a/core-java/src/test/java/com/baeldung/CharToStringTest.java b/core-java/src/test/java/com/baeldung/CharToStringTest.java index d91016d104..4fd451f2ed 100644 --- a/core-java/src/test/java/com/baeldung/CharToStringTest.java +++ b/core-java/src/test/java/com/baeldung/CharToStringTest.java @@ -7,7 +7,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class CharToStringTest { @Test - public void givenChar_whenCallingStringValueOf_shouldConvertToString(){ + public void givenChar_whenCallingStringValueOf_shouldConvertToString() { final char givenChar = 'x'; final String result = String.valueOf(givenChar); @@ -16,7 +16,7 @@ public class CharToStringTest { } @Test - public void givenChar_whenCallingToStringOnCharacter_shouldConvertToString(){ + public void givenChar_whenCallingToStringOnCharacter_shouldConvertToString() { final char givenChar = 'x'; final String result = Character.toString(givenChar); @@ -25,7 +25,7 @@ public class CharToStringTest { } @Test - public void givenChar_whenCallingCharacterConstructor_shouldConvertToString3(){ + public void givenChar_whenCallingCharacterConstructor_shouldConvertToString3() { final char givenChar = 'x'; final String result = new Character(givenChar).toString(); @@ -34,7 +34,7 @@ public class CharToStringTest { } @Test - public void givenChar_whenConcatenated_shouldConvertToString4(){ + public void givenChar_whenConcatenated_shouldConvertToString4() { final char givenChar = 'x'; final String result = givenChar + ""; @@ -43,7 +43,7 @@ public class CharToStringTest { } @Test - public void givenChar_whenFormated_shouldConvertToString5(){ + public void givenChar_whenFormated_shouldConvertToString5() { final char givenChar = 'x'; final String result = String.format("%c", givenChar); diff --git a/core-java/src/test/java/com/baeldung/RandomListElementTest.java b/core-java/src/test/java/com/baeldung/RandomListElementUnitTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/RandomListElementTest.java rename to core-java/src/test/java/com/baeldung/RandomListElementUnitTest.java index 1918c801dc..6ae7c40f4d 100644 --- a/core-java/src/test/java/com/baeldung/RandomListElementTest.java +++ b/core-java/src/test/java/com/baeldung/RandomListElementUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import java.util.*; import java.util.concurrent.ThreadLocalRandom; -public class RandomListElementTest { +public class RandomListElementUnitTest { @Test public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom() { @@ -20,7 +20,7 @@ public class RandomListElementTest { public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingMathRandom() { List givenList = Lists.newArrayList(1, 2, 3); - givenList.get((int)(Math.random() * givenList.size())); + givenList.get((int) (Math.random() * givenList.size())); } @Test diff --git a/core-java/src/test/java/com/baeldung/StringToIntOrIntegerTest.java b/core-java/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/StringToIntOrIntegerTest.java rename to core-java/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java index 6c1493d89b..a7ad0bf114 100644 --- a/core-java/src/test/java/com/baeldung/StringToIntOrIntegerTest.java +++ b/core-java/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java @@ -1,11 +1,12 @@ package com.baeldung; -import com.google.common.primitives.Ints; -import org.junit.Test; - import static org.assertj.core.api.Assertions.assertThat; -public class StringToIntOrIntegerTest { +import org.junit.Test; + +import com.google.common.primitives.Ints; + +public class StringToIntOrIntegerUnitTest { @Test public void givenString_whenParsingInt_shouldConvertToInt() { @@ -16,7 +17,6 @@ public class StringToIntOrIntegerTest { assertThat(result).isEqualTo(42); } - @Test public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() { String givenString = "42"; diff --git a/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java b/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java index d94f72b685..ac8c666e4b 100644 --- a/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java +++ b/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java @@ -42,192 +42,137 @@ public class Java8CollectorsTest { @Test public void whenCollectingToList_shouldCollectToList() throws Exception { - final List result = givenList.stream() - .collect(toList()); + final List result = givenList.stream().collect(toList()); - assertThat(result) - .containsAll(givenList); + assertThat(result).containsAll(givenList); } @Test public void whenCollectingToList_shouldCollectToSet() throws Exception { - final Set result = givenList.stream() - .collect(toSet()); + final Set result = givenList.stream().collect(toSet()); - assertThat(result) - .containsAll(givenList); + assertThat(result).containsAll(givenList); } @Test public void whenCollectingToCollection_shouldCollectToCollection() throws Exception { - final List result = givenList.stream() - .collect(toCollection(LinkedList::new)); + final List result = givenList.stream().collect(toCollection(LinkedList::new)); - assertThat(result) - .containsAll(givenList) - .isInstanceOf(LinkedList.class); + assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class); } @Test public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception { assertThatThrownBy(() -> { - givenList.stream() - .collect(toCollection(ImmutableList::of)); + givenList.stream().collect(toCollection(ImmutableList::of)); }).isInstanceOf(UnsupportedOperationException.class); } @Test public void whenCollectingToMap_shouldCollectToMap() throws Exception { - final Map result = givenList.stream() - .collect(toMap(Function.identity(), String::length)); + final Map result = givenList.stream().collect(toMap(Function.identity(), String::length)); - assertThat(result) - .containsEntry("a", 1) - .containsEntry("bb", 2) - .containsEntry("ccc", 3) - .containsEntry("dd", 2); + assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2); } @Test public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception { - final Map result = givenList.stream() - .collect(toMap(Function.identity(), String::length, (i1, i2) -> i1)); + final Map result = givenList.stream().collect(toMap(Function.identity(), String::length, (i1, i2) -> i1)); - assertThat(result) - .containsEntry("a", 1) - .containsEntry("bb", 2) - .containsEntry("ccc", 3) - .containsEntry("dd", 2); + assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2); } @Test public void whenCollectingAndThen_shouldCollect() throws Exception { - final List result = givenList.stream() - .collect(collectingAndThen(toList(), ImmutableList::copyOf)); + final List result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf)); - assertThat(result) - .containsAll(givenList) - .isInstanceOf(ImmutableList.class); + assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class); } @Test public void whenJoining_shouldJoin() throws Exception { - final String result = givenList.stream() - .collect(joining()); + final String result = givenList.stream().collect(joining()); - assertThat(result) - .isEqualTo("abbcccdd"); + assertThat(result).isEqualTo("abbcccdd"); } @Test public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception { - final String result = givenList.stream() - .collect(joining(" ")); + final String result = givenList.stream().collect(joining(" ")); - assertThat(result) - .isEqualTo("a bb ccc dd"); + assertThat(result).isEqualTo("a bb ccc dd"); } @Test public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception { - final String result = givenList.stream() - .collect(joining(" ", "PRE-", "-POST")); + final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST")); - assertThat(result) - .isEqualTo("PRE-a bb ccc dd-POST"); + assertThat(result).isEqualTo("PRE-a bb ccc dd-POST"); } @Test public void whenPartitioningBy_shouldPartition() throws Exception { - final Map> result = givenList.stream() - .collect(partitioningBy(s -> s.length() > 2)); + final Map> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2)); - assertThat(result) - .containsKeys(true, false) - .satisfies(booleanListMap -> { - assertThat(booleanListMap.get(true)) - .contains("ccc"); + assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> { + assertThat(booleanListMap.get(true)).contains("ccc"); - assertThat(booleanListMap.get(false)) - .contains("a", "bb", "dd"); - }); + assertThat(booleanListMap.get(false)).contains("a", "bb", "dd"); + }); } @Test public void whenCounting_shouldCount() throws Exception { - final Long result = givenList.stream() - .collect(counting()); + final Long result = givenList.stream().collect(counting()); - assertThat(result) - .isEqualTo(4); + assertThat(result).isEqualTo(4); } @Test public void whenSummarizing_shouldSummarize() throws Exception { - final DoubleSummaryStatistics result = givenList.stream() - .collect(summarizingDouble(String::length)); + final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length)); - assertThat(result.getAverage()) - .isEqualTo(2); - assertThat(result.getCount()) - .isEqualTo(4); - assertThat(result.getMax()) - .isEqualTo(3); - assertThat(result.getMin()) - .isEqualTo(1); - assertThat(result.getSum()) - .isEqualTo(8); + assertThat(result.getAverage()).isEqualTo(2); + assertThat(result.getCount()).isEqualTo(4); + assertThat(result.getMax()).isEqualTo(3); + assertThat(result.getMin()).isEqualTo(1); + assertThat(result.getSum()).isEqualTo(8); } @Test public void whenAveraging_shouldAverage() throws Exception { - final Double result = givenList.stream() - .collect(averagingDouble(String::length)); + final Double result = givenList.stream().collect(averagingDouble(String::length)); - assertThat(result) - .isEqualTo(2); + assertThat(result).isEqualTo(2); } @Test public void whenSumming_shouldSum() throws Exception { - final Double result = givenList.stream() - .collect(summingDouble(String::length)); + final Double result = givenList.stream().collect(summingDouble(String::length)); - assertThat(result) - .isEqualTo(8); + assertThat(result).isEqualTo(8); } @Test public void whenMaxingBy_shouldMaxBy() throws Exception { - final Optional result = givenList.stream() - .collect(maxBy(Comparator.naturalOrder())); + final Optional result = givenList.stream().collect(maxBy(Comparator.naturalOrder())); - assertThat(result) - .isPresent() - .hasValue("dd"); + assertThat(result).isPresent().hasValue("dd"); } @Test public void whenGroupingBy_shouldGroupBy() throws Exception { - final Map> result = givenList.stream() - .collect(groupingBy(String::length, toSet())); + final Map> result = givenList.stream().collect(groupingBy(String::length, toSet())); - assertThat(result) - .containsEntry(1, newHashSet("a")) - .containsEntry(2, newHashSet("bb", "dd")) - .containsEntry(3, newHashSet("ccc")); + assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc")); } - @Test public void whenCreatingCustomCollector_shouldCollect() throws Exception { - final ImmutableSet result = givenList.stream() - .collect(toImmutableSet()); + final ImmutableSet result = givenList.stream().collect(toImmutableSet()); - assertThat(result) - .isInstanceOf(ImmutableSet.class) - .contains("a", "bb", "ccc", "dd"); + assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd"); } diff --git a/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java b/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureUnitTest.java similarity index 88% rename from core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java rename to core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureUnitTest.java index 5363a73afa..df12c3d79e 100644 --- a/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java +++ b/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureUnitTest.java @@ -1,24 +1,26 @@ package com.baeldung.completablefuture; -import java.util.concurrent.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class CompletableFutureTest { +public class CompletableFutureUnitTest { @Test public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException { - Future completableFuture = calculateAsync(); String result = completableFuture.get(); assertEquals("Hello", result); - } public Future calculateAsync() throws InterruptedException { @@ -35,15 +37,12 @@ public class CompletableFutureTest { @Test public void whenRunningCompletableFutureWithResult_thenGetMethodReturnsImmediately() throws InterruptedException, ExecutionException { - Future completableFuture = CompletableFuture.completedFuture("Hello"); String result = completableFuture.get(); assertEquals("Hello", result); - } - public Future calculateAsyncWithCancellation() throws InterruptedException { CompletableFuture completableFuture = new CompletableFuture<>(); @@ -56,90 +55,67 @@ public class CompletableFutureTest { return completableFuture; } - @Test(expected = CancellationException.class) public void whenCancelingTheFuture_thenThrowsCancellationException() throws ExecutionException, InterruptedException { - Future future = calculateAsyncWithCancellation(); future.get(); - } @Test public void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() throws ExecutionException, InterruptedException { - CompletableFuture future = CompletableFuture.supplyAsync(() -> "Hello"); assertEquals("Hello", future.get()); - } @Test public void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture future = completableFuture.thenAccept(s -> System.out.println("Computation returned: " + s)); future.get(); - } @Test public void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture future = completableFuture.thenRun(() -> System.out.println("Computation finished.")); future.get(); - } @Test public void whenAddingThenApplyToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture future = completableFuture.thenApply(s -> s + " World"); assertEquals("Hello World", future.get()); - } @Test public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException { - - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello") - .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World")); + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World")); assertEquals("Hello World", completableFuture.get()); - } @Test public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { - - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello") - .thenCombine(CompletableFuture.supplyAsync(() -> " World"), - (s1, s2) -> s1 + s2); + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2); assertEquals("Hello World", completableFuture.get()); - } @Test public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { - - CompletableFuture.supplyAsync(() -> "Hello") - .thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), - (s1, s2) -> System.out.println(s1 + s2)); - + CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> System.out.println(s1 + s2)); } @Test public void whenFutureCombinedWithAllOfCompletes_thenAllFuturesAreDone() throws ExecutionException, InterruptedException { - CompletableFuture future1 = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture future2 = CompletableFuture.supplyAsync(() -> "Beautiful"); CompletableFuture future3 = CompletableFuture.supplyAsync(() -> "World"); @@ -154,17 +130,13 @@ public class CompletableFutureTest { assertTrue(future2.isDone()); assertTrue(future3.isDone()); - String combined = Stream.of(future1, future2, future3) - .map(CompletableFuture::join) - .collect(Collectors.joining(" ")); + String combined = Stream.of(future1, future2, future3).map(CompletableFuture::join).collect(Collectors.joining(" ")); assertEquals("Hello Beautiful World", combined); - } @Test public void whenFutureThrows_thenHandleMethodReceivesException() throws ExecutionException, InterruptedException { - String name = null; // ... @@ -177,12 +149,10 @@ public class CompletableFutureTest { }).handle((s, t) -> s != null ? s : "Hello, Stranger!"); assertEquals("Hello, Stranger!", completableFuture.get()); - } @Test(expected = ExecutionException.class) public void whenCompletingFutureExceptionally_thenGetMethodThrows() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = new CompletableFuture<>(); // ... @@ -192,18 +162,15 @@ public class CompletableFutureTest { // ... completableFuture.get(); - } @Test public void whenAddingThenApplyAsyncToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture future = completableFuture.thenApplyAsync(s -> s + " World"); assertEquals("Hello World", future.get()); - } } \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java b/core-java/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java rename to core-java/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java index 4bce40c2d9..e4753dbd5c 100644 --- a/core-java/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java +++ b/core-java/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java @@ -14,7 +14,7 @@ import java.time.temporal.ChronoUnit; import static org.assertj.core.api.Assertions.assertThat; -public class JavaUtilTimeTest { +public class JavaUtilTimeUnitTest { @Test public void currentTime() { diff --git a/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java similarity index 89% rename from core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java rename to core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java index e07bcc9a8d..6f3384c8eb 100644 --- a/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java +++ b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java @@ -1,7 +1,8 @@ package com.baeldung.functionalinterface; -import com.google.common.util.concurrent.Uninterruptibles; -import org.junit.Test; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.HashMap; @@ -13,54 +14,43 @@ import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; -import static org.junit.Assert.*; +import org.junit.Test; -public class FunctionalInterfaceTest { +import com.google.common.util.concurrent.Uninterruptibles; + +public class FunctionalInterfaceUnitTest { @Test public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() { - Map nameMap = new HashMap<>(); Integer value = nameMap.computeIfAbsent("John", s -> s.length()); assertEquals(new Integer(4), nameMap.get("John")); assertEquals(new Integer(4), value); - } @Test public void whenPassingMethodReferenceToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() { - Map nameMap = new HashMap<>(); Integer value = nameMap.computeIfAbsent("John", String::length); assertEquals(new Integer(4), nameMap.get("John")); assertEquals(new Integer(4), value); - - } - - public byte[] transformArray(short[] array, ShortToByteFunction function) { - byte[] transformedArray = new byte[array.length]; - for (int i = 0; i < array.length; i++) { - transformedArray[i] = function.applyAsByte(array[i]); - } - return transformedArray; } @Test public void whenUsingCustomFunctionalInterfaceForPrimitives_thenCanUseItAsLambda() { - short[] array = {(short) 1, (short) 2, (short) 3}; + short[] array = { (short) 1, (short) 2, (short) 3 }; byte[] transformedArray = transformArray(array, s -> (byte) (s * 2)); - byte[] expectedArray = {(byte) 2, (byte) 4, (byte) 6}; + byte[] expectedArray = { (byte) 2, (byte) 4, (byte) 6 }; assertArrayEquals(expectedArray, transformedArray); } @Test public void whenUsingBiFunction_thenCanUseItToReplaceMapValues() { - Map salaries = new HashMap<>(); salaries.put("John", 40000); salaries.put("Freddy", 30000); @@ -71,22 +61,18 @@ public class FunctionalInterfaceTest { assertEquals(new Integer(50000), salaries.get("John")); assertEquals(new Integer(30000), salaries.get("Freddy")); assertEquals(new Integer(60000), salaries.get("Samuel")); - } - @Test public void whenPassingLambdaToThreadConstructor_thenLambdaInferredToRunnable() { - Thread thread = new Thread(() -> System.out.println("Hello From Another Thread")); thread.start(); - } @Test public void whenUsingSupplierToGenerateNumbers_thenCanUseItInStreamGenerate() { - int[] fibs = {0, 1}; + int[] fibs = { 0, 1 }; Stream fibonacci = Stream.generate(() -> { int result = fibs[1]; int fib3 = fibs[0] + fibs[1]; @@ -95,55 +81,44 @@ public class FunctionalInterfaceTest { return result; }); - List fibonacci5 = fibonacci.limit(5) - .collect(Collectors.toList()); + List fibonacci5 = fibonacci.limit(5).collect(Collectors.toList()); assertEquals(new Integer(1), fibonacci5.get(0)); assertEquals(new Integer(1), fibonacci5.get(1)); assertEquals(new Integer(2), fibonacci5.get(2)); assertEquals(new Integer(3), fibonacci5.get(3)); assertEquals(new Integer(5), fibonacci5.get(4)); - } @Test public void whenUsingConsumerInForEach_thenConsumerExecutesForEachListElement() { - List names = Arrays.asList("John", "Freddy", "Samuel"); names.forEach(name -> System.out.println("Hello, " + name)); - } @Test public void whenUsingBiConsumerInForEach_thenConsumerExecutesForEachMapElement() { - Map ages = new HashMap<>(); ages.put("John", 25); ages.put("Freddy", 24); ages.put("Samuel", 30); ages.forEach((name, age) -> System.out.println(name + " is " + age + " years old")); - } @Test public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() { - List names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David"); - List namesWithA = names.stream() - .filter(name -> name.startsWith("A")) - .collect(Collectors.toList()); + List namesWithA = names.stream().filter(name -> name.startsWith("A")).collect(Collectors.toList()); assertEquals(2, namesWithA.size()); assertTrue(namesWithA.contains("Angela")); assertTrue(namesWithA.contains("Aaron")); - } @Test public void whenUsingUnaryOperatorWithReplaceAll_thenAllValuesInTheListAreReplaced() { - List names = Arrays.asList("bob", "josh", "megan"); names.replaceAll(String::toUpperCase); @@ -151,7 +126,6 @@ public class FunctionalInterfaceTest { assertEquals("BOB", names.get(0)); assertEquals("JOSH", names.get(1)); assertEquals("MEGAN", names.get(2)); - } @Test @@ -159,8 +133,7 @@ public class FunctionalInterfaceTest { List values = Arrays.asList(3, 5, 8, 9, 12); - int sum = values.stream() - .reduce(0, (i1, i2) -> i1 + i2); + int sum = values.stream().reduce(0, (i1, i2) -> i1 + i2); assertEquals(37, sum); @@ -178,10 +151,6 @@ public class FunctionalInterfaceTest { } - public double squareLazy(Supplier lazyValue) { - return Math.pow(lazyValue.get(), 2); - } - @Test public void whenUsingSupplierToGenerateValue_thenValueIsGeneratedLazily() { @@ -196,4 +165,18 @@ public class FunctionalInterfaceTest { } + // + + public double squareLazy(Supplier lazyValue) { + return Math.pow(lazyValue.get(), 2); + } + + public byte[] transformArray(short[] array, ShortToByteFunction function) { + byte[] transformedArray = new byte[array.length]; + for (int i = 0; i < array.length; i++) { + transformedArray[i] = function.applyAsByte(array[i]); + } + return transformedArray; + } + } diff --git a/core-java/src/test/java/com/baeldung/java/networking/udp/UDPTest.java b/core-java/src/test/java/com/baeldung/java/networking/udp/UDPTest.java new file mode 100644 index 0000000000..cf35c07ab3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/networking/udp/UDPTest.java @@ -0,0 +1,39 @@ +package com.baeldung.java.networking.udp; + + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +public class UDPTest { + private EchoClient client; + + @Before + public void setup() throws IOException { + new EchoServer().start(); + client = new EchoClient(); + } + + @Test + public void whenCanSendAndReceivePacket_thenCorrect1() { + String echo = client.sendEcho("hello server"); + assertEquals("hello server", echo); + echo = client.sendEcho("server is working"); + assertFalse(echo.equals("hello server")); + } + + @After + public void tearDown() { + stopEchoServer(); + client.close(); + } + + private void stopEchoServer() { + client.sendEcho("end"); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/networking/url/UrlTest.java b/core-java/src/test/java/com/baeldung/java/networking/url/UrlTest.java new file mode 100644 index 0000000000..14444f0145 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/networking/url/UrlTest.java @@ -0,0 +1,104 @@ +package com.baeldung.java.networking.url; + +import static org.junit.Assert.assertEquals; + +import java.net.MalformedURLException; +import java.net.URL; + +import org.junit.Test; + +public class UrlTest { + + @Test + public void givenUrl_whenCanIdentifyProtocol_thenCorrect() throws MalformedURLException { + URL url = new URL("http://baeldung.com"); + assertEquals("http", url.getProtocol()); + } + + @Test + public void givenUrl_whenCanGetHost_thenCorrect() throws MalformedURLException { + URL url = new URL("http://baeldung.com"); + assertEquals("baeldung.com", url.getHost()); + } + + @Test + public void givenUrl_whenCanGetFileName_thenCorrect2() throws MalformedURLException { + URL url = new URL("http://baeldung.com/articles?topic=java&version=8"); + assertEquals("/articles?topic=java&version=8", url.getFile()); + } + + @Test + public void givenUrl_whenCanGetFileName_thenCorrect1() throws MalformedURLException { + URL url = new URL("http://baeldung.com/guidelines.txt"); + assertEquals("/guidelines.txt", url.getFile()); + } + + @Test + public void givenUrl_whenCanGetPathParams_thenCorrect() throws MalformedURLException { + URL url = new URL("http://baeldung.com/articles?topic=java&version=8"); + assertEquals("/articles", url.getPath()); + } + + @Test + public void givenUrl_whenCanGetQueryParams_thenCorrect() throws MalformedURLException { + URL url = new URL("http://baeldung.com/articles?topic=java"); + assertEquals("topic=java", url.getQuery()); + } + + @Test + public void givenUrl_whenGetsDefaultPort_thenCorrect() throws MalformedURLException { + URL url = new URL("http://baeldung.com"); + assertEquals(-1, url.getPort()); + assertEquals(80, url.getDefaultPort()); + } + + @Test + public void givenUrl_whenGetsPort_thenCorrect() throws MalformedURLException { + URL url = new URL("http://baeldung.com:8090"); + assertEquals(8090, url.getPort()); + assertEquals(80, url.getDefaultPort()); + } + + @Test + public void givenBaseUrl_whenCreatesRelativeUrl_thenCorrect() throws MalformedURLException { + URL baseUrl = new URL("http://baeldung.com"); + URL relativeUrl = new URL(baseUrl, "a-guide-to-java-sockets"); + assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString()); + } + + @Test + public void givenAbsoluteUrl_whenIgnoresBaseUrl_thenCorrect() throws MalformedURLException { + URL baseUrl = new URL("http://baeldung.com"); + URL relativeUrl = new URL(baseUrl, "http://baeldung.com/a-guide-to-java-sockets"); + assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString()); + } + + @Test + public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException { + String protocol = "http"; + String host = "baeldung.com"; + String file = "/guidelines.txt"; + URL url = new URL(protocol, host, file); + assertEquals("http://baeldung.com/guidelines.txt", url.toString()); + } + + @Test + public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect2() throws MalformedURLException { + String protocol = "http"; + String host = "baeldung.com"; + String file = "/articles?topic=java&version=8"; + URL url = new URL(protocol, host, file); + assertEquals("http://baeldung.com/guidelines.txt", url.toString()); + } + + @Test + public void givenUrlComponentsWithPort_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException { + String protocol = "http"; + String host = "baeldung.com"; + int port = 9000; + String file = "/guidelines.txt"; + URL url = new URL(protocol, host, port, file); + assertEquals("http://baeldung.com:9000/guidelines.txt", url.toString()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java b/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java index d1ac6df5e4..cb7ecefc81 100644 --- a/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java +++ b/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java @@ -16,6 +16,7 @@ public class EchoTest { String resp2 = client.sendMessage("world"); assertEquals("hello", resp1); assertEquals("world", resp2); + process.destroy(); } } diff --git a/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java b/core-java/src/test/java/com/baeldung/java/reflection/ReflectionUnitTest.java similarity index 81% rename from core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java rename to core-java/src/test/java/com/baeldung/java/reflection/ReflectionUnitTest.java index a12a2f205f..e008616c72 100644 --- a/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java +++ b/core-java/src/test/java/com/baeldung/java/reflection/ReflectionUnitTest.java @@ -11,7 +11,7 @@ import java.util.List; import java.util.ArrayList; import static org.junit.Assert.*; -public class ReflectionTest { +public class ReflectionUnitTest { @Test public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() { @@ -20,8 +20,7 @@ public class ReflectionTest { List actualFieldNames = getFieldNames(fields); - assertTrue(Arrays.asList("name", "age") - .containsAll(actualFieldNames)); + assertTrue(Arrays.asList("name", "age").containsAll(actualFieldNames)); } @Test @@ -35,8 +34,7 @@ public class ReflectionTest { } @Test - public void givenClassName_whenCreatesObject_thenCorrect() - throws ClassNotFoundException { + public void givenClassName_whenCreatesObject_thenCorrect() throws ClassNotFoundException { Class clazz = Class.forName("com.baeldung.java.reflection.Goat"); assertEquals("Goat", clazz.getSimpleName()); @@ -45,8 +43,7 @@ public class ReflectionTest { } @Test - public void givenClass_whenRecognisesModifiers_thenCorrect() - throws ClassNotFoundException { + public void givenClass_whenRecognisesModifiers_thenCorrect() throws ClassNotFoundException { Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); int goatMods = goatClass.getModifiers(); @@ -80,8 +77,7 @@ public class ReflectionTest { } @Test - public void givenClass_whenGetsImplementedInterfaces_thenCorrect() - throws ClassNotFoundException { + public void givenClass_whenGetsImplementedInterfaces_thenCorrect() throws ClassNotFoundException { Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); Class[] goatInterfaces = goatClass.getInterfaces(); @@ -94,8 +90,7 @@ public class ReflectionTest { } @Test - public void givenClass_whenGetsConstructor_thenCorrect() - throws ClassNotFoundException { + public void givenClass_whenGetsConstructor_thenCorrect() throws ClassNotFoundException { Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); Constructor[] constructors = goatClass.getConstructors(); @@ -104,8 +99,7 @@ public class ReflectionTest { } @Test - public void givenClass_whenGetsFields_thenCorrect() - throws ClassNotFoundException { + public void givenClass_whenGetsFields_thenCorrect() throws ClassNotFoundException { Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); Field[] fields = animalClass.getDeclaredFields(); @@ -116,20 +110,17 @@ public class ReflectionTest { } @Test - public void givenClass_whenGetsMethods_thenCorrect() - throws ClassNotFoundException { + public void givenClass_whenGetsMethods_thenCorrect() throws ClassNotFoundException { Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); Method[] methods = animalClass.getDeclaredMethods(); List actualMethods = getMethodNames(methods); assertEquals(4, actualMethods.size()); - assertTrue(actualMethods.containsAll(Arrays.asList("getName", - "setName", "getSound"))); + assertTrue(actualMethods.containsAll(Arrays.asList("getName", "setName", "getSound"))); } @Test - public void givenClass_whenGetsAllConstructors_thenCorrect() - throws ClassNotFoundException { + public void givenClass_whenGetsAllConstructors_thenCorrect() throws ClassNotFoundException { Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); Constructor[] constructors = birdClass.getConstructors(); @@ -137,24 +128,20 @@ public class ReflectionTest { } @Test - public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() - throws Exception { + public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() throws Exception { Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); Constructor cons1 = birdClass.getConstructor(); Constructor cons2 = birdClass.getConstructor(String.class); - Constructor cons3 = birdClass.getConstructor(String.class, - boolean.class); + Constructor cons3 = birdClass.getConstructor(String.class, boolean.class); } @Test - public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() - throws Exception { + public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() throws Exception { Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); Constructor cons1 = birdClass.getConstructor(); Constructor cons2 = birdClass.getConstructor(String.class); - Constructor cons3 = birdClass.getConstructor(String.class, - boolean.class); + Constructor cons3 = birdClass.getConstructor(String.class, boolean.class); Bird bird1 = (Bird) cons1.newInstance(); Bird bird2 = (Bird) cons2.newInstance("Weaver bird"); @@ -168,8 +155,7 @@ public class ReflectionTest { } @Test - public void givenClass_whenGetsPublicFields_thenCorrect() - throws ClassNotFoundException { + public void givenClass_whenGetsPublicFields_thenCorrect() throws ClassNotFoundException { Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); Field[] fields = birdClass.getFields(); assertEquals(1, fields.length); @@ -178,8 +164,7 @@ public class ReflectionTest { } @Test - public void givenClass_whenGetsPublicFieldByName_thenCorrect() - throws Exception { + public void givenClass_whenGetsPublicFieldByName_thenCorrect() throws Exception { Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); Field field = birdClass.getField("CATEGORY"); assertEquals("CATEGORY", field.getName()); @@ -187,8 +172,7 @@ public class ReflectionTest { } @Test - public void givenClass_whenGetsDeclaredFields_thenCorrect() - throws ClassNotFoundException { + public void givenClass_whenGetsDeclaredFields_thenCorrect() throws ClassNotFoundException { Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); Field[] fields = birdClass.getDeclaredFields(); assertEquals(1, fields.length); @@ -196,8 +180,7 @@ public class ReflectionTest { } @Test - public void givenClass_whenGetsFieldsByName_thenCorrect() - throws Exception { + public void givenClass_whenGetsFieldsByName_thenCorrect() throws Exception { Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); Field field = birdClass.getDeclaredField("walks"); assertEquals("walks", field.getName()); @@ -205,17 +188,14 @@ public class ReflectionTest { } @Test - public void givenClassField_whenGetsType_thenCorrect() - throws Exception { - Field field = Class.forName("com.baeldung.java.reflection.Bird") - .getDeclaredField("walks"); + public void givenClassField_whenGetsType_thenCorrect() throws Exception { + Field field = Class.forName("com.baeldung.java.reflection.Bird").getDeclaredField("walks"); Class fieldClass = field.getType(); assertEquals("boolean", fieldClass.getSimpleName()); } @Test - public void givenClassField_whenSetsAndGetsValue_thenCorrect() - throws Exception { + public void givenClassField_whenSetsAndGetsValue_thenCorrect() throws Exception { Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); Bird bird = (Bird) birdClass.newInstance(); Field field = birdClass.getDeclaredField("walks"); @@ -232,8 +212,7 @@ public class ReflectionTest { } @Test - public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() - throws Exception { + public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() throws Exception { Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); Field field = birdClass.getField("CATEGORY"); field.setAccessible(true); @@ -242,21 +221,17 @@ public class ReflectionTest { } @Test - public void givenClass_whenGetsAllPublicMethods_thenCorrect() - throws ClassNotFoundException { + public void givenClass_whenGetsAllPublicMethods_thenCorrect() throws ClassNotFoundException { Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); Method[] methods = birdClass.getMethods(); List methodNames = getMethodNames(methods); - assertTrue(methodNames.containsAll(Arrays - .asList("equals", "notifyAll", "hashCode", - "walks", "eats", "toString"))); + assertTrue(methodNames.containsAll(Arrays.asList("equals", "notifyAll", "hashCode", "walks", "eats", "toString"))); } @Test - public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() - throws ClassNotFoundException { + public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() throws ClassNotFoundException { Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); List actualMethodNames = getMethodNames(birdClass.getDeclaredMethods()); @@ -269,12 +244,10 @@ public class ReflectionTest { } @Test - public void givenMethodName_whenGetsMethod_thenCorrect() - throws Exception { + public void givenMethodName_whenGetsMethod_thenCorrect() throws Exception { Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); Method walksMethod = birdClass.getDeclaredMethod("walks"); - Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", - boolean.class); + Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class); assertFalse(walksMethod.isAccessible()); assertFalse(setWalksMethod.isAccessible()); @@ -288,12 +261,10 @@ public class ReflectionTest { } @Test - public void givenMethod_whenInvokes_thenCorrect() - throws Exception { + public void givenMethod_whenInvokes_thenCorrect() throws Exception { Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); Bird bird = (Bird) birdClass.newInstance(); - Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", - boolean.class); + Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class); Method walksMethod = birdClass.getDeclaredMethod("walks"); boolean walks = (boolean) walksMethod.invoke(bird); @@ -308,19 +279,19 @@ public class ReflectionTest { } - private static List getFieldNames(Field[] fields) { - List fieldNames = new ArrayList<>(); - for (Field field : fields) - fieldNames.add(field.getName()); - return fieldNames; + private static List getFieldNames(Field[] fields) { + List fieldNames = new ArrayList<>(); + for (Field field : fields) + fieldNames.add(field.getName()); + return fieldNames; - } + } - private static List getMethodNames(Method[] methods) { - List methodNames = new ArrayList<>(); - for (Method method : methods) - methodNames.add(method.getName()); - return methodNames; - } + private static List getMethodNames(Method[] methods) { + List methodNames = new ArrayList<>(); + for (Method method : methods) + methodNames.add(method.getName()); + return methodNames; + } } diff --git a/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java b/core-java/src/test/java/com/baeldung/java/regex/RegexUnitTest.java similarity index 99% rename from core-java/src/test/java/com/baeldung/java/regex/RegexTest.java rename to core-java/src/test/java/com/baeldung/java/regex/RegexUnitTest.java index 414401eb85..e4ea55aae3 100644 --- a/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java +++ b/core-java/src/test/java/com/baeldung/java/regex/RegexUnitTest.java @@ -7,7 +7,7 @@ import java.util.regex.Pattern; import org.junit.Test; -public class RegexTest { +public class RegexUnitTest { private static Pattern pattern; private static Matcher matcher; @@ -499,4 +499,3 @@ public class RegexTest { return matches; } } - diff --git a/core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java b/core-java/src/test/java/com/baeldung/printscreen/ScreenshotIntegrationTest.java similarity index 92% rename from core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java rename to core-java/src/test/java/com/baeldung/printscreen/ScreenshotIntegrationTest.java index 7e35fc3e30..13609b6977 100644 --- a/core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java +++ b/core-java/src/test/java/com/baeldung/printscreen/ScreenshotIntegrationTest.java @@ -7,8 +7,7 @@ import java.io.File; import static org.junit.Assert.assertTrue; - -public class ScreenshotTest { +public class ScreenshotIntegrationTest { private Screenshot screenshot = new Screenshot("Screenshot.jpg"); private File file = new File("Screenshot.jpg"); diff --git a/core-java/src/test/java/com/baeldung/socket/EchoMultiTest.java b/core-java/src/test/java/com/baeldung/socket/EchoMultiTest.java index fcf353281d..50af34d61a 100644 --- a/core-java/src/test/java/com/baeldung/socket/EchoMultiTest.java +++ b/core-java/src/test/java/com/baeldung/socket/EchoMultiTest.java @@ -17,43 +17,43 @@ public class EchoMultiTest { Thread.sleep(500); } - @Test - public void givenClient1_whenServerResponds_thenCorrect() { - EchoClient client = new EchoClient(); - client.startConnection("127.0.0.1", PORT); - String msg1 = client.sendMessage("hello"); - String msg2 = client.sendMessage("world"); - String terminate = client.sendMessage("."); + @Test + public void givenClient1_whenServerResponds_thenCorrect() { + EchoClient client = new EchoClient(); + client.startConnection("127.0.0.1", PORT); + String msg1 = client.sendMessage("hello"); + String msg2 = client.sendMessage("world"); + String terminate = client.sendMessage("."); - assertEquals(msg1, "hello"); - assertEquals(msg2, "world"); - assertEquals(terminate, "bye"); - client.stopConnection(); - } + assertEquals(msg1, "hello"); + assertEquals(msg2, "world"); + assertEquals(terminate, "bye"); + client.stopConnection(); + } - @Test - public void givenClient2_whenServerResponds_thenCorrect() { - EchoClient client = new EchoClient(); - client.startConnection("127.0.0.1", PORT); - String msg1 = client.sendMessage("hello"); - String msg2 = client.sendMessage("world"); - String terminate = client.sendMessage("."); - assertEquals(msg1, "hello"); - assertEquals(msg2, "world"); - assertEquals(terminate, "bye"); - client.stopConnection(); - } + @Test + public void givenClient2_whenServerResponds_thenCorrect() { + EchoClient client = new EchoClient(); + client.startConnection("127.0.0.1", PORT); + String msg1 = client.sendMessage("hello"); + String msg2 = client.sendMessage("world"); + String terminate = client.sendMessage("."); + assertEquals(msg1, "hello"); + assertEquals(msg2, "world"); + assertEquals(terminate, "bye"); + client.stopConnection(); + } - @Test - public void givenClient3_whenServerResponds_thenCorrect() { - EchoClient client = new EchoClient(); - client.startConnection("127.0.0.1", PORT); - String msg1 = client.sendMessage("hello"); - String msg2 = client.sendMessage("world"); - String terminate = client.sendMessage("."); - assertEquals(msg1, "hello"); - assertEquals(msg2, "world"); - assertEquals(terminate, "bye"); - client.stopConnection(); - } + @Test + public void givenClient3_whenServerResponds_thenCorrect() { + EchoClient client = new EchoClient(); + client.startConnection("127.0.0.1", PORT); + String msg1 = client.sendMessage("hello"); + String msg2 = client.sendMessage("world"); + String terminate = client.sendMessage("."); + assertEquals(msg1, "hello"); + assertEquals(msg2, "world"); + assertEquals(terminate, "bye"); + client.stopConnection(); + } } diff --git a/core-java/src/test/java/com/baeldung/socket/EchoTest.java b/core-java/src/test/java/com/baeldung/socket/EchoTest.java index cb09d42f79..6c93646ba6 100644 --- a/core-java/src/test/java/com/baeldung/socket/EchoTest.java +++ b/core-java/src/test/java/com/baeldung/socket/EchoTest.java @@ -18,28 +18,28 @@ public class EchoTest { Thread.sleep(500); } - private EchoClient client = new EchoClient(); + private EchoClient client = new EchoClient(); - @Before - public void init() { - client.startConnection("127.0.0.1", PORT); - } + @Before + public void init() { + client.startConnection("127.0.0.1", PORT); + } - @Test - public void givenClient_whenServerEchosMessage_thenCorrect() { + @Test + public void givenClient_whenServerEchosMessage_thenCorrect() { - String resp1 = client.sendMessage("hello"); - String resp2 = client.sendMessage("world"); - String resp3 = client.sendMessage("!"); - String resp4 = client.sendMessage("."); - assertEquals("hello", resp1); - assertEquals("world", resp2); - assertEquals("!", resp3); - assertEquals("good bye", resp4); - } + String resp1 = client.sendMessage("hello"); + String resp2 = client.sendMessage("world"); + String resp3 = client.sendMessage("!"); + String resp4 = client.sendMessage("."); + assertEquals("hello", resp1); + assertEquals("world", resp2); + assertEquals("!", resp3); + assertEquals("good bye", resp4); + } - @After - public void tearDown() { - client.stopConnection(); - } + @After + public void tearDown() { + client.stopConnection(); + } } diff --git a/core-java/src/test/java/com/baeldung/socket/GreetServerTest.java b/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java similarity index 90% rename from core-java/src/test/java/com/baeldung/socket/GreetServerTest.java rename to core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java index caf56a8c76..06b37d8539 100644 --- a/core-java/src/test/java/com/baeldung/socket/GreetServerTest.java +++ b/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java @@ -9,7 +9,7 @@ import java.util.concurrent.Executors; import static org.junit.Assert.assertEquals; -public class GreetServerTest { +public class GreetServerIntegrationTest { private GreetClient client; @@ -24,7 +24,7 @@ public class GreetServerTest { @Before public void init() { client = new GreetClient(); - client.startConnection("127.0.0.1", PORT); + client.startConnection("127.0.0.1", PORT); } diff --git a/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java b/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java index 23be2200d3..d701babc20 100644 --- a/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java +++ b/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java @@ -42,7 +42,7 @@ public class FileNotFoundExceptionTest { LOG.error("Optional file " + fileName + " was not found.", ex); } } - + private void readFailingFile() throws IOException { BufferedReader rd = new BufferedReader(new FileReader(new File(fileName))); rd.readLine(); diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java similarity index 94% rename from core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java rename to core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java index 16f25ae021..603b0bfbf9 100644 --- a/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java @@ -3,7 +3,7 @@ package org.baeldung.equalshashcode.entities; import org.junit.Assert; import org.junit.Test; -public class PrimitiveClassTest { +public class PrimitiveClassUnitTest { @Test public void testTwoEqualsObjects() { diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java similarity index 94% rename from core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java rename to core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java index 52d024a696..0943436883 100644 --- a/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java @@ -5,11 +5,10 @@ import java.awt.Color; import org.junit.Assert; import org.junit.Test; -public class SquareClassTest { +public class SquareClassUnitTest { @Test public void testEqualsAndHashcodes() { - Square aObject = new Square(10, Color.BLUE); Square bObject = new Square(10, Color.BLUE); diff --git a/core-java/src/test/java/org/baeldung/java/JavaIoIntegrationTest.java b/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java similarity index 98% rename from core-java/src/test/java/org/baeldung/java/JavaIoIntegrationTest.java rename to core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java index ff92410bc4..501f2ffca0 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaIoIntegrationTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java @@ -14,7 +14,7 @@ import org.slf4j.LoggerFactory; import com.google.common.base.Charsets; import com.google.common.io.Files; -public class JavaIoIntegrationTest { +public class JavaIoUnitTest { protected final Logger logger = LoggerFactory.getLogger(getClass()); // tests - iterate lines in a file diff --git a/core-java/src/test/java/org/baeldung/java/JavaTimerUnitTest.java b/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java similarity index 98% rename from core-java/src/test/java/org/baeldung/java/JavaTimerUnitTest.java rename to core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java index fcc74dbe64..da316aa885 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaTimerUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java @@ -9,7 +9,7 @@ import java.util.concurrent.TimeUnit; import org.junit.Test; -public class JavaTimerUnitTest { +public class JavaTimerLongRunningUnitTest { // tests diff --git a/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java b/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java index ad1f2dc70c..885c3bcd6c 100644 --- a/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java @@ -7,11 +7,11 @@ import org.junit.Test; public class ArraysJoinAndSplitJUnitTest { - private final String[] sauces = {"Marinara", "Olive Oil"}; - private final String[] cheeses = {"Mozzarella", "Feta", "Parmesan"}; - private final String[] vegetables = {"Olives", "Spinach", "Green Peppers"}; + private final String[] sauces = { "Marinara", "Olive Oil" }; + private final String[] cheeses = { "Mozzarella", "Feta", "Parmesan" }; + private final String[] vegetables = { "Olives", "Spinach", "Green Peppers" }; - private final String[] customers = {"Jay", "Harry", "Ronnie", "Gary", "Ross"}; + private final String[] customers = { "Jay", "Harry", "Ronnie", "Gary", "Ross" }; @Test public void givenThreeStringArrays_whenJoiningIntoOneStringArray_shouldSucceed() { @@ -25,12 +25,9 @@ public class ArraysJoinAndSplitJUnitTest { System.arraycopy(vegetables, 0, toppings, AddedSoFar, vegetables.length); - Assert.assertArrayEquals(toppings, - new String[]{"Marinara", "Olive Oil", "Mozzarella", "Feta", - "Parmesan", "Olives", "Spinach", "Green Peppers"}); + Assert.assertArrayEquals(toppings, new String[] { "Marinara", "Olive Oil", "Mozzarella", "Feta", "Parmesan", "Olives", "Spinach", "Green Peppers" }); } - @Test public void givenOneStringArray_whenSplittingInHalfTwoStringArrays_shouldSucceed() { int ordersHalved = (customers.length / 2) + (customers.length % 2); @@ -38,7 +35,7 @@ public class ArraysJoinAndSplitJUnitTest { String[] driverOne = Arrays.copyOf(customers, ordersHalved); String[] driverTwo = Arrays.copyOfRange(customers, ordersHalved, customers.length); - Assert.assertArrayEquals(driverOne, new String[]{"Jay", "Harry", "Ronnie"}); - Assert.assertArrayEquals(driverTwo, new String[]{"Gary", "Ross"}); + Assert.assertArrayEquals(driverOne, new String[] { "Jay", "Harry", "Ronnie" }); + Assert.assertArrayEquals(driverTwo, new String[] { "Gary", "Ross" }); } } diff --git a/core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java b/core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java index 30b0111555..6f291c535f 100644 --- a/core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java +++ b/core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java @@ -18,10 +18,7 @@ public class ArrayListTest { @Before public void setUp() { - List list = LongStream.range(0, 16) - .boxed() - .map(Long::toHexString) - .collect(toCollection(ArrayList::new)); + List list = LongStream.range(0, 16).boxed().map(Long::toHexString).collect(toCollection(ArrayList::new)); stringsToSearch = new ArrayList<>(list); stringsToSearch.addAll(list); } @@ -34,8 +31,7 @@ public class ArrayListTest { @Test public void givenCollection_whenProvideItToArrayListCtor_thenArrayListIsPopulatedWithItsElements() { - Collection numbers = - IntStream.range(0, 10).boxed().collect(toSet()); + Collection numbers = IntStream.range(0, 10).boxed().collect(toSet()); List list = new ArrayList<>(numbers); assertEquals(10, list.size()); @@ -56,8 +52,7 @@ public class ArrayListTest { @Test public void givenCollection_whenAddToArrayList_thenIsAdded() { List list = new ArrayList<>(Arrays.asList(1L, 2L, 3L)); - LongStream.range(4, 10).boxed() - .collect(collectingAndThen(toCollection(ArrayList::new), ys -> list.addAll(0, ys))); + LongStream.range(4, 10).boxed().collect(collectingAndThen(toCollection(ArrayList::new), ys -> list.addAll(0, ys))); assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(list)); } @@ -88,10 +83,7 @@ public class ArrayListTest { public void givenPredicate_whenIterateArrayList_thenFindAllElementsSatisfyingPredicate() { Set matchingStrings = new HashSet<>(Arrays.asList("a", "c", "9")); - List result = stringsToSearch - .stream() - .filter(matchingStrings::contains) - .collect(toCollection(ArrayList::new)); + List result = stringsToSearch.stream().filter(matchingStrings::contains).collect(toCollection(ArrayList::new)); assertEquals(6, result.size()); } @@ -131,8 +123,7 @@ public class ArrayListTest { @Test public void givenCondition_whenIterateArrayList_thenRemoveAllElementsSatisfyingCondition() { - Set matchingStrings - = Sets.newHashSet("a", "b", "c", "d", "e", "f"); + Set matchingStrings = Sets.newHashSet("a", "b", "c", "d", "e", "f"); Iterator it = stringsToSearch.iterator(); while (it.hasNext()) { diff --git a/core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java b/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java similarity index 60% rename from core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java rename to core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java index a6814ee600..cc042eeca9 100644 --- a/core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java +++ b/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java @@ -1,21 +1,21 @@ package org.baeldung.java.enums; - -import com.baeldung.enums.Pizza; -import org.junit.Test; +import static junit.framework.TestCase.assertTrue; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; -import static junit.framework.TestCase.assertTrue; +import org.junit.Test; +import com.baeldung.enums.Pizza; + +public class PizzaUnitTest { -public class PizzaTest { @Test public void givenPizaOrder_whenReady_thenDeliverable() { Pizza testPz = new Pizza(); - testPz.setStatus(Pizza.PizzaStatus.READY); + testPz.setStatus(Pizza.PizzaStatusEnum.READY); assertTrue(testPz.isDeliverable()); } @@ -23,16 +23,16 @@ public class PizzaTest { public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() { List pzList = new ArrayList<>(); Pizza pz1 = new Pizza(); - pz1.setStatus(Pizza.PizzaStatus.DELIVERED); + pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED); Pizza pz2 = new Pizza(); - pz2.setStatus(Pizza.PizzaStatus.ORDERED); + pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED); Pizza pz3 = new Pizza(); - pz3.setStatus(Pizza.PizzaStatus.ORDERED); + pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED); Pizza pz4 = new Pizza(); - pz4.setStatus(Pizza.PizzaStatus.READY); + pz4.setStatus(Pizza.PizzaStatusEnum.READY); pzList.add(pz1); pzList.add(pz2); @@ -48,33 +48,34 @@ public class PizzaTest { List pzList = new ArrayList<>(); Pizza pz1 = new Pizza(); - pz1.setStatus(Pizza.PizzaStatus.DELIVERED); + pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED); Pizza pz2 = new Pizza(); - pz2.setStatus(Pizza.PizzaStatus.ORDERED); + pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED); Pizza pz3 = new Pizza(); - pz3.setStatus(Pizza.PizzaStatus.ORDERED); + pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED); Pizza pz4 = new Pizza(); - pz4.setStatus(Pizza.PizzaStatus.READY); + pz4.setStatus(Pizza.PizzaStatusEnum.READY); pzList.add(pz1); pzList.add(pz2); pzList.add(pz3); pzList.add(pz4); - EnumMap> map = Pizza.groupPizzaByStatus(pzList); - assertTrue(map.get(Pizza.PizzaStatus.DELIVERED).size() == 1); - assertTrue(map.get(Pizza.PizzaStatus.ORDERED).size() == 2); - assertTrue(map.get(Pizza.PizzaStatus.READY).size() == 1); + EnumMap> map = Pizza.groupPizzaByStatus(pzList); + assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1); + assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2); + assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1); } @Test public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() { Pizza pz = new Pizza(); - pz.setStatus(Pizza.PizzaStatus.READY); + pz.setStatus(Pizza.PizzaStatusEnum.READY); pz.deliver(); - assertTrue(pz.getStatus() == Pizza.PizzaStatus.DELIVERED); + assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED); } + } diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java similarity index 99% rename from core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java rename to core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java index 24213ba869..f39ba80c08 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java @@ -13,7 +13,7 @@ import java.nio.file.Paths; import org.apache.commons.io.FileUtils; import org.junit.Test; -public class JavaFileIntegrationTest { +public class JavaFileUnitTest { // create a file diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java similarity index 98% rename from core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileTest.java rename to core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java index e679b82d3f..2aa3b366ba 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java @@ -23,7 +23,7 @@ import java.util.Scanner; import org.junit.Test; -public class JavaReadFromFileTest { +public class JavaReadFromFileUnitTest { @Test public void whenReadWithBufferedReader_thenCorrect() throws IOException { @@ -111,7 +111,7 @@ public class JavaReadFromFileTest { @Test public void whenReadUTFEncodedFile_thenCorrect() throws IOException { - final String expected_value = "青空"; + final String expected_value = "?空"; final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8")); final String currentLine = reader.readLine(); reader.close(); diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaScannerTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java similarity index 99% rename from core-java/src/test/java/org/baeldung/java/io/JavaScannerTest.java rename to core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java index 61f0f52316..5af286dbca 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaScannerTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java @@ -15,7 +15,7 @@ import java.util.Scanner; import org.junit.Test; -public class JavaScannerTest { +public class JavaScannerUnitTest { @Test public void whenReadFileWithScanner_thenCorrect() throws IOException { diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaWriteToFileTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaWriteToFileUnitTest.java similarity index 99% rename from core-java/src/test/java/org/baeldung/java/io/JavaWriteToFileTest.java rename to core-java/src/test/java/org/baeldung/java/io/JavaWriteToFileUnitTest.java index 93cfffa39d..9ff95c4e16 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaWriteToFileTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaWriteToFileUnitTest.java @@ -26,7 +26,7 @@ import java.nio.file.Paths; import org.junit.Test; -public class JavaWriteToFileTest { +public class JavaWriteToFileUnitTest { private String fileName = "src/test/resources/test_write.txt"; private String fileName1 = "src/test/resources/test_write_1.txt"; diff --git a/core-java/src/test/java/org/baeldung/java/lists/ListAssertJTest.java b/core-java/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java similarity index 83% rename from core-java/src/test/java/org/baeldung/java/lists/ListAssertJTest.java rename to core-java/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java index b8926946a9..c609f5badb 100644 --- a/core-java/src/test/java/org/baeldung/java/lists/ListAssertJTest.java +++ b/core-java/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java @@ -7,7 +7,7 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -public class ListAssertJTest { +public class ListAssertJUnitTest { private final List list1 = Arrays.asList("1", "2", "3", "4"); private final List list2 = Arrays.asList("1", "2", "3", "4"); @@ -15,9 +15,7 @@ public class ListAssertJTest { @Test public void whenTestingForEquality_ShouldBeEqual() throws Exception { - assertThat(list1) - .isEqualTo(list2) - .isNotEqualTo(list3); + assertThat(list1).isEqualTo(list2).isNotEqualTo(list3); assertThat(list1.equals(list2)).isTrue(); assertThat(list1.equals(list3)).isFalse(); diff --git a/core-java/src/test/java/org/baeldung/java/lists/ListTestNGTest.java b/core-java/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java similarity index 94% rename from core-java/src/test/java/org/baeldung/java/lists/ListTestNGTest.java rename to core-java/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java index fa80d0e224..b7c2bd7272 100644 --- a/core-java/src/test/java/org/baeldung/java/lists/ListTestNGTest.java +++ b/core-java/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java @@ -6,7 +6,7 @@ import org.testng.annotations.Test; import java.util.Arrays; import java.util.List; -public class ListTestNGTest { +public class ListTestNgUnitTest { private final List list1 = Arrays.asList("1", "2", "3", "4"); private final List list2 = Arrays.asList("1", "2", "3", "4"); diff --git a/core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java b/core-java/src/test/java/org/baeldung/java/md5/JavaMD5UnitTest.java similarity index 77% rename from core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java rename to core-java/src/test/java/org/baeldung/java/md5/JavaMD5UnitTest.java index 83f1fb33b6..55e71470c8 100644 --- a/core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java +++ b/core-java/src/test/java/org/baeldung/java/md5/JavaMD5UnitTest.java @@ -1,9 +1,10 @@ package org.baeldung.java.md5; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; +import java.io.File; +import java.io.IOException; import java.nio.file.Files; -import java.nio.file.Path; import java.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -11,80 +12,64 @@ import java.security.NoSuchAlgorithmException; import javax.xml.bind.DatatypeConverter; import org.apache.commons.codec.digest.DigestUtils; -import org.junit.Before; import org.junit.Test; import com.google.common.hash.HashCode; import com.google.common.hash.Hashing; -import java.io.File; -import java.io.IOException; -import java.nio.*; -import static org.assertj.core.api.Assertions.assertThat; +public class JavaMD5UnitTest { - -public class JavaMD5Test { - - String filename = "src/test/resources/test_md5.txt"; String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; - + String hash = "35454B055CC325EA1AF2126E27707052"; String password = "ILoveJava"; - - - + @Test public void givenPassword_whenHashing_thenVerifying() throws NoSuchAlgorithmException { String hash = "35454B055CC325EA1AF2126E27707052"; String password = "ILoveJava"; - + MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] digest = md.digest(); String myHash = DatatypeConverter.printHexBinary(digest).toUpperCase(); - + assertThat(myHash.equals(hash)).isTrue(); } - + @Test public void givenFile_generatingChecksum_thenVerifying() throws NoSuchAlgorithmException, IOException { String filename = "src/test/resources/test_md5.txt"; String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; - + MessageDigest md = MessageDigest.getInstance("MD5"); md.update(Files.readAllBytes(Paths.get(filename))); byte[] digest = md.digest(); - String myChecksum = DatatypeConverter - .printHexBinary(digest).toUpperCase(); - + String myChecksum = DatatypeConverter.printHexBinary(digest).toUpperCase(); + assertThat(myChecksum.equals(checksum)).isTrue(); } - + @Test - public void givenPassword_whenHashingUsingCommons_thenVerifying() { + public void givenPassword_whenHashingUsingCommons_thenVerifying() { String hash = "35454B055CC325EA1AF2126E27707052"; String password = "ILoveJava"; - String md5Hex = DigestUtils - .md5Hex(password).toUpperCase(); - + String md5Hex = DigestUtils.md5Hex(password).toUpperCase(); + assertThat(md5Hex.equals(hash)).isTrue(); } - - + @Test public void givenFile_whenChecksumUsingGuava_thenVerifying() throws IOException { String filename = "src/test/resources/test_md5.txt"; String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; - - HashCode hash = com.google.common.io.Files - .hash(new File(filename), Hashing.md5()); - String myChecksum = hash.toString() - .toUpperCase(); - + + HashCode hash = com.google.common.io.Files.hash(new File(filename), Hashing.md5()); + String myChecksum = hash.toString().toUpperCase(); + assertThat(myChecksum.equals(checksum)).isTrue(); } - } diff --git a/core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaTest.java b/core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaManualTest.java similarity index 98% rename from core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaTest.java rename to core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaManualTest.java index 5127ccb10c..bb849d6a13 100644 --- a/core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaTest.java +++ b/core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaManualTest.java @@ -6,7 +6,7 @@ import java.util.TimerTask; import org.junit.Test; -public class SandboxJavaTest { +public class SandboxJavaManualTest { @Test public void givenUsingTimer_whenSchedulingTimerTaskOnce_thenCorrect() throws InterruptedException { diff --git a/jpa-storedprocedure/pom.xml b/jpa-storedprocedure/pom.xml index b2ebaa32e2..b5a2e8693c 100644 --- a/jpa-storedprocedure/pom.xml +++ b/jpa-storedprocedure/pom.xml @@ -11,6 +11,7 @@ 7.0 5.1.0.Final 5.1.38 + 2.19.1 @@ -33,6 +34,16 @@ + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + + + diff --git a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureTest.java b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java similarity index 98% rename from jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureTest.java rename to jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java index 69351d9683..c93d59fe30 100644 --- a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureTest.java +++ b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java @@ -15,7 +15,7 @@ import org.junit.Test; import com.baeldung.jpa.model.Car; -public class StoredProcedureTest { +public class StoredProcedureIntegrationTest { private static EntityManagerFactory factory = null; private static EntityManager entityManager = null; diff --git a/play-framework/student-api/test/ApplicationTest.java b/play-framework/student-api/test/ApplicationTest.java new file mode 100644 index 0000000000..1133978e9a --- /dev/null +++ b/play-framework/student-api/test/ApplicationTest.java @@ -0,0 +1,172 @@ + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Arrays; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import model.Student; +import play.test.*; +import static play.test.Helpers.*; + +public class ApplicationTest{ + private static final String BASE_URL = "http://localhost:9000"; + + @Test +public void testInServer() throws Exception { + TestServer server = testServer(3333); + running(server, () -> { + try { + WSClient ws = play.libs.ws.WS.newClient(3333); + CompletionStage completionStage = ws.url("/").get(); + WSResponse response = completionStage.toCompletableFuture().get(); + ws.close(); + assertEquals(OK, response.getStatus()); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + }); +} + @Test + public void whenCreatesRecord_thenCorrect() { + Student student = new Student("jody", "west", 50); + JSONObject obj = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))); + assertTrue(obj.getBoolean("isSuccessfull")); + JSONObject body = obj.getJSONObject("body"); + assertEquals(student.getAge(), body.getInt("age")); + assertEquals(student.getFirstName(), body.getString("firstName")); + assertEquals(student.getLastName(), body.getString("lastName")); + } + + @Test + public void whenDeletesCreatedRecord_thenCorrect() { + Student student = new Student("Usain", "Bolt", 25); + JSONObject ob1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body"); + int id = ob1.getInt("id"); + JSONObject obj1 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject())); + assertTrue(obj1.getBoolean("isSuccessfull")); + makeRequest(BASE_URL + "/" + id, "DELETE", null); + JSONObject obj2 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject())); + assertFalse(obj2.getBoolean("isSuccessfull")); + } + + @Test + public void whenUpdatesCreatedRecord_thenCorrect() { + Student student = new Student("john", "doe", 50); + JSONObject body1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body"); + assertEquals(student.getAge(), body1.getInt("age")); + int newAge = 60; + body1.put("age", newAge); + JSONObject body2 = new JSONObject(makeRequest(BASE_URL, "PUT", body1)).getJSONObject("body"); + assertFalse(student.getAge() == body2.getInt("age")); + assertTrue(newAge == body2.getInt("age")); + } + + @Test + public void whenGetsAllRecords_thenCorrect() { + Student student1 = new Student("jane", "daisy", 50); + Student student2 = new Student("john", "daniel", 60); + Student student3 = new Student("don", "mason", 55); + Student student4 = new Student("scarlet", "ohara", 90); + + makeRequest(BASE_URL, "POST", new JSONObject(student1)); + makeRequest(BASE_URL, "POST", new JSONObject(student2)); + makeRequest(BASE_URL, "POST", new JSONObject(student3)); + makeRequest(BASE_URL, "POST", new JSONObject(student4)); + + JSONObject objects = new JSONObject(makeRequest(BASE_URL, "GET", null)); + assertTrue(objects.getBoolean("isSuccessfull")); + JSONArray array = objects.getJSONArray("body"); + assertTrue(array.length() >= 4); + } + + public static String makeRequest(String myUrl, String httpMethod, JSONObject parameters) { + + URL url = null; + try { + url = new URL(myUrl); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + HttpURLConnection conn = null; + try { + + conn = (HttpURLConnection) url.openConnection(); + } catch (IOException e) { + e.printStackTrace(); + } + conn.setDoInput(true); + + conn.setReadTimeout(10000); + + conn.setRequestProperty("Content-Type", "application/json"); + DataOutputStream dos = null; + int respCode = 0; + String inputString = null; + try { + conn.setRequestMethod(httpMethod); + + if (Arrays.asList("POST", "PUT").contains(httpMethod)) { + String params = parameters.toString(); + + conn.setDoOutput(true); + + dos = new DataOutputStream(conn.getOutputStream()); + dos.writeBytes(params); + dos.flush(); + dos.close(); + } + respCode = conn.getResponseCode(); + if (respCode != 200 && respCode != 201) { + String error = inputStreamToString(conn.getErrorStream()); + return error; + } + inputString = inputStreamToString(conn.getInputStream()); + + } catch (IOException e) { + + e.printStackTrace(); + } + return inputString; + } + + public static String inputStreamToString(InputStream is) { + BufferedReader br = null; + StringBuilder sb = new StringBuilder(); + + String line; + try { + + br = new BufferedReader(new InputStreamReader(is)); + while ((line = br.readLine()) != null) { + sb.append(line); + } + + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + return sb.toString(); + + } +} diff --git a/pom.xml b/pom.xml index 1b9aa81da1..89b377a214 100644 --- a/pom.xml +++ b/pom.xml @@ -58,7 +58,7 @@ mockito mocks - mutation-testing + testing orika diff --git a/resteasy/pom.xml b/resteasy/pom.xml index ec9e87b0d1..04e8576e1f 100644 --- a/resteasy/pom.xml +++ b/resteasy/pom.xml @@ -10,6 +10,8 @@ 3.0.14.Final + 2.19.1 + 1.6.0 @@ -23,6 +25,35 @@ 1.8 + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + 8082 + + + + @@ -73,5 +104,66 @@ + + + live + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + + + **/*LiveTest.java + + + + + + + json + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + false + + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + + + + \ No newline at end of file diff --git a/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java b/resteasy/src/test/java/com/baeldung/server/RestEasyClientLiveTest.java similarity index 61% rename from resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java rename to resteasy/src/test/java/com/baeldung/server/RestEasyClientLiveTest.java index ef18b0f23f..7e709edb96 100644 --- a/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java +++ b/resteasy/src/test/java/com/baeldung/server/RestEasyClientLiveTest.java @@ -1,7 +1,15 @@ package com.baeldung.server; -import com.baeldung.client.ServicesInterface; -import com.baeldung.model.Movie; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.List; +import java.util.Locale; + +import javax.naming.NamingException; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; + import org.apache.commons.io.IOUtils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; @@ -14,18 +22,13 @@ import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine; import org.junit.Before; import org.junit.Test; -import javax.naming.NamingException; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; -import java.util.List; -import java.util.Locale; -public class RestEasyClientTest { +import com.baeldung.client.ServicesInterface; +import com.baeldung.model.Movie; - public static final UriBuilder FULL_PATH = UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest"); +public class RestEasyClientLiveTest { + + public static final UriBuilder FULL_PATH = UriBuilder.fromPath("http://127.0.0.1:8082/RestEasyTutorial/rest"); Movie transformerMovie = null; Movie batmanMovie = null; ObjectMapper jsonMapper = null; @@ -35,22 +38,22 @@ public class RestEasyClientTest { jsonMapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); + final SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); jsonMapper.setDateFormat(sdf); - try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/transformer.json")) { - String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + try (InputStream inputStream = new RestEasyClientLiveTest().getClass().getResourceAsStream("./movies/transformer.json")) { + final String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class); - } catch (Exception e) { + } catch (final Exception e) { e.printStackTrace(); throw new RuntimeException("Test is going to die ...", e); } - try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/batman.json")) { - String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + try (InputStream inputStream = new RestEasyClientLiveTest().getClass().getResourceAsStream("./movies/batman.json")) { + final String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException("Test is going to die ...", e); } } @@ -58,41 +61,41 @@ public class RestEasyClientTest { @Test public void testListAllMovies() { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface proxy = target.proxy(ServicesInterface.class); + final ResteasyClient client = new ResteasyClientBuilder().build(); + final ResteasyWebTarget target = client.target(FULL_PATH); + final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(transformerMovie); moviesResponse.close(); moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); - List movies = proxy.listMovies(); + final List movies = proxy.listMovies(); System.out.println(movies); } @Test public void testMovieByImdbId() { - String transformerImdbId = "tt0418279"; + final String transformerImdbId = "tt0418279"; - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface proxy = target.proxy(ServicesInterface.class); + final ResteasyClient client = new ResteasyClientBuilder().build(); + final ResteasyWebTarget target = client.target(FULL_PATH); + final ServicesInterface proxy = target.proxy(ServicesInterface.class); - Response moviesResponse = proxy.addMovie(transformerMovie); + final Response moviesResponse = proxy.addMovie(transformerMovie); moviesResponse.close(); - Movie movies = proxy.movieByImdbId(transformerImdbId); + final Movie movies = proxy.movieByImdbId(transformerImdbId); System.out.println(movies); } @Test public void testAddMovie() { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface proxy = target.proxy(ServicesInterface.class); + final ResteasyClient client = new ResteasyClientBuilder().build(); + final ResteasyWebTarget target = client.target(FULL_PATH); + final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); @@ -109,17 +112,15 @@ public class RestEasyClientTest { @Test public void testAddMovieMultiConnection() { - PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); - CloseableHttpClient httpClient = HttpClients.custom() - .setConnectionManager(cm) - .build(); - ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient); - ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); - ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface proxy = target.proxy(ServicesInterface.class); + final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); + final CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build(); + final ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient); + final ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); + final ResteasyWebTarget target = client.target(FULL_PATH); + final ServicesInterface proxy = target.proxy(ServicesInterface.class); - Response batmanResponse = proxy.addMovie(batmanMovie); - Response transformerResponse = proxy.addMovie(transformerMovie); + final Response batmanResponse = proxy.addMovie(batmanMovie); + final Response transformerResponse = proxy.addMovie(transformerMovie); if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus()); @@ -132,16 +133,14 @@ public class RestEasyClientTest { transformerResponse.close(); cm.close(); - - } @Test public void testDeleteMovie() { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface proxy = target.proxy(ServicesInterface.class); + final ResteasyClient client = new ResteasyClientBuilder().build(); + final ResteasyWebTarget target = client.target(FULL_PATH); + final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); @@ -159,9 +158,9 @@ public class RestEasyClientTest { @Test public void testUpdateMovie() { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface proxy = target.proxy(ServicesInterface.class); + final ResteasyClient client = new ResteasyClientBuilder().build(); + final ResteasyWebTarget target = client.target(FULL_PATH); + final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java index 0ce8c0300b..fda7b01c7a 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java @@ -1,9 +1,9 @@ package org.baeldung.persistence; -import org.baeldung.persistence.query.JPACriteriaQueryTest; -import org.baeldung.persistence.query.JPAQuerydslTest; -import org.baeldung.persistence.query.JPASpecificationTest; -import org.baeldung.persistence.query.RsqlTest; +import org.baeldung.persistence.query.JPACriteriaQueryIntegrationTest; +import org.baeldung.persistence.query.JPAQuerydslIntegrationTest; +import org.baeldung.persistence.query.JPASpecificationIntegrationTest; +import org.baeldung.persistence.query.RsqlIntegrationTest; import org.baeldung.persistence.service.FooServicePersistenceIntegrationTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; @@ -11,11 +11,11 @@ import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ // @formatter:off - RsqlTest.class - ,JPASpecificationTest.class + RsqlIntegrationTest.class + ,JPASpecificationIntegrationTest.class ,FooServicePersistenceIntegrationTest.class - ,JPAQuerydslTest.class - ,JPACriteriaQueryTest.class + ,JPAQuerydslIntegrationTest.class + ,JPACriteriaQueryIntegrationTest.class }) // public class PersistenceTestSuite { diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryIntegrationTest.java similarity index 98% rename from spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryIntegrationTest.java index 1d0826e6ba..e8e98074c6 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryIntegrationTest.java @@ -24,7 +24,7 @@ import org.springframework.transaction.annotation.Transactional; @ContextConfiguration(classes = { PersistenceConfig.class }) @Transactional @Rollback -public class JPACriteriaQueryTest { +public class JPACriteriaQueryIntegrationTest { @Autowired private IUserDAO userApi; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslIntegrationTest.java similarity index 98% rename from spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslIntegrationTest.java index d5fbc819fd..d397c3aac4 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslIntegrationTest.java @@ -23,7 +23,7 @@ import org.springframework.transaction.annotation.Transactional; @ContextConfiguration(classes = { PersistenceConfig.class }) @Transactional @Rollback -public class JPAQuerydslTest { +public class JPAQuerydslIntegrationTest { @Autowired private MyUserRepository repo; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationIntegrationTest.java similarity index 99% rename from spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationIntegrationTest.java index 0d8773dd61..8bd4857e85 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationIntegrationTest.java @@ -26,7 +26,7 @@ import org.springframework.transaction.annotation.Transactional; @ContextConfiguration(classes = { PersistenceConfig.class }) @Transactional @Rollback -public class JPASpecificationTest { +public class JPASpecificationIntegrationTest { @Autowired private UserRepository repository; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlIntegrationTest.java similarity index 99% rename from spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlIntegrationTest.java index e0deb8d4ec..16dfa8a12f 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlIntegrationTest.java @@ -27,7 +27,7 @@ import cz.jirutka.rsql.parser.ast.Node; @ContextConfiguration(classes = { PersistenceConfig.class }) @Transactional @Rollback -public class RsqlTest { +public class RsqlIntegrationTest { @Autowired private UserRepository repository; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java similarity index 97% rename from spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java index 930ab20262..99b391eda1 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java @@ -23,7 +23,7 @@ import org.springframework.web.context.WebApplicationContext; @WebAppConfiguration @Transactional @ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) -public class LoggerInterceptorTest { +public class LoggerInterceptorIntegrationTest { @Autowired WebApplicationContext wac; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java similarity index 97% rename from spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java index 916a849c63..662fc997f9 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java @@ -28,7 +28,7 @@ import org.springframework.web.context.WebApplicationContext; @Transactional @ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) @WithMockUser(username = "admin", roles = { "USER", "ADMIN" }) -public class SessionTimerInterceptorTest { +public class SessionTimerInterceptorIntegrationTest { @Autowired WebApplicationContext wac; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java similarity index 97% rename from spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java index ff40c86906..0e8f7c98ed 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java @@ -25,7 +25,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @Transactional @ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) @WithMockUser(username = "admin", roles = { "USER", "ADMIN" }) -public class UserInterceptorTest { +public class UserInterceptorIntegrationTest { @Autowired WebApplicationContext wac; diff --git a/mutation-testing/README.md b/testing/README.md similarity index 100% rename from mutation-testing/README.md rename to testing/README.md diff --git a/mutation-testing/pom.xml b/testing/pom.xml similarity index 97% rename from mutation-testing/pom.xml rename to testing/pom.xml index cdee59fcb4..aa523d95ef 100644 --- a/mutation-testing/pom.xml +++ b/testing/pom.xml @@ -1,77 +1,77 @@ - - 4.0.0 - com.baeldung - mutation-testing - 0.1-SNAPSHOT - mutation-testing - - - org.pitest - pitest-parent - 1.1.10 - pom - - - junit - junit - 4.9 - - - - - - org.pitest - pitest-maven - 1.1.10 - - - com.baeldung.testing.mutation.* - - - com.baeldung.mutation.test.* - - - - - org.jacoco - jacoco-maven-plugin - 0.7.7.201606060606 - - - - prepare-agent - - - - report - prepare-package - - report - - - - jacoco-check - - check - - - - - PACKAGE - - - LINE - COVEREDRATIO - 0.50 - - - - - - - - - - - + + 4.0.0 + com.baeldung + mutation-testing + 0.1-SNAPSHOT + mutation-testing + + + org.pitest + pitest-parent + 1.1.10 + pom + + + junit + junit + 4.9 + + + + + + org.pitest + pitest-maven + 1.1.10 + + + com.baeldung.testing.mutation.* + + + com.baeldung.mutation.test.* + + + + + org.jacoco + jacoco-maven-plugin + 0.7.7.201606060606 + + + + prepare-agent + + + + report + prepare-package + + report + + + + jacoco-check + + check + + + + + PACKAGE + + + LINE + COVEREDRATIO + 0.50 + + + + + + + + + + + diff --git a/mutation-testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java b/testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java similarity index 97% rename from mutation-testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java rename to testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java index 0b166f1557..e264a4c759 100644 --- a/mutation-testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java +++ b/testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java @@ -1,15 +1,15 @@ -package com.baeldung.testing.mutation; - -public class Palindrome { - - public boolean isPalindrome(String inputString) { - if (inputString.length() == 0) { - return true; - } else { - char firstChar = inputString.charAt(0); - char lastChar = inputString.charAt(inputString.length() - 1); - String mid = inputString.substring(1, inputString.length() - 1); - return (firstChar == lastChar) && isPalindrome(mid); - } - } -} +package com.baeldung.testing.mutation; + +public class Palindrome { + + public boolean isPalindrome(String inputString) { + if (inputString.length() == 0) { + return true; + } else { + char firstChar = inputString.charAt(0); + char lastChar = inputString.charAt(inputString.length() - 1); + String mid = inputString.substring(1, inputString.length() - 1); + return (firstChar == lastChar) && isPalindrome(mid); + } + } +} diff --git a/mutation-testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java b/testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java similarity index 96% rename from mutation-testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java rename to testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java index 3add6290f6..11ed966b16 100644 --- a/mutation-testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java +++ b/testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java @@ -1,34 +1,34 @@ -package com.baeldung.mutation.test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -import com.baeldung.testing.mutation.Palindrome; - -public class TestPalindrome { - @Test - public void whenEmptyString_thanAccept() { - Palindrome palindromeTester = new Palindrome(); - assertTrue(palindromeTester.isPalindrome("noon")); - } - - @Test - public void whenPalindrom_thanAccept() { - Palindrome palindromeTester = new Palindrome(); - assertTrue(palindromeTester.isPalindrome("noon")); - } - - @Test - public void whenNotPalindrom_thanReject(){ - Palindrome palindromeTester = new Palindrome(); - assertFalse(palindromeTester.isPalindrome("box")); - } - - @Test - public void whenNearPalindrom_thanReject(){ - Palindrome palindromeTester = new Palindrome(); - assertFalse(palindromeTester.isPalindrome("neon")); - } -} +package com.baeldung.mutation.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.baeldung.testing.mutation.Palindrome; + +public class TestPalindrome { + @Test + public void whenEmptyString_thanAccept() { + Palindrome palindromeTester = new Palindrome(); + assertTrue(palindromeTester.isPalindrome("noon")); + } + + @Test + public void whenPalindrom_thanAccept() { + Palindrome palindromeTester = new Palindrome(); + assertTrue(palindromeTester.isPalindrome("noon")); + } + + @Test + public void whenNotPalindrom_thanReject(){ + Palindrome palindromeTester = new Palindrome(); + assertFalse(palindromeTester.isPalindrome("box")); + } + + @Test + public void whenNearPalindrom_thanReject(){ + Palindrome palindromeTester = new Palindrome(); + assertFalse(palindromeTester.isPalindrome("neon")); + } +}