[BAEL-11401] - Moved articles out of core-java (part 2)

This commit is contained in:
amit2103
2018-12-29 21:54:59 +05:30
parent 8b65216ba3
commit c61ac5101e
45 changed files with 40 additions and 9 deletions

View File

@@ -6,19 +6,14 @@
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java)
- [MD5 Hashing in Java](http://www.baeldung.com/java-md5)
- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets)
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)
- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java)
- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
- [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java)
- [URL Encoding and Decoding in Java](http://www.baeldung.com/java-url-encoding-decoding)
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions)
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
- [JVM Log Forging](http://www.baeldung.com/jvm-log-forging)
- [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe)
- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
- [How to Add a Single Element to a Stream](http://www.baeldung.com/java-stream-append-prepend)
- [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null)
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)
@@ -26,7 +21,6 @@
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri)
- [OutOfMemoryError: GC Overhead Limit Exceeded](http://www.baeldung.com/java-gc-overhead-limit-exceeded)
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack)
- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter)
@@ -57,11 +51,9 @@
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
- [Calculating the nth Root in Java](https://www.baeldung.com/java-nth-root)
- [Convert Double to String, Removing Decimal Places](https://www.baeldung.com/java-double-to-string)
- [Different Ways to Capture Java Heap Dumps](https://www.baeldung.com/java-heap-dump-capture)
- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset)
- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing)
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
- [Understanding Memory Leaks in Java](https://www.baeldung.com/java-memory-leaks)
- [A Guide to SimpleDateFormat](https://www.baeldung.com/java-simple-date-format)
- [SSL Handshake Failures](https://www.baeldung.com/java-ssl-handshake-failures)
- [Changing the Order in a Sum Operation Can Produce Different Results?](https://www.baeldung.com/java-floating-point-sum-order)

View File

@@ -1,25 +0,0 @@
package com.baeldung.heapdump;
import com.sun.management.HotSpotDiagnosticMXBean;
import javax.management.MBeanServer;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.nio.file.Paths;
public class HeapDump {
public static void dumpHeap(String filePath, boolean live) throws IOException {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
HotSpotDiagnosticMXBean mxBean = ManagementFactory.newPlatformMXBeanProxy(
server, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class);
mxBean.dumpHeap(filePath, live);
}
public static void main(String[] args) throws IOException {
String file = Paths.get("dump.hprof").toFile().getPath();
dumpHeap(file, true);
}
}

View File

@@ -1,65 +0,0 @@
package com.baeldung.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.util.Iterator;
import java.util.List;
public class FullResponseBuilder {
public static String getFullResponse(HttpURLConnection con) throws IOException {
StringBuilder fullResponseBuilder = new StringBuilder();
fullResponseBuilder.append(con.getResponseCode())
.append(" ")
.append(con.getResponseMessage())
.append("\n");
con.getHeaderFields()
.entrySet()
.stream()
.filter(entry -> entry.getKey() != null)
.forEach(entry -> {
fullResponseBuilder.append(entry.getKey())
.append(": ");
List<String> headerValues = entry.getValue();
Iterator<String> it = headerValues.iterator();
if (it.hasNext()) {
fullResponseBuilder.append(it.next());
while (it.hasNext()) {
fullResponseBuilder.append(", ")
.append(it.next());
}
}
fullResponseBuilder.append("\n");
});
Reader streamReader = null;
if (con.getResponseCode() > 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();
fullResponseBuilder.append("Response: ")
.append(content);
return fullResponseBuilder.toString();
}
}

View File

@@ -1,21 +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<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;
}
}

View File

@@ -1,29 +0,0 @@
package com.baeldung.jmx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Game implements GameMBean {
private static final Logger LOG = LoggerFactory.getLogger(Game.class);
private String playerName;
@Override
public void playFootball(String clubName) {
LOG.debug(this.playerName + " playing football for " + clubName);
}
@Override
public String getPlayerName() {
LOG.debug("Return playerName " + this.playerName);
return playerName;
}
@Override
public void setPlayerName(String playerName) {
LOG.debug("Set playerName to value " + playerName);
this.playerName = playerName;
}
}

View File

@@ -1,11 +0,0 @@
package com.baeldung.jmx;
public interface GameMBean {
public void playFootball(String clubName);
public String getPlayerName();
public void setPlayerName(String playerName);
}

View File

@@ -1,37 +0,0 @@
package com.baeldung.jmx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.management.*;
import java.lang.management.ManagementFactory;
public class JMXTutorialMainlauncher {
private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class);
public static void main(String[] args) {
// TODO Auto-generated method stub
LOG.debug("This is basic JMX tutorial");
ObjectName objectName = null;
try {
objectName = new ObjectName("com.baeldung.tutorial:type=basic,name=game");
} catch (MalformedObjectNameException e) {
e.printStackTrace();
}
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
Game gameObj = new Game();
try {
server.registerMBean(gameObj, objectName);
} catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {
e.printStackTrace();
}
LOG.debug("Registration for Game mbean with the platform server is successfull");
LOG.debug("Please open jconsole to access Game mbean");
while (true) {
// to ensure application does not terminate
}
}
}

View File

@@ -1,9 +0,0 @@
package com.baeldung.memoryleaks.equalshashcode;
public class Person {
public String name;
public Person(String name) {
this.name = name;
}
}

View File

@@ -1,25 +0,0 @@
package com.baeldung.memoryleaks.equalshashcode;
public class PersonOptimized {
public String name;
public PersonOptimized(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof PersonOptimized)) {
return false;
}
PersonOptimized person = (PersonOptimized) o;
return person.name.equals(name);
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + name.hashCode();
return result;
}}

View File

@@ -1,32 +0,0 @@
package com.baeldung.memoryleaks.finalize;
import java.nio.charset.Charset;
import java.util.Random;
public class BulkyObject {
private String data[];
public BulkyObject() {
data = new String[1000000];
for(int i=0; i<1000000; i++) {
data[i] = getRandomString();
}
}
private String getRandomString() {
byte[] array = new byte[1000];
new Random().nextBytes(array);
return new String(array, Charset.forName("UTF-8"));
}
@Override
public void finalize() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Finalizer called");
}
}

