[BAEL-11401] - Moved articles out of core-java (part 2)
This commit is contained in:
@@ -1,112 +0,0 @@
|
||||
package com.baeldung.encoderdecoder;
|
||||
|
||||
import static java.util.stream.Collectors.joining;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URL;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.util.UriUtils;
|
||||
|
||||
public class EncoderDecoderUnitTest {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(EncoderDecoderUnitTest.class);
|
||||
private static final String testUrl = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253";
|
||||
private static final String testUrlWithPath = "http://www.baeldung.com/path+1?key1=value+1&key2=value%40%21%242&key3=value%253";
|
||||
|
||||
private String encodeValue(String value) {
|
||||
String encoded = null;
|
||||
try {
|
||||
encoded = URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
LOGGER.error("Error encoding parameter {}", e.getMessage(), e);
|
||||
}
|
||||
return encoded;
|
||||
}
|
||||
|
||||
private String decode(String value) {
|
||||
String decoded = null;
|
||||
try {
|
||||
decoded = URLDecoder.decode(value, StandardCharsets.UTF_8.toString());
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
LOGGER.error("Error encoding parameter {}", e.getMessage(), e);
|
||||
}
|
||||
return decoded;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenURL_whenAnalyze_thenCorrect() throws Exception {
|
||||
URL url = new URL(testUrl);
|
||||
|
||||
Assert.assertThat(url.getProtocol(), is("http"));
|
||||
Assert.assertThat(url.getHost(), is("www.baeldung.com"));
|
||||
Assert.assertThat(url.getQuery(), is("key1=value+1&key2=value%40%21%242&key3=value%253"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRequestParam_whenUTF8Scheme_thenEncode() throws Exception {
|
||||
Map<String, String> requestParams = new HashMap<>();
|
||||
requestParams.put("key1", "value 1");
|
||||
requestParams.put("key2", "value@!$2");
|
||||
requestParams.put("key3", "value%3");
|
||||
|
||||
String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com?", ""));
|
||||
|
||||
Assert.assertThat(testUrl, is(encodedURL));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRequestParam_whenUTF8Scheme_thenDecodeRequestParams() throws Exception {
|
||||
URL url = new URL(testUrl);
|
||||
|
||||
String query = url.getQuery();
|
||||
|
||||
String decodedQuery = Arrays.stream(query.split("&")).map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1])).collect(joining("&"));
|
||||
|
||||
Assert.assertEquals("http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery);
|
||||
}
|
||||
|
||||
private String encodePath(String path) {
|
||||
try {
|
||||
path = UriUtils.encodePath(path, "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
LOGGER.error("Error encoding parameter {}", e.getMessage(), e);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathSegment_thenEncodeDecode() throws UnsupportedEncodingException {
|
||||
String pathSegment = "/Path 1/Path+2";
|
||||
String encodedPathSegment = encodePath(pathSegment);
|
||||
String decodedPathSegment = UriUtils.decode(encodedPathSegment, "UTF-8");
|
||||
Assert.assertEquals("/Path%201/Path+2", encodedPathSegment);
|
||||
Assert.assertEquals("/Path 1/Path+2", decodedPathSegment);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathAndRequestParam_whenUTF8Scheme_thenEncode() throws Exception {
|
||||
Map<String, String> requestParams = new HashMap<>();
|
||||
requestParams.put("key1", "value 1");
|
||||
requestParams.put("key2", "value@!$2");
|
||||
requestParams.put("key3", "value%3");
|
||||
|
||||
String path = "path+1";
|
||||
|
||||
String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com/" + encodePath(path) + "?", ""));
|
||||
|
||||
Assert.assertThat(testUrlWithPath, is(encodedURL));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,188 +0,0 @@
|
||||
package com.baeldung.http;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
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;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class HttpRequestLiveTest {
|
||||
|
||||
@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;
|
||||
StringBuilder content = new StringBuilder();
|
||||
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;
|
||||
StringBuilder content = new StringBuilder();
|
||||
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);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFailedRequest_thenOk() throws IOException {
|
||||
URL url = new URL("http://example.com");
|
||||
HttpURLConnection con = (HttpURLConnection) url.openConnection();
|
||||
con.setRequestMethod("POST");
|
||||
|
||||
con.setConnectTimeout(5000);
|
||||
con.setReadTimeout(5000);
|
||||
|
||||
int status = con.getResponseCode();
|
||||
|
||||
Reader streamReader = null;
|
||||
|
||||
if (status > 299) {
|
||||
streamReader = new InputStreamReader(con.getErrorStream());
|
||||
} else {
|
||||
streamReader = new InputStreamReader(con.getInputStream());
|
||||
}
|
||||
|
||||
BufferedReader in = new BufferedReader(streamReader);
|
||||
String inputLine;
|
||||
StringBuilder content = new StringBuilder();
|
||||
while ((inputLine = in.readLine()) != null) {
|
||||
content.append(inputLine);
|
||||
}
|
||||
in.close();
|
||||
|
||||
con.disconnect();
|
||||
|
||||
assertEquals("status code incorrect", status, 411);
|
||||
assertTrue("error content", content.toString()
|
||||
.contains("411 - Length Required"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequestFullResponse_thenOk() throws IOException {
|
||||
URL url = new URL("http://example.com");
|
||||
HttpURLConnection con = (HttpURLConnection) url.openConnection();
|
||||
con.setRequestMethod("GET");
|
||||
|
||||
con.setConnectTimeout(5000);
|
||||
con.setReadTimeout(5000);
|
||||
|
||||
String fullResponse = FullResponseBuilder.getFullResponse(con);
|
||||
|
||||
con.disconnect();
|
||||
|
||||
assertEquals("status code incorrect", con.getResponseCode(), 200);
|
||||
assertTrue("header incorrect", fullResponse.contains("Content-Type: text/html; charset=UTF-8"));
|
||||
assertTrue("response incorrect", fullResponse.contains("<!doctype html><html><head>"));
|
||||
}
|
||||
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
package com.baeldung.memoryleaks.equalshashcode;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class PersonMemoryLeakUnitTest {
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenMap_whenEqualsAndHashCodeNotOverridden_thenMemoryLeak() {
|
||||
Map<Person, Integer> map = new HashMap<Person, Integer>();
|
||||
for(int i=0; i<10000000; i++) {
|
||||
map.put(new Person("jon"), 1);
|
||||
}
|
||||
assertTrue(map.size() > 1);
|
||||
System.out.print("Debug Point - VisuaLVM");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenMap_whenEqualsAndHashCodeOverridden_thenNoMemoryLeak() {
|
||||
Map<PersonOptimized, Integer> map = new HashMap<PersonOptimized, Integer>();
|
||||
for(int i=0; i<10000; i++) {
|
||||
map.put(new PersonOptimized("jon"), 1);
|
||||
}
|
||||
assertTrue(map.size() == 1);
|
||||
System.out.print("Debug Point - VisuaLVM");
|
||||
}
|
||||
}
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
package com.baeldung.memoryleaks.finalize;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FinalizeMemoryLeakUnitTest {
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenObjectWithFinalizer_whenCreatingAndDestroyingThisObject_thenMemoryLeak() {
|
||||
BulkyObject[] stock = new BulkyObject[100000];
|
||||
|
||||
for(int i=0; i<100000; i++) {
|
||||
stock[i] = new BulkyObject();
|
||||
}
|
||||
System.out.print("Debug Point - VisuaLVM");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenObjectWithoutFinalizer_whenCreatingAndDestroyingThisObject_thenNoMemoryLeak() {
|
||||
BulkyObjectOptimized[] stock = new BulkyObjectOptimized[100000];
|
||||
|
||||
for(int i=0; i<100000; i++) {
|
||||
stock[i] = new BulkyObjectOptimized();
|
||||
}
|
||||
System.out.print("Debug Point - VisuaLVM");
|
||||
}
|
||||
}
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.memoryleaks.innerclass;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StaticInnerClassMemoryLeakUnitTest {
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenUsingInnerClass_whenInitializingInnerClass_thenInnerClassHoldsReferenceOfOuterObject() {
|
||||
InnerClassWrapper.SimpleInnerClass simpleInnerClassObj = new InnerClassWrapper().new SimpleInnerClass();
|
||||
System.out.print("Debug Point - VisuaLVM");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenUsingStaticNestedClass_whenInitializingInnerClass_thenStaticNestedClassDoesntReferenceOuterObject() {
|
||||
StaticNestedClassWrapper.StaticNestedClass staticNestedClassObj = new StaticNestedClassWrapper.StaticNestedClass();
|
||||
System.out.print("Debug Point - VisuaLVM");
|
||||
}
|
||||
}
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.memoryleaks.internedstrings;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringInternMemoryLeakUnitTest {
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenJava6OrBelow_whenInterningLargeStrings_thenPermgenIncreases() {
|
||||
new InternedString().readString();
|
||||
System.out.print("Debug Point - VisuaLVM");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenJava6OrBelow_whenNotInterningLargeStrings_thenPermgenDoesntIncrease() {
|
||||
new StringObject().readString();
|
||||
System.out.print("Debug Point - VisuaLVM");
|
||||
}
|
||||
}
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
package com.baeldung.memoryleaks.staticfields;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NonStaticFieldsMemoryLeakUnitTest {
|
||||
public List<Double> list = new ArrayList<>();
|
||||
|
||||
public void populateList() {
|
||||
for (int i = 0; i < 10000000; i++) {
|
||||
list.add(Math.random());
|
||||
}
|
||||
System.out.println("Debug Point 2");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenNonStaticLargeList_whenPopulatingList_thenListGarbageCollected() {
|
||||
System.out.println("Debug Point 1");
|
||||
new NonStaticFieldsMemoryLeakUnitTest().populateList();
|
||||
System.out.println("Debug Point 3");
|
||||
}
|
||||
}
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
package com.baeldung.memoryleaks.staticfields;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StaticFieldsMemoryLeakUnitTest {
|
||||
public static List<Double> list = new ArrayList<>();
|
||||
|
||||
public void populateList() {
|
||||
for (int i = 0; i < 10000000; i++) {
|
||||
list.add(Math.random());
|
||||
}
|
||||
System.out.println("Debug Point 2");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenStaticLargeList_whenPopulatingList_thenListIsNotGarbageCollected() {
|
||||
System.out.println("Debug Point 1");
|
||||
new StaticFieldsDemo().populateList();
|
||||
System.out.println("Debug Point 3");
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package com.baeldung.socket;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class EchoIntegrationTest {
|
||||
private static int port;
|
||||
|
||||
@BeforeClass
|
||||
public static void start() throws InterruptedException, IOException {
|
||||
|
||||
// Take an available port
|
||||
ServerSocket s = new ServerSocket(0);
|
||||
port = s.getLocalPort();
|
||||
s.close();
|
||||
|
||||
Executors.newSingleThreadExecutor()
|
||||
.submit(() -> new EchoServer().start(port));
|
||||
Thread.sleep(500);
|
||||
}
|
||||
|
||||
private EchoClient client = new EchoClient();
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
client.startConnection("127.0.0.1", port);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
client.stopConnection();
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.baeldung.socket;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GreetServerIntegrationTest {
|
||||
|
||||
private GreetClient client;
|
||||
|
||||
private static int port;
|
||||
|
||||
@BeforeClass
|
||||
public static void start() throws InterruptedException, IOException {
|
||||
|
||||
// Take an available port
|
||||
ServerSocket s = new ServerSocket(0);
|
||||
port = s.getLocalPort();
|
||||
s.close();
|
||||
|
||||
Executors.newSingleThreadExecutor()
|
||||
.submit(() -> new GreetServer().start(port));
|
||||
Thread.sleep(500);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
client = new GreetClient();
|
||||
client.startConnection("127.0.0.1", port);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGreetingClient_whenServerRespondsWhenStarted_thenCorrect() {
|
||||
String response = client.sendMessage("hello server");
|
||||
assertEquals("hello client", response);
|
||||
}
|
||||
|
||||
@After
|
||||
public void finish() {
|
||||
client.stopConnection();
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
package com.baeldung.socket;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class SocketEchoMultiIntegrationTest {
|
||||
|
||||
private static int port;
|
||||
|
||||
@BeforeClass
|
||||
public static void start() throws InterruptedException, IOException {
|
||||
|
||||
// Take an available port
|
||||
ServerSocket s = new ServerSocket(0);
|
||||
port = s.getLocalPort();
|
||||
s.close();
|
||||
|
||||
Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(port));
|
||||
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(".");
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package com.baeldung.unsafe;
|
||||
|
||||
import sun.misc.Unsafe;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
class CASCounter {
|
||||
private final Unsafe unsafe;
|
||||
private volatile long counter = 0;
|
||||
private long offset;
|
||||
|
||||
private Unsafe getUnsafe() throws IllegalAccessException, NoSuchFieldException {
|
||||
Field f = Unsafe.class.getDeclaredField("theUnsafe");
|
||||
f.setAccessible(true);
|
||||
return (Unsafe) f.get(null);
|
||||
}
|
||||
|
||||
public CASCounter() throws Exception {
|
||||
unsafe = getUnsafe();
|
||||
offset = unsafe.objectFieldOffset(CASCounter.class.getDeclaredField("counter"));
|
||||
}
|
||||
|
||||
public void increment() {
|
||||
long before = counter;
|
||||
while (!unsafe.compareAndSwapLong(this, offset, before, before + 1)) {
|
||||
before = counter;
|
||||
}
|
||||
}
|
||||
|
||||
public long getCounter() {
|
||||
return counter;
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package com.baeldung.unsafe;
|
||||
|
||||
import sun.misc.Unsafe;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
class OffHeapArray {
|
||||
private final static int BYTE = 1;
|
||||
private long size;
|
||||
private long address;
|
||||
|
||||
private Unsafe getUnsafe() throws IllegalAccessException, NoSuchFieldException {
|
||||
Field f = Unsafe.class.getDeclaredField("theUnsafe");
|
||||
f.setAccessible(true);
|
||||
return (Unsafe) f.get(null);
|
||||
}
|
||||
|
||||
OffHeapArray(long size) throws NoSuchFieldException, IllegalAccessException {
|
||||
this.size = size;
|
||||
address = getUnsafe().allocateMemory(size * BYTE);
|
||||
}
|
||||
|
||||
public void set(long i, byte value) throws NoSuchFieldException, IllegalAccessException {
|
||||
getUnsafe().putByte(address + i * BYTE, value);
|
||||
}
|
||||
|
||||
public int get(long idx) throws NoSuchFieldException, IllegalAccessException {
|
||||
return getUnsafe().getByte(address + idx * BYTE);
|
||||
}
|
||||
|
||||
public long size() {
|
||||
return size;
|
||||
}
|
||||
|
||||
void freeMemory() throws NoSuchFieldException, IllegalAccessException {
|
||||
getUnsafe().freeMemory(address);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
package com.baeldung.unsafe;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import sun.misc.Unsafe;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static junit.framework.Assert.assertTrue;
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class UnsafeUnitTest {
|
||||
|
||||
private Unsafe unsafe;
|
||||
|
||||
@Before
|
||||
public void setup() throws NoSuchFieldException, IllegalAccessException {
|
||||
Field f = Unsafe.class.getDeclaredField("theUnsafe");
|
||||
f.setAccessible(true);
|
||||
unsafe = (Unsafe) f.get(null);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenClass_whenInitializeIt_thenShouldHaveDifferentStateWhenUseUnsafe() throws IllegalAccessException, InstantiationException {
|
||||
//when
|
||||
InitializationOrdering o1 = new InitializationOrdering();
|
||||
assertEquals(o1.getA(), 1);
|
||||
|
||||
//when
|
||||
InitializationOrdering o3 = (InitializationOrdering) unsafe.allocateInstance(InitializationOrdering.class);
|
||||
assertEquals(o3.getA(), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrivateMethod_whenUsingUnsafe_thenCanModifyPrivateField() throws NoSuchFieldException {
|
||||
//given
|
||||
SecretHolder secretHolder = new SecretHolder();
|
||||
|
||||
//when
|
||||
Field f = secretHolder.getClass().getDeclaredField("SECRET_VALUE");
|
||||
unsafe.putInt(secretHolder, unsafe.objectFieldOffset(f), 1);
|
||||
|
||||
//then
|
||||
assertTrue(secretHolder.secretIsDisclosed());
|
||||
}
|
||||
|
||||
@Test(expected = IOException.class)
|
||||
public void givenUnsafeThrowException_whenThrowCheckedException_thenNotNeedToCatchIt() {
|
||||
unsafe.throwException(new IOException());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore // Uncomment for local
|
||||
public void givenArrayBiggerThatMaxInt_whenAllocateItOffHeapMemory_thenSuccess() throws NoSuchFieldException, IllegalAccessException {
|
||||
//given
|
||||
long SUPER_SIZE = (long) Integer.MAX_VALUE * 2;
|
||||
OffHeapArray array = new OffHeapArray(SUPER_SIZE);
|
||||
|
||||
//when
|
||||
int sum = 0;
|
||||
for (int i = 0; i < 100; i++) {
|
||||
array.set((long) Integer.MAX_VALUE + i, (byte) 3);
|
||||
sum += array.get((long) Integer.MAX_VALUE + i);
|
||||
}
|
||||
|
||||
long arraySize = array.size();
|
||||
|
||||
array.freeMemory();
|
||||
|
||||
//then
|
||||
assertEquals(arraySize, SUPER_SIZE);
|
||||
assertEquals(sum, 300);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsafeCompareAndSwap_whenUseIt_thenCounterYildCorrectLockFreeResults() throws Exception {
|
||||
//given
|
||||
int NUM_OF_THREADS = 1_000;
|
||||
int NUM_OF_INCREMENTS = 10_000;
|
||||
ExecutorService service = Executors.newFixedThreadPool(NUM_OF_THREADS);
|
||||
CASCounter casCounter = new CASCounter();
|
||||
|
||||
//when
|
||||
IntStream.rangeClosed(0, NUM_OF_THREADS - 1)
|
||||
.forEach(i -> service.submit(() -> IntStream
|
||||
.rangeClosed(0, NUM_OF_INCREMENTS - 1)
|
||||
.forEach(j -> casCounter.increment())));
|
||||
|
||||
service.shutdown();
|
||||
service.awaitTermination(1, TimeUnit.MINUTES);
|
||||
|
||||
//then
|
||||
assertEquals(NUM_OF_INCREMENTS * NUM_OF_THREADS, casCounter.getCounter());
|
||||
|
||||
}
|
||||
|
||||
class InitializationOrdering {
|
||||
private long a;
|
||||
|
||||
public InitializationOrdering() {
|
||||
this.a = 1;
|
||||
}
|
||||
|
||||
public long getA() {
|
||||
return this.a;
|
||||
}
|
||||
}
|
||||
|
||||
class SecretHolder {
|
||||
private int SECRET_VALUE = 0;
|
||||
|
||||
public boolean secretIsDisclosed() {
|
||||
return SECRET_VALUE == 1;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user