Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,25 @@
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<ZonedDateTime, String> events = new ConcurrentSkipListMap<>(Comparator.comparingLong(new ToLongFunction<ZonedDateTime>() {
@Override
public long applyAsLong(ZonedDateTime value) {
return value
.toInstant()
.toEpochMilli();
}
}));
private final ConcurrentSkipListMap<ZonedDateTime, String> events
= new ConcurrentSkipListMap<>(Comparator.comparingLong(value -> value.toInstant().toEpochMilli()));

public void acceptEvent(Event event) {
events.put(event.getEventTime(), event.getContent());
}

public ConcurrentNavigableMap<ZonedDateTime, String> getEventsFromLastMinute() {
return events.tailMap(ZonedDateTime
.now()
.minusMinutes(1));
.now()
.minusMinutes(1));
}

public ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
return events.headMap(ZonedDateTime
.now()
.minusMinutes(1));
.now()
.minusMinutes(1));
}

}
Expand Down
Original file line number Diff line number Diff line change
@@ -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);
}
}
}
Original file line number Diff line number Diff line change
@@ -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();
}
}
}
Original file line number Diff line number Diff line change
@@ -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");
}
}

}
Original file line number Diff line number Diff line change
@@ -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<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();

for (Map.Entry<String, String> 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;
}
}
Original file line number Diff line number Diff line change
@@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
126 changes: 126 additions & 0 deletions core-java/src/test/java/com/baeldung/http/HttpRequestTest.java
Original file line number Diff line number Diff line change
@@ -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<String, String> 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<String, String> 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<HttpCookie> usernameCookie = null;
if (cookiesHeader != null) {
List<HttpCookie> 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);
}

}
51 changes: 28 additions & 23 deletions core-java/src/test/java/com/baeldung/java/set/SetTest.java
Original file line number Diff line number Diff line change
@@ -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 {

Expand Down Expand Up @@ -44,22 +40,22 @@ public void givenHashSet_whenAddNullObject_thenOK() {

@Test
public void givenHashSetAndTreeSet_whenAddObjects_thenHashSetIsFaster() {
Set<String> 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<String> 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<String> set = new HashSet<>();
set.add("Baeldung");
set.add("is");
set.add("Awesome");
});

long TreeSetInsertionTime = measureExecution(() -> {
Set<String> set = new TreeSet<>();
set.add("Baeldung");
set.add("is");
set.add("Awesome");
});

assertTrue(hashSetInsertionTime < TreeSetInsertionTime);
}

@Test
Expand All @@ -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;
}
}
Loading