View File

@@ -1,22 +0,0 @@
package com.baeldung.memoryleaks.finalize;
import java.nio.charset.Charset;
import java.util.Random;
public class BulkyObjectOptimized {
private String data[];
public BulkyObjectOptimized() {
data = new String[1000000];
for(int i=0; i<1000000; i++) {
data[i] = getRandomString();
}
}
private String getRandomString() {
byte[] array = new byte[1000];
new Random().nextBytes(array);
return new String(array, Charset.forName("UTF-8"));
}
}

View File

@@ -1,22 +0,0 @@
package com.baeldung.memoryleaks.innerclass;
import java.nio.charset.Charset;
import java.util.Random;
public class BulkyObject {
private String data[];
public BulkyObject() {
data = new String[1000000];
for(int i=0; i<1000000; i++) {
data[i] = getRandomString();
}
}
private String getRandomString() {
byte[] array = new byte[1000];
new Random().nextBytes(array);
return new String(array, Charset.forName("UTF-8"));
}
}

View File

@@ -1,17 +0,0 @@
package com.baeldung.memoryleaks.innerclass;
public class InnerClassDriver {
public static InnerClassWrapper.SimpleInnerClass getSimpleInnerClassObj() {
return new InnerClassWrapper().new SimpleInnerClass();
}
public static void main2(String[] args) {
InnerClassWrapper.SimpleInnerClass simpleInnerClassObj = getSimpleInnerClassObj();
System.out.println("Debug point");
}
public static void main(String[] args) {
StaticNestedClassWrapper.StaticNestedClass simpleInnerClassObj = new StaticNestedClassWrapper.StaticNestedClass();
System.out.println("Debug point");
}
}

View File

@@ -1,10 +0,0 @@
package com.baeldung.memoryleaks.innerclass;
public class InnerClassWrapper {
private BulkyObject bulkyObject = new BulkyObject();
public class SimpleInnerClass {
}
}

View File

@@ -1,10 +0,0 @@
package com.baeldung.memoryleaks.innerclass;
public class StaticNestedClassWrapper {
private BulkyObject bulkyObject = new BulkyObject();
public static class StaticNestedClass {
}
}

View File

@@ -1,17 +0,0 @@
package com.baeldung.memoryleaks.internedstrings;
public class InternedString {
private static final String FILEPATH = "C:\\bigstring.txt";
public void readString() {
String s1 = ReadStringFromFileUtil.read(FILEPATH).intern();
String s2 = ReadStringFromFileUtil.read(FILEPATH).intern();
if (s1 == s2) {
System.out.println("Both the strings objects are same");
}
else {
System.out.println("Both the strings objects are different");
}
}
}

View File

@@ -1,34 +0,0 @@
package com.baeldung.memoryleaks.internedstrings;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadStringFromFileUtil {
public static String read(String fileName) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}

View File

@@ -1,17 +0,0 @@
package com.baeldung.memoryleaks.internedstrings;
public class StringObject {
private static final String FILEPATH = "C:\\bigstring.txt";
public void readString() {
String s1 = ReadStringFromFileUtil.read(FILEPATH);
String s2 = ReadStringFromFileUtil.read(FILEPATH);
if (s1 == s2) {
System.out.println("Both the strings objects are same");
}
else {
System.out.println("Both the strings objects are different");
}
}
}

View File

@@ -1,21 +0,0 @@
package com.baeldung.memoryleaks.staticfields;
import java.util.ArrayList;
import java.util.List;
public class NonStaticFieldsDemo {
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");
}
public static void main(String[] args) {
System.out.println("Debug Point 1");
new NonStaticFieldsDemo().populateList();
System.out.println("Debug Point 3");
}
}

View File

@@ -1,21 +0,0 @@
package com.baeldung.memoryleaks.staticfields;
import java.util.ArrayList;
import java.util.List;
public class StaticFieldsDemo {
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");
}
public static void main(String[] args) {
System.out.println("Debug Point 1");
new StaticFieldsDemo().populateList();
System.out.println("Debug Point 3");
}
}

View File

@@ -1,19 +0,0 @@
package com.baeldung.outofmemoryerror;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class OutOfMemoryGCLimitExceed {
public static void addRandomDataToMap() {
Map<Integer, String> dataMap = new HashMap<>();
Random r = new Random();
while (true) {
dataMap.put(r.nextInt(), String.valueOf(r.nextInt()));
}
}
public static void main(String[] args) {
OutOfMemoryGCLimitExceed.addRandomDataToMap();
}
}

View File

@@ -1,47 +0,0 @@
package com.baeldung.socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.*;
public class EchoClient {
private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class);
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) {
LOG.debug("Error when initializing connection", 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) {
LOG.debug("error when closing", e);
}
}
}

View File

@@ -1,76 +0,0 @@
package com.baeldung.socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.*;
import java.io.*;
public class EchoMultiServer {
private static final Logger LOG = LoggerFactory.getLogger(EchoMultiServer.class);
private ServerSocket serverSocket;
public void start(int port) {
try {
serverSocket = new ServerSocket(port);
while (true)
new EchoClientHandler(serverSocket.accept()).start();
} catch (IOException e) {
e.printStackTrace();
} finally {
stop();
}
}
public void stop() {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static class EchoClientHandler extends Thread {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
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);
}
in.close();
out.close();
clientSocket.close();
} catch (IOException e) {
LOG.debug(e.getMessage());
}
}
}
public static void main(String[] args) {
EchoMultiServer server = new EchoMultiServer();
server.start(5555);
}
}

View File

@@ -1,55 +0,0 @@
package com.baeldung.socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.*;
import java.io.*;
public class EchoServer {
private static final Logger LOG = LoggerFactory.getLogger(EchoServer.class);
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) {
LOG.debug(e.getMessage());
}
}
public void stop() {
try {
in.close();
out.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
LOG.debug(e.getMessage());
}
}
public static void main(String[] args) {
EchoServer server = new EchoServer();
server.start(4444);
}
}

View File

@@ -1,50 +0,0 @@
package com.baeldung.socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class GreetClient {
private static final Logger LOG = LoggerFactory.getLogger(EchoMultiServer.class);
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) {
LOG.debug(e.getMessage());
}
}
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) {
LOG.debug(e.getMessage());
}
}
}

View File

@@ -1,52 +0,0 @@
package com.baeldung.socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.*;
import java.io.*;
public class GreetServer {
private static final Logger LOG = LoggerFactory.getLogger(GreetServer.class);
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) {
LOG.debug(e.getMessage());
}
}
public void stop() {
try {
in.close();
out.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
LOG.debug(e.getMessage());
}
}
public static void main(String[] args) {
GreetServer server = new GreetServer();
server.start(6666);
}
}

View File

@@ -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));
}
}

View File

@@ -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>"));
}
}

View File

@@ -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");
}
}

View File

@@ -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");
}
}

View File

@@ -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");
}
}

View File

@@ -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");
}
}

View File

@@ -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");
}
}

View File

@@ -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");
}
}

View File

@@ -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);
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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;
}
}

View File

@@ -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);
}
}

View File

@@ -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;
}
}
}