diff --git a/core-java/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java b/core-java/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java index 9eef00bd3f24..3aca6b01470a 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java +++ b/core-java/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java @@ -4,17 +4,10 @@ import java.util.Comparator; import java.util.concurrent.ConcurrentNavigableMap; import java.util.concurrent.ConcurrentSkipListMap; -import java.util.function.ToLongFunction; public class EventWindowSort { - private final ConcurrentSkipListMap events = new ConcurrentSkipListMap<>(Comparator.comparingLong(new ToLongFunction() { - @Override - public long applyAsLong(ZonedDateTime value) { - return value - .toInstant() - .toEpochMilli(); - } - })); + private final ConcurrentSkipListMap events + = new ConcurrentSkipListMap<>(Comparator.comparingLong(value -> value.toInstant().toEpochMilli())); public void acceptEvent(Event event) { events.put(event.getEventTime(), event.getContent()); @@ -22,14 +15,14 @@ public void acceptEvent(Event event) { public ConcurrentNavigableMap getEventsFromLastMinute() { return events.tailMap(ZonedDateTime - .now() - .minusMinutes(1)); + .now() + .minusMinutes(1)); } public ConcurrentNavigableMap getEventsOlderThatOneMinute() { return events.headMap(ZonedDateTime - .now() - .minusMinutes(1)); + .now() + .minusMinutes(1)); } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadA.java b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadA.java new file mode 100644 index 000000000000..b19bc3fe1ac8 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadA.java @@ -0,0 +1,21 @@ +package com.baeldung.concurrent.sleepwait; + +/*** + * Example of waking up a waiting thread + */ +public class ThreadA { + private static final ThreadB b = new ThreadB(); + + public static void main(String... args) throws InterruptedException { + b.start(); + + synchronized (b) { + while (b.sum == 0) { + System.out.println("Waiting for ThreadB to complete..."); + b.wait(); + } + + System.out.println("ThreadB has completed. Sum from that thread is: " + b.sum); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadB.java b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadB.java new file mode 100644 index 000000000000..1fc180a5de72 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadB.java @@ -0,0 +1,20 @@ +package com.baeldung.concurrent.sleepwait; + +/*** + * Example of waking up a waiting thread + */ +class ThreadB extends Thread { + int sum; + + @Override + public void run() { + synchronized (this) { + int i = 0; + while (i < 100000) { + sum += i; + i++; + } + notify(); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java new file mode 100644 index 000000000000..e84fe29d8734 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java @@ -0,0 +1,23 @@ +package com.baeldung.concurrent.sleepwait; + +/*** + * Example of wait() and sleep() methods + */ +public class WaitSleepExample { + private static final Object LOCK = new Object(); + + public static void main(String... args) throws InterruptedException { + sleepWaitInSyncronizedBlocks(); + } + + private static void sleepWaitInSyncronizedBlocks() throws InterruptedException { + Thread.sleep(1000); // called on the thread + System.out.println("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second"); + + synchronized (LOCK) { + LOCK.wait(1000); // called on the object, synchronization required + System.out.println("Object '" + LOCK + "' is woken after waiting for 1 second"); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/http/ParameterStringBuilder.java b/core-java/src/main/java/com/baeldung/http/ParameterStringBuilder.java new file mode 100644 index 000000000000..bed4195faa7e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/http/ParameterStringBuilder.java @@ -0,0 +1,21 @@ +package com.baeldung.http; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.Map; + +public class ParameterStringBuilder { + public static String getParamsString(Map params) throws UnsupportedEncodingException { + StringBuilder result = new StringBuilder(); + + for (Map.Entry entry : params.entrySet()) { + result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); + result.append("="); + result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); + result.append("&"); + } + + String resultString = result.toString(); + return resultString.length() > 0 ? resultString.substring(0, resultString.length() - 1) : resultString; + } +} diff --git a/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorUnitTest.java b/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java similarity index 91% rename from core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorUnitTest.java rename to core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java index 69c802feb8b1..bc63fbe6f730 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorUnitTest.java +++ b/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java @@ -1,22 +1,17 @@ package com.baeldung.concurrent.future; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.concurrent.CancellationException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; -public class SquareCalculatorUnitTest { +import java.util.concurrent.*; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class SquareCalculatorIntegrationTest { @Rule public TestName name = new TestName(); diff --git a/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java b/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java similarity index 96% rename from core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java rename to core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java index 02727264653a..2a8eda896b31 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java +++ b/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java @@ -9,7 +9,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.util.Lists.newArrayList; -public class PriorityBlockingQueueUnitTest { +public class PriorityBlockingQueueIntegrationTest { @Test public void givenUnorderedValues_whenPolling_thenShouldOrderQueue() throws InterruptedException { diff --git a/core-java/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetTest.java b/core-java/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetTest.java rename to core-java/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java index a2dbbae5200d..92fff8446b60 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetTest.java +++ b/core-java/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java @@ -13,7 +13,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -public class ConcurrentSkipListSetTest { +public class ConcurrentSkipListSetIntegrationTest { @Test public void givenThreadsProducingEvents_whenGetForEventsFromLastMinute_thenReturnThoseEventsInTheLockFreeWay() throws InterruptedException { diff --git a/core-java/src/test/java/com/baeldung/http/HttpRequestTest.java b/core-java/src/test/java/com/baeldung/http/HttpRequestTest.java new file mode 100644 index 000000000000..f238f7df7c0f --- /dev/null +++ b/core-java/src/test/java/com/baeldung/http/HttpRequestTest.java @@ -0,0 +1,126 @@ +package com.baeldung.http; + +import org.apache.commons.lang.StringUtils; +import org.junit.Test; +import static org.junit.Assert.*; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.CookieManager; +import java.net.HttpCookie; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +public class HttpRequestTest { + + @Test + public void whenGetRequest_thenOk() throws IOException { + URL url = new URL("http://example.com"); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + + Map parameters = new HashMap<>(); + parameters.put("param1", "val"); + con.setDoOutput(true); + DataOutputStream out = new DataOutputStream(con.getOutputStream()); + out.writeBytes(ParameterStringBuilder.getParamsString(parameters)); + out.flush(); + out.close(); + + con.setConnectTimeout(5000); + con.setReadTimeout(5000); + + int status = con.getResponseCode(); + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + StringBuffer content = new StringBuffer(); + while ((inputLine = in.readLine()) != null) { + content.append(inputLine); + } + in.close(); + + assertEquals("status code incorrect", status, 200); + assertTrue("content incorrect", content.toString().contains("Example Domain")); + } + + @Test + public void whenPostRequest_thenOk() throws IOException { + URL url = new URL("http://example.com"); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("POST"); + con.setRequestProperty("Content-Type", "application/json"); + + Map parameters = new HashMap<>(); + parameters.put("param1", "val"); + con.setDoOutput(true); + DataOutputStream out = new DataOutputStream(con.getOutputStream()); + out.writeBytes(ParameterStringBuilder.getParamsString(parameters)); + out.flush(); + out.close(); + + int status = con.getResponseCode(); + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + StringBuffer content = new StringBuffer(); + while ((inputLine = in.readLine()) != null) { + content.append(inputLine); + } + in.close(); + + assertEquals("status code incorrect", status, 200); + } + + @Test + public void whenGetCookies_thenOk() throws IOException { + URL url = new URL("http://example.com"); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + + CookieManager cookieManager = new CookieManager(); + String cookiesHeader = con.getHeaderField("Set-Cookie"); + Optional usernameCookie = null; + if (cookiesHeader != null) { + List cookies = HttpCookie.parse(cookiesHeader); + cookies.forEach(cookie -> cookieManager.getCookieStore().add(null, cookie)); + usernameCookie = cookies.stream().findAny().filter(cookie -> cookie.getName().equals("username")); + } + + if (usernameCookie == null) { + cookieManager.getCookieStore().add(null, new HttpCookie("username", "john")); + } + + con.disconnect(); + + con = (HttpURLConnection) url.openConnection(); + con.setRequestProperty("Cookie", StringUtils.join(cookieManager.getCookieStore().getCookies(), ";")); + + int status = con.getResponseCode(); + + assertEquals("status code incorrect", status, 200); + } + + @Test + public void whenRedirect_thenOk() throws IOException { + URL url = new URL("http://example.com"); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + + con.setInstanceFollowRedirects(true); + int status = con.getResponseCode(); + + if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM) { + String location = con.getHeaderField("Location"); + URL newUrl = new URL(location); + con = (HttpURLConnection) newUrl.openConnection(); + } + + assertEquals("status code incorrect", con.getResponseCode(), 200); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/set/SetTest.java b/core-java/src/test/java/com/baeldung/java/set/SetTest.java index 59e135283f00..32a5c7e07ee9 100644 --- a/core-java/src/test/java/com/baeldung/java/set/SetTest.java +++ b/core-java/src/test/java/com/baeldung/java/set/SetTest.java @@ -1,15 +1,11 @@ package com.baeldung.java.set; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.Test; -import java.util.ConcurrentModificationException; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; -import java.util.TreeSet; +import java.util.*; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class SetTest { @@ -44,22 +40,22 @@ public void givenHashSet_whenAddNullObject_thenOK() { @Test public void givenHashSetAndTreeSet_whenAddObjects_thenHashSetIsFaster() { - Set set = new HashSet<>(); - long startTime = System.nanoTime(); - set.add("Baeldung"); - set.add("is"); - set.add("Awesome"); - long endTime = System.nanoTime(); - long duration1 = (endTime - startTime); - Set set2 = new TreeSet<>(); - startTime = System.nanoTime(); - set2.add("Baeldung"); - set2.add("is"); - set2.add("Awesome"); - endTime = System.nanoTime(); - long duration2 = (endTime - startTime); - assertTrue(duration1 < duration2); + long hashSetInsertionTime = measureExecution(() -> { + Set set = new HashSet<>(); + set.add("Baeldung"); + set.add("is"); + set.add("Awesome"); + }); + + long TreeSetInsertionTime = measureExecution(() -> { + Set set = new TreeSet<>(); + set.add("Baeldung"); + set.add("is"); + set.add("Awesome"); + }); + + assertTrue(hashSetInsertionTime < TreeSetInsertionTime); } @Test @@ -86,4 +82,13 @@ public void givenHashSet_whenModifyWhenIterator_thenFailFast() { it.next(); } } + + private static long measureExecution(Runnable task) { + long startTime = System.nanoTime(); + task.run(); + long endTime = System.nanoTime(); + long executionTime = endTime - startTime; + System.out.println(executionTime); + return executionTime; + } } diff --git a/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferTest.java b/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferTest.java new file mode 100644 index 000000000000..4064d38267a9 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferTest.java @@ -0,0 +1,68 @@ +package com.baeldung.mappedbytebuffer; + +import org.junit.Test; + +import java.nio.CharBuffer; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.EnumSet; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class MappedByteBufferTest { + + + @Test + public void givenFileChannel_whenReadToTheMappedByteBuffer_thenShouldSuccess() throws Exception { + //given + CharBuffer charBuffer = null; + Path pathToRead = getFileURIFromResources("fileToRead.txt"); + + //when + try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToRead, EnumSet.of(StandardOpenOption.READ))) { + MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size()); + + if (mappedByteBuffer != null) { + charBuffer = Charset.forName("UTF-8").decode(mappedByteBuffer); + } + } + + //then + assertNotNull(charBuffer); + assertEquals(charBuffer.toString(), "This is a content of the file"); + } + + @Test + public void givenPath_whenWriteToItUsingMappedByteBuffer_thenShouldSuccessfullyWrite() throws Exception { + //given + CharBuffer charBuffer = CharBuffer.wrap("This will be written to the file"); + Path pathToWrite = getFileURIFromResources("fileToWriteTo.txt"); + + //when + try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite, + EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) { + MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, charBuffer.length()); + + if (mappedByteBuffer != null) { + mappedByteBuffer.put(Charset.forName("utf-8").encode(charBuffer)); + } + } + + //then + List fileContent = Files.readAllLines(pathToWrite); + assertEquals(fileContent.get(0), "This will be written to the file"); + + } + + public Path getFileURIFromResources(String fileName) throws Exception { + ClassLoader classLoader = getClass().getClassLoader(); + return Paths.get(classLoader.getResource(fileName).getPath()); + } +} diff --git a/core-java/src/test/java/com/baeldung/threadlocal/ThreadLocalTest.java b/core-java/src/test/java/com/baeldung/threadlocal/ThreadLocalIntegrationTest.java similarity index 96% rename from core-java/src/test/java/com/baeldung/threadlocal/ThreadLocalTest.java rename to core-java/src/test/java/com/baeldung/threadlocal/ThreadLocalIntegrationTest.java index ac2e8fbe63c3..cc4b4f021a7d 100644 --- a/core-java/src/test/java/com/baeldung/threadlocal/ThreadLocalTest.java +++ b/core-java/src/test/java/com/baeldung/threadlocal/ThreadLocalIntegrationTest.java @@ -7,7 +7,7 @@ import static org.junit.Assert.assertEquals; -public class ThreadLocalTest { +public class ThreadLocalIntegrationTest { @Test public void givenThreadThatStoresContextInAMap_whenStartThread_thenShouldSetContextForBothUsers() throws ExecutionException, InterruptedException { //when diff --git a/core-java/src/test/java/com/baeldung/transferqueue/TransferQueueTest.java b/core-java/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/transferqueue/TransferQueueTest.java rename to core-java/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java index 1af9821ed093..e49738e98352 100644 --- a/core-java/src/test/java/com/baeldung/transferqueue/TransferQueueTest.java +++ b/core-java/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java @@ -9,7 +9,7 @@ import static junit.framework.TestCase.assertEquals; @FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class TransferQueueTest { +public class TransferQueueIntegrationTest { @Test public void whenMultipleConsumersAndProducers_thenProcessAllMessages() throws InterruptedException { diff --git a/core-java/src/test/resources/fileToRead.txt b/core-java/src/test/resources/fileToRead.txt new file mode 100644 index 000000000000..45d73fa10d31 --- /dev/null +++ b/core-java/src/test/resources/fileToRead.txt @@ -0,0 +1 @@ +This is a content of the file \ No newline at end of file diff --git a/core-java/src/test/resources/fileToWriteTo.txt b/core-java/src/test/resources/fileToWriteTo.txt new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/disruptor/src/test/java/com/baeldung/disruptor/DisruptorTest.java b/disruptor/src/test/java/com/baeldung/disruptor/DisruptorIntegrationTest.java similarity index 95% rename from disruptor/src/test/java/com/baeldung/disruptor/DisruptorTest.java rename to disruptor/src/test/java/com/baeldung/disruptor/DisruptorIntegrationTest.java index 28a5ff72ce8d..10929f21b02b 100644 --- a/disruptor/src/test/java/com/baeldung/disruptor/DisruptorTest.java +++ b/disruptor/src/test/java/com/baeldung/disruptor/DisruptorIntegrationTest.java @@ -1,16 +1,17 @@ package com.baeldung.disruptor; -import java.util.concurrent.ThreadFactory; -import org.junit.Before; -import org.junit.Test; import com.lmax.disruptor.BusySpinWaitStrategy; import com.lmax.disruptor.RingBuffer; import com.lmax.disruptor.WaitStrategy; import com.lmax.disruptor.dsl.Disruptor; import com.lmax.disruptor.dsl.ProducerType; import com.lmax.disruptor.util.DaemonThreadFactory; +import org.junit.Before; +import org.junit.Test; + +import java.util.concurrent.ThreadFactory; -public class DisruptorTest { +public class DisruptorIntegrationTest { private Disruptor disruptor; private WaitStrategy waitStrategy; @@ -21,7 +22,7 @@ public void setUp() throws Exception { private void createDisruptor(final ProducerType producerType, final EventConsumer eventConsumer) { final ThreadFactory threadFactory = DaemonThreadFactory.INSTANCE; - disruptor = new Disruptor(ValueEvent.EVENT_FACTORY, 16, threadFactory, producerType, waitStrategy); + disruptor = new Disruptor<>(ValueEvent.EVENT_FACTORY, 16, threadFactory, producerType, waitStrategy); disruptor.handleEventsWith(eventConsumer.getEventHandler()); } diff --git a/libraries/src/main/java/com/baeldung/http/HttpRequestBuilder.java b/libraries/src/main/java/com/baeldung/http/HttpRequestBuilder.java deleted file mode 100644 index bfa7cc121b66..000000000000 --- a/libraries/src/main/java/com/baeldung/http/HttpRequestBuilder.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.http; - -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Map; - -import org.apache.log4j.Logger; - -public class HttpRequestBuilder { - - private static final Logger LOG = Logger.getLogger(HttpRequestBuilder.class); - - public HttpResponseWrapper sendRequest(String urlString, String method, Map parameters, Map properties) throws IOException{ - URL url = new URL(urlString); - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - con.setRequestMethod(method); - if (properties != null) { - properties.forEach((key, value) -> con.setRequestProperty(key, value)); - } - if (parameters != null) { - con.setDoOutput(true); - DataOutputStream out = new DataOutputStream(con.getOutputStream()); - out.writeBytes(ParameterStringBuilder.getParamsString(parameters)); - out.flush(); - out.close(); - } - - int status = con.getResponseCode(); - - BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); - String inputLine; - StringBuffer content = new StringBuffer(); - while ((inputLine = in.readLine()) != null) { - content.append(inputLine); - } - in.close(); - - HttpResponseWrapper responseWrapper = new HttpResponseWrapper(); - responseWrapper.setStatus(status); - responseWrapper.setContent(content.toString()); - - return responseWrapper; - } - -} diff --git a/libraries/src/main/java/com/baeldung/http/HttpResponseWrapper.java b/libraries/src/main/java/com/baeldung/http/HttpResponseWrapper.java deleted file mode 100644 index c0f68ac18b1e..000000000000 --- a/libraries/src/main/java/com/baeldung/http/HttpResponseWrapper.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.http; - -public class HttpResponseWrapper { - private int status; - private String content; - - public HttpResponseWrapper(){ } - - public HttpResponseWrapper(int status, String content) { - super(); - this.status = status; - this.content = content; - } - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } - -} diff --git a/libraries/src/main/java/com/baeldung/http/ParameterStringBuilder.java b/libraries/src/main/java/com/baeldung/http/ParameterStringBuilder.java deleted file mode 100644 index b148ddb3fd20..000000000000 --- a/libraries/src/main/java/com/baeldung/http/ParameterStringBuilder.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.http; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.Map; - -public class ParameterStringBuilder { - public static String getParamsString(Map params) { - StringBuilder result = new StringBuilder(); - - params.forEach((key, value) -> { - try { - result.append(URLEncoder.encode(key, "UTF-8")); - result.append("="); - result.append(URLEncoder.encode(value, "UTF-8")); - result.append("&"); - } catch (UnsupportedEncodingException exc) { - } - }); - - String resultString = result.toString(); - if (resultString.length() > 0) { - resultString = resultString.substring(0, resultString.length() - 1); - } - return resultString; - } -} diff --git a/libraries/src/main/java/com/baeldung/httpclient/HttpClientRequestBuilder.java b/libraries/src/main/java/com/baeldung/httpclient/HttpClientRequestBuilder.java deleted file mode 100644 index b2f6c36a4f2e..000000000000 --- a/libraries/src/main/java/com/baeldung/httpclient/HttpClientRequestBuilder.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.baeldung.httpclient; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.HttpClient; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.message.BasicNameValuePair; - -import com.baeldung.http.HttpResponseWrapper; -import com.baeldung.http.ParameterStringBuilder; - -public class HttpClientRequestBuilder { - - public HttpResponseWrapper sendGetRequest(String url, Map parameters) { - HttpClient client = HttpClientBuilder.create() - .build(); - if (parameters != null) { - url += "?" + ParameterStringBuilder.getParamsString(parameters); - } - HttpGet request = new HttpGet(url); - try { - HttpResponse response = client.execute(request); - - HttpResponseWrapper responseWrapper = new HttpResponseWrapper(); - responseWrapper.setStatus(response.getStatusLine() - .getStatusCode()); - BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity() - .getContent())); - - String line = "", content = ""; - while ((line = in.readLine()) != null) { - content += line; - } - responseWrapper.setContent(content); - return responseWrapper; - } catch (ClientProtocolException e) { - e.printStackTrace(); - return null; - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } - - public HttpResponseWrapper sendPostRequestWithParameters(String url, Map parameters) { - HttpClient client = HttpClientBuilder.create() - .build(); - HttpPost request = new HttpPost(url); - - try { - if (parameters != null) { - List nameValuePairs = new ArrayList<>(); - parameters.forEach((key, value) -> nameValuePairs.add(new BasicNameValuePair(key, value))); - request.setEntity(new UrlEncodedFormEntity(nameValuePairs)); - } - - HttpResponse response = client.execute(request); - - HttpResponseWrapper responseWrapper = new HttpResponseWrapper(); - responseWrapper.setStatus(response.getStatusLine() - .getStatusCode()); - BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity() - .getContent())); - - String line = "", content = ""; - while ((line = in.readLine()) != null) { - content += line; - } - responseWrapper.setContent(content); - return responseWrapper; - } catch (ClientProtocolException e) { - e.printStackTrace(); - return null; - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } - - public HttpResponseWrapper sendPostRequestWithJson(String url, String json) { - HttpClient client = HttpClientBuilder.create() - .build(); - HttpPost request = new HttpPost(url); - - try { - request.addHeader("Content-Type", "application/json"); - request.setEntity(new StringEntity(json)); - - HttpResponse response = client.execute(request); - - HttpResponseWrapper responseWrapper = new HttpResponseWrapper(); - responseWrapper.setStatus(response.getStatusLine() - .getStatusCode()); - BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity() - .getContent())); - - String line = "", content = ""; - while ((line = in.readLine()) != null) { - content += line; - } - responseWrapper.setContent(content); - return responseWrapper; - } catch (ClientProtocolException e) { - e.printStackTrace(); - return null; - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } - -} diff --git a/libraries/src/test/java/com/baeldung/http/HttpRequestBuilderTest.java b/libraries/src/test/java/com/baeldung/http/HttpRequestBuilderTest.java deleted file mode 100644 index 7f5992fbd9d0..000000000000 --- a/libraries/src/test/java/com/baeldung/http/HttpRequestBuilderTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.http; - -import org.junit.Test; -import static org.junit.Assert.*; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; - -import java.io.IOException; - -public class HttpRequestBuilderTest { - - private HttpRequestBuilder requestPerformer; - - @Before - public void setup() { - requestPerformer = new HttpRequestBuilder(); - } - - @Test - public void whenGetRequest_thenOk() throws IOException { - HttpResponseWrapper response = requestPerformer.sendRequest("http://www.example.com", "GET", null, null); - assertEquals("status code incorrect", response.getStatus(), 200); - assertTrue("content incorrect", response.getContent() - .contains("Example Domain")); - } - - @Test - public void whenPostRequest_thenOk() throws IOException { - Map parameters = new HashMap<>(); - parameters.put("param1", "val"); - Map properties = new HashMap<>(); - properties.put("Content-Type", "application/json"); - HttpResponseWrapper response = requestPerformer.sendRequest("http://www.example.com", "POST", parameters, properties); - assertEquals("status code incorrect", response.getStatus(), 200); - } - -} diff --git a/libraries/src/test/java/com/baeldung/httpclient/HttpClientRequestBuilderTest.java b/libraries/src/test/java/com/baeldung/httpclient/HttpClientRequestBuilderTest.java deleted file mode 100644 index 886d2649a38f..000000000000 --- a/libraries/src/test/java/com/baeldung/httpclient/HttpClientRequestBuilderTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.httpclient; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.http.HttpResponseWrapper; - -public class HttpClientRequestBuilderTest { - private HttpClientRequestBuilder requestBuilder; - - @Before - public void setup() { - requestBuilder = new HttpClientRequestBuilder(); - } - - @Test - public void whenGetRequest_thenOk() { - Map parameters = new HashMap<>(); - parameters.put("param1", "val"); - HttpResponseWrapper response = requestBuilder.sendGetRequest("http://www.example.com",parameters); - assertEquals("status code incorrect", response.getStatus(), 200); - assertTrue("content incorrect", response.getContent() - .contains("Example Domain")); - } - - @Test - public void whenPostRequestWithParameters_thenOk() { - Map parameters = new HashMap<>(); - parameters.put("param1", "val"); - HttpResponseWrapper response = requestBuilder.sendPostRequestWithParameters("http://www.example.com", parameters); - assertEquals("status code incorrect", response.getStatus(), 200); - } - - @Test - public void whenPostRequestWithJson_thenOk() { - String json = "{\"id\":\"1\"}"; - HttpResponseWrapper response = requestBuilder.sendPostRequestWithJson("http://www.example.com",json); - assertEquals("status code incorrect", response.getStatus(), 200); - } -} diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBTest.java b/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java similarity index 93% rename from spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBTest.java rename to spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java index 2c40c5b117fe..1fcc4be45dca 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBTest.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java @@ -1,7 +1,8 @@ package org.baeldung.persistence.repository; -import javax.annotation.Resource; - +import org.baeldung.config.StudentJpaConfig; +import org.baeldung.persistence.dao.StudentRepository; +import org.baeldung.persistence.model.Student; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; @@ -9,16 +10,14 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.transaction.annotation.Transactional; -import org.baeldung.config.StudentJpaConfig; -import org.baeldung.persistence.model.Student; -import org.baeldung.persistence.dao.StudentRepository; +import javax.annotation.Resource; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { StudentJpaConfig.class }, loader = AnnotationConfigContextLoader.class) @Transactional -public class InMemoryDBTest { +public class InMemoryDBIntegrationTest { @Resource private StudentRepository studentRepository; diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerTest.java b/spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java similarity index 98% rename from spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerTest.java rename to spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java index a1f9e71bec27..1dae55937123 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java @@ -26,7 +26,7 @@ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = WebConfig.class) @WebAppConfiguration -public class HeavyResourceControllerTest { +public class HeavyResourceControllerIntegrationTest { private MockMvc mockMvc; diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeControllerTest.java b/spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java similarity index 96% rename from spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeControllerTest.java rename to spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java index a38177f78bdc..9ef2dfa215ef 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeControllerTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java @@ -18,7 +18,7 @@ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = WebConfig.class) @WebAppConfiguration -public class CustomMediaTypeControllerTest { +public class CustomMediaTypeControllerIntegrationTest { private MockMvc mockMvc; diff --git a/spring-rest/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleControllerTest.java b/spring-rest/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleControllerIntegrationTest.java similarity index 88% rename from spring-rest/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleControllerTest.java rename to spring-rest/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleControllerIntegrationTest.java index f2f00a40d88a..7bd16a3e9743 100644 --- a/spring-rest/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleControllerTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleControllerIntegrationTest.java @@ -1,15 +1,6 @@ package org.baeldung.web.test; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import org.baeldung.config.WebConfig; import org.junit.Before; import org.junit.Test; @@ -22,11 +13,17 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = WebConfig.class) @WebAppConfiguration -public class BazzNewMappingsExampleControllerTest { +public class BazzNewMappingsExampleControllerIntegrationTest { private MockMvc mockMvc; diff --git a/spring-session/pom.xml b/spring-session/pom.xml index 2c8b15a6eba7..79095cbfbbb0 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -59,7 +59,7 @@ maven-surefire-plugin - **/*ControllerTest.java + **/*IntegrationTest.java diff --git a/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerTest.java b/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java similarity index 97% rename from spring-session/src/test/java/com/baeldung/spring/session/SessionControllerTest.java rename to spring-session/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java index c8138889b238..84dd2bc1390f 100644 --- a/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerTest.java +++ b/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java @@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -public class SessionControllerTest { +public class SessionControllerIntegrationTest { private Jedis jedis; private TestRestTemplate testRestTemplate;