Merge branch 'master' into BAEL-10836
This commit is contained in:
+1
-14
@@ -7,7 +7,6 @@
|
||||
- [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)
|
||||
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
|
||||
- [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)
|
||||
@@ -27,13 +26,11 @@
|
||||
- [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)
|
||||
- [Broadcasting and Multicasting in Java](http://www.baeldung.com/java-broadcast-multicast)
|
||||
- [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)
|
||||
- [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class)
|
||||
- [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
|
||||
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
|
||||
- [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator)
|
||||
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
|
||||
@@ -42,31 +39,20 @@
|
||||
- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os)
|
||||
- [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
|
||||
- [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid)
|
||||
- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java)
|
||||
- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
|
||||
- [Class Loaders in Java](http://www.baeldung.com/java-classloaders)
|
||||
- [Sending Emails with Java](http://www.baeldung.com/java-email)
|
||||
- [Introduction to SSL in Java](http://www.baeldung.com/java-ssl)
|
||||
- [Java KeyStore API](http://www.baeldung.com/java-keystore)
|
||||
- [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking)
|
||||
- [Guide to Java Clock Class](http://www.baeldung.com/java-clock)
|
||||
- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns)
|
||||
- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns)
|
||||
- [Singletons in Java](http://www.baeldung.com/java-singleton)
|
||||
- [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight)
|
||||
- [The Observer Pattern in Java](http://www.baeldung.com/java-observer-pattern)
|
||||
- [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern)
|
||||
- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join)
|
||||
- [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class)
|
||||
- [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension)
|
||||
- [Console I/O in Java](http://www.baeldung.com/java-console-input-output)
|
||||
- [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler)
|
||||
- [Encrypting and Decrypting Files in Java](http://www.baeldung.com/java-cipher-input-output-stream)
|
||||
- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object)
|
||||
- [Guide to Java Instrumentation](http://www.baeldung.com/java-instrumentation)
|
||||
- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type)
|
||||
- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions)
|
||||
- [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods)
|
||||
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
|
||||
- [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)
|
||||
@@ -85,3 +71,4 @@
|
||||
- [Calculate the Area of a Circle in Java](https://www.baeldung.com/java-calculate-circle-area)
|
||||
- [A Guide to the Java Math Class](https://www.baeldung.com/java-lang-math)
|
||||
- [Graphs in Java](https://www.baeldung.com/java-graphs)
|
||||
- [Console I/O in Java](http://www.baeldung.com/java-console-input-output)
|
||||
|
||||
+1
-7
@@ -131,11 +131,6 @@
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2database.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.mail</groupId>
|
||||
<artifactId>mail</artifactId>
|
||||
<version>${javax.mail.version}</version>
|
||||
</dependency>
|
||||
<!-- Mime Type Resolution Libraries -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tika</groupId>
|
||||
@@ -482,7 +477,7 @@
|
||||
<properties>
|
||||
|
||||
<!-- marshalling -->
|
||||
<jackson.version>2.8.5</jackson.version>
|
||||
<jackson.version>2.9.7</jackson.version>
|
||||
<gson.version>2.8.2</gson.version>
|
||||
|
||||
<!-- util -->
|
||||
@@ -514,7 +509,6 @@
|
||||
|
||||
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
|
||||
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
||||
<javax.mail.version>1.5.0-b01</javax.mail.version>
|
||||
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
|
||||
<onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version>
|
||||
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
|
||||
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.constructorsstaticfactorymethods.application;
|
||||
|
||||
import com.baeldung.constructorsstaticfactorymethods.entities.User;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
User user1 = User.createWithDefaultCountry("John", "john@domain.com");
|
||||
User user2 = User.createWithLoggedInstantiationTime("John", "john@domain.com", "Argentina");
|
||||
User user3 = User.getSingletonInstance("John", "john@domain.com", "Argentina");
|
||||
}
|
||||
}
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
package com.baeldung.constructorsstaticfactorymethods.entities;
|
||||
|
||||
import java.time.LocalTime;
|
||||
import java.util.logging.ConsoleHandler;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.logging.SimpleFormatter;
|
||||
|
||||
public class User {
|
||||
|
||||
private static volatile User instance = null;
|
||||
private static final Logger LOGGER = Logger.getLogger(User.class.getName());
|
||||
private final String name;
|
||||
private final String email;
|
||||
private final String country;
|
||||
|
||||
public static User createWithDefaultCountry(String name, String email) {
|
||||
return new User(name, email, "Argentina");
|
||||
}
|
||||
|
||||
public static User createWithLoggedInstantiationTime(String name, String email, String country) {
|
||||
setLoggerProperties();
|
||||
LOGGER.log(Level.INFO, "Creating User instance at : {0}", LocalTime.now());
|
||||
return new User(name, email, country);
|
||||
}
|
||||
|
||||
public static User getSingletonInstance(String name, String email, String country) {
|
||||
if (instance == null) {
|
||||
synchronized (User.class) {
|
||||
if (instance == null) {
|
||||
instance = new User(name, email, country);
|
||||
}
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
|
||||
}
|
||||
|
||||
private User(String name, String email, String country) {
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
private static void setLoggerProperties() {
|
||||
ConsoleHandler handler = new ConsoleHandler();
|
||||
handler.setLevel(Level.INFO);
|
||||
handler.setFormatter(new SimpleFormatter());
|
||||
LOGGER.addHandler(handler);
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package com.baeldung.forkjoin;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ForkJoinTask;
|
||||
import java.util.concurrent.RecursiveAction;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class CustomRecursiveAction extends RecursiveAction {
|
||||
|
||||
private String workLoad = "";
|
||||
private static final int THRESHOLD = 4;
|
||||
|
||||
private static Logger logger = Logger.getAnonymousLogger();
|
||||
|
||||
public CustomRecursiveAction(String workLoad) {
|
||||
this.workLoad = workLoad;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void compute() {
|
||||
|
||||
if (workLoad.length() > THRESHOLD) {
|
||||
ForkJoinTask.invokeAll(createSubtasks());
|
||||
} else {
|
||||
processing(workLoad);
|
||||
}
|
||||
}
|
||||
|
||||
private Collection<CustomRecursiveAction> createSubtasks() {
|
||||
|
||||
List<CustomRecursiveAction> subtasks = new ArrayList<>();
|
||||
|
||||
String partOne = workLoad.substring(0, workLoad.length() / 2);
|
||||
String partTwo = workLoad.substring(workLoad.length() / 2, workLoad.length());
|
||||
|
||||
subtasks.add(new CustomRecursiveAction(partOne));
|
||||
subtasks.add(new CustomRecursiveAction(partTwo));
|
||||
|
||||
return subtasks;
|
||||
}
|
||||
|
||||
private void processing(String work) {
|
||||
String result = work.toUpperCase();
|
||||
logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread()
|
||||
.getName());
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package com.baeldung.forkjoin;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ForkJoinTask;
|
||||
import java.util.concurrent.RecursiveTask;
|
||||
|
||||
public class CustomRecursiveTask extends RecursiveTask<Integer> {
|
||||
|
||||
private int[] arr;
|
||||
|
||||
private static final int THRESHOLD = 20;
|
||||
|
||||
public CustomRecursiveTask(int[] arr) {
|
||||
this.arr = arr;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Integer compute() {
|
||||
|
||||
if (arr.length > THRESHOLD) {
|
||||
|
||||
return ForkJoinTask.invokeAll(createSubtasks()).stream().mapToInt(ForkJoinTask::join).sum();
|
||||
|
||||
} else {
|
||||
return processing(arr);
|
||||
}
|
||||
}
|
||||
|
||||
private Collection<CustomRecursiveTask> createSubtasks() {
|
||||
List<CustomRecursiveTask> dividedTasks = new ArrayList<>();
|
||||
dividedTasks.add(new CustomRecursiveTask(Arrays.copyOfRange(arr, 0, arr.length / 2)));
|
||||
dividedTasks.add(new CustomRecursiveTask(Arrays.copyOfRange(arr, arr.length / 2, arr.length)));
|
||||
return dividedTasks;
|
||||
}
|
||||
|
||||
private Integer processing(int[] arr) {
|
||||
return Arrays.stream(arr).filter(a -> a > 10 && a < 27).map(a -> a * 10).sum();
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.forkjoin.util;
|
||||
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
|
||||
public class PoolUtil {
|
||||
|
||||
public static ForkJoinPool forkJoinPool = new ForkJoinPool(2);
|
||||
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package com.baeldung.gc;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A simple Java program to demonstrate how to enable verbose Garbage Collection (GC) logging.
|
||||
* <p>
|
||||
* This simple program loads 3 million {@link java.lang.String} instances into a {@link java.util.HashMap}
|
||||
* object before making an explicit call to the garbage collector using <code>System.gc()</code>.
|
||||
* <p>
|
||||
* Finally, it removes 2 million of the {@link java.lang.String} instances from the {@link java.util.HashMap}.
|
||||
* We also explicitly use <code>System.out.println</code> to make interpreting the output easier.
|
||||
* <p>
|
||||
* Run this program with the following arguments to see verbose GC logging in its complete form:
|
||||
* <pre>
|
||||
* -XX:+UseSerialGC -Xms1024m -Xmx1024m -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintGCDateStamps -Xloggc:/path/to/file/gc.log
|
||||
* </pre>
|
||||
* Where:
|
||||
* <ul>
|
||||
* <li><code>-XX:+UseSerialGC</code> - specify the serial garbage collector.</li>
|
||||
* <li><code>-Xms1024m</code> - specify the minimal heap size.</li>
|
||||
* <li><code>-Xmx1024m</code> - specify the maximal heap size.</li>
|
||||
* <li><code>-verbose:gc</code> - activate the logging of garbage collection information in its simplest form.</li>
|
||||
* <li><code>-XX:+PrintGCDetails</code> - activate detailed information about garbage collection.</li>
|
||||
* <li><code>-XX:+PrintGCTimeStamps</code> - include a timestamp in the output reflecting the real-time passed in seconds since the JVM started.</li>
|
||||
* <li><code>-XX:+PrintGCDateStamps</code> - include the absolute date and time at the start of each line.</li>
|
||||
* <li><code>-Xloggc</code> - by default the GC log is written to stdout. Specify an output file via this argument.</li>
|
||||
* </ul>
|
||||
* <p>
|
||||
* It should be noted that the first three arguments are not strictly necessary but for the purposes or the example
|
||||
* help really simplify things.
|
||||
*
|
||||
*/
|
||||
public class VerboseGarbageCollectorRunner {
|
||||
|
||||
private static Map<String, String> stringContainer = new HashMap<>();
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Start of program!");
|
||||
String stringWithPrefix = "stringWithPrefix";
|
||||
|
||||
// Load Java Heap with 3 M java.lang.String instances
|
||||
for (int i = 0; i < 3000000; i++) {
|
||||
String newString = stringWithPrefix + i;
|
||||
stringContainer.put(newString, newString);
|
||||
}
|
||||
System.out.println("MAP size: " + stringContainer.size());
|
||||
|
||||
// Explicit GC!
|
||||
System.gc();
|
||||
|
||||
// Remove 2 M out of 3 M
|
||||
for (int i = 0; i < 2000000; i++) {
|
||||
String newString = stringWithPrefix + i;
|
||||
stringContainer.remove(newString);
|
||||
}
|
||||
|
||||
System.out.println("MAP size: " + stringContainer.size());
|
||||
System.out.println("End of program!");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package com.baeldung.javanetworking.uriurl;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class URIDemo {
|
||||
private final Logger logger = LoggerFactory.getLogger(URIDemo.class);
|
||||
|
||||
String URISTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
|
||||
// parsed locator
|
||||
String URISCHEME = "https";
|
||||
String URISCHEMESPECIFIC;
|
||||
String URIHOST = "wordpress.org";
|
||||
String URIAUTHORITY = "wordpress.org:443";
|
||||
|
||||
String URIPATH = "/support/topic/page-jumps-within-wordpress/";
|
||||
int URIPORT = 443;
|
||||
String URIQUERY = "replies=3";
|
||||
String URIFRAGMENT = "post-2278484";
|
||||
String URIUSERINFO;
|
||||
String URICOMPOUND = URISCHEME + "://" + URIHOST + ":" + URIPORT + URIPATH + "?" + URIQUERY + "#" + URIFRAGMENT;
|
||||
|
||||
URI uri;
|
||||
URL url;
|
||||
BufferedReader in = null;
|
||||
String URIContent = "";
|
||||
|
||||
private String getParsedPieces(URI uri) {
|
||||
logger.info("*** List of parsed pieces ***");
|
||||
URISCHEME = uri.getScheme();
|
||||
logger.info("URISCHEME: " + URISCHEME);
|
||||
URISCHEMESPECIFIC = uri.getSchemeSpecificPart();
|
||||
logger.info("URISCHEMESPECIFIC: " + URISCHEMESPECIFIC);
|
||||
URIHOST = uri.getHost();
|
||||
URIAUTHORITY = uri.getAuthority();
|
||||
logger.info("URIAUTHORITY: " + URIAUTHORITY);
|
||||
logger.info("URIHOST: " + URIHOST);
|
||||
URIPATH = uri.getPath();
|
||||
logger.info("URIPATH: " + URIPATH);
|
||||
URIPORT = uri.getPort();
|
||||
logger.info("URIPORT: " + URIPORT);
|
||||
URIQUERY = uri.getQuery();
|
||||
logger.info("URIQUERY: " + URIQUERY);
|
||||
URIFRAGMENT = uri.getFragment();
|
||||
logger.info("URIFRAGMENT: " + URIFRAGMENT);
|
||||
|
||||
try {
|
||||
url = uri.toURL();
|
||||
} catch (MalformedURLException e) {
|
||||
logger.info("MalformedURLException thrown: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.info("IllegalArgumentException thrown: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
public String testURIAsNew(String URIString) {
|
||||
// creating URI object
|
||||
try {
|
||||
uri = new URI(URIString);
|
||||
} catch (URISyntaxException e) {
|
||||
logger.info("URISyntaxException thrown: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
return getParsedPieces(uri);
|
||||
}
|
||||
|
||||
public String testURIAsCreate(String URIString) {
|
||||
// creating URI object
|
||||
uri = URI.create(URIString);
|
||||
return getParsedPieces(uri);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
URIDemo demo = new URIDemo();
|
||||
String contentCreate = demo.testURIAsCreate(demo.URICOMPOUND);
|
||||
demo.logger.info(contentCreate);
|
||||
String contentNew = demo.testURIAsNew(demo.URICOMPOUND);
|
||||
demo.logger.info(contentNew);
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
package com.baeldung.javanetworking.uriurl;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class URLDemo {
|
||||
private final Logger log = LoggerFactory.getLogger(URLDemo.class);
|
||||
|
||||
String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
|
||||
// parsed locator
|
||||
String URLPROTOCOL = "https";
|
||||
// final static String URLAUTHORITY = "wordpress.org:443";
|
||||
String URLHOST = "wordpress.org";
|
||||
String URLPATH = "/support/topic/page-jumps-within-wordpress/";
|
||||
// final static String URLFILENAME = "/support/topic/page-jumps-within-wordpress/?replies=3";
|
||||
// final static int URLPORT = 443;
|
||||
int URLDEFAULTPORT = 443;
|
||||
String URLQUERY = "replies=3";
|
||||
String URLREFERENCE = "post-2278484";
|
||||
String URLCOMPOUND = URLPROTOCOL + "://" + URLHOST + ":" + URLDEFAULTPORT + URLPATH + "?" + URLQUERY + "#" + URLREFERENCE;
|
||||
|
||||
URL url;
|
||||
URLConnection urlConnection = null;
|
||||
HttpURLConnection connection = null;
|
||||
BufferedReader in = null;
|
||||
String urlContent = "";
|
||||
|
||||
public String testURL(String urlString) throws IOException, IllegalArgumentException {
|
||||
String urlStringCont = "";
|
||||
// comment the if clause if experiment with URL
|
||||
/*if (!URLSTRING.equals(urlString)) {
|
||||
throw new IllegalArgumentException("URL String argument is not proper: " + urlString);
|
||||
}*/
|
||||
// creating URL object
|
||||
url = new URL(urlString);
|
||||
// get URL connection
|
||||
urlConnection = url.openConnection();
|
||||
connection = null;
|
||||
// we can check, if connection is proper type
|
||||
if (urlConnection instanceof HttpURLConnection) {
|
||||
connection = (HttpURLConnection) urlConnection;
|
||||
} else {
|
||||
log.info("Please enter an HTTP URL");
|
||||
throw new IOException("HTTP URL is not correct");
|
||||
}
|
||||
// we can check response code (200 OK is expected)
|
||||
log.info(connection.getResponseCode() + " " + connection.getResponseMessage());
|
||||
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||
String current;
|
||||
|
||||
while ((current = in.readLine()) != null) {
|
||||
urlStringCont += current;
|
||||
}
|
||||
return urlStringCont;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
URLDemo demo = new URLDemo();
|
||||
String content = demo.testURL(demo.URLCOMPOUND);
|
||||
demo.log.info(content);
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package com.baeldung.mail;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Properties;
|
||||
import javax.mail.*;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeBodyPart;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import javax.mail.internet.MimeMultipart;
|
||||
|
||||
public class EmailService {
|
||||
|
||||
private String host = "";
|
||||
private int port = 0;
|
||||
private String username = "";
|
||||
private String password = "";
|
||||
|
||||
|
||||
public EmailService(String host, int port, String username, String password) {
|
||||
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
|
||||
sendMail();
|
||||
}
|
||||
|
||||
private void sendMail() {
|
||||
|
||||
Properties prop = new Properties();
|
||||
prop.put("mail.smtp.auth", true);
|
||||
prop.put("mail.smtp.starttls.enable", "true");
|
||||
prop.put("mail.smtp.host", host);
|
||||
prop.put("mail.smtp.port", port);
|
||||
prop.put("mail.smtp.ssl.trust", host);
|
||||
|
||||
Session session = Session.getInstance(prop, new Authenticator() {
|
||||
@Override
|
||||
protected PasswordAuthentication getPasswordAuthentication() {
|
||||
return new PasswordAuthentication(username, password);
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
|
||||
Message message = new MimeMessage(session);
|
||||
message.setFrom(new InternetAddress("from@gmail.com"));
|
||||
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
|
||||
message.setSubject("Mail Subject");
|
||||
|
||||
String msg = "This is my first email using JavaMailer";
|
||||
|
||||
MimeBodyPart mimeBodyPart = new MimeBodyPart();
|
||||
mimeBodyPart.setContent(msg, "text/html");
|
||||
|
||||
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
|
||||
attachmentBodyPart.attachFile(new File("pom.xml"));
|
||||
|
||||
Multipart multipart = new MimeMultipart();
|
||||
multipart.addBodyPart(mimeBodyPart);
|
||||
multipart.addBodyPart(attachmentBodyPart);
|
||||
|
||||
message.setContent(multipart);
|
||||
|
||||
Transport.send(message);
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String ... args) {
|
||||
new EmailService("smtp.mailtrap.io", 25, "87ba3d9555fae8", "91cb4379af43ed");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
### Relevant Articles:
|
||||
- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java)
|
||||
- [A Guide To HTTP Cookies In Java](http://www.baeldung.com/cookies-java)
|
||||
- [A Guide to the Java URL](http://www.baeldung.com/java-url)
|
||||
- [Working with Network Interfaces in Java](http://www.baeldung.com/java-network-interfaces)
|
||||
@@ -1,57 +0,0 @@
|
||||
package com.baeldung.networking.cookies;
|
||||
|
||||
import java.net.*;
|
||||
import java.util.List;
|
||||
|
||||
public class PersistentCookieStore implements CookieStore, Runnable {
|
||||
CookieStore store;
|
||||
|
||||
public PersistentCookieStore() {
|
||||
store = new CookieManager().getCookieStore();
|
||||
// deserialize cookies into store
|
||||
Runtime.getRuntime()
|
||||
.addShutdownHook(new Thread(this));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
// serialize cookies to persistent storage
|
||||
}
|
||||
|
||||
@Override
|
||||
public void add(URI uri, HttpCookie cookie) {
|
||||
store.add(uri, cookie);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<HttpCookie> get(URI uri) {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<HttpCookie> getCookies() {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<URI> getURIs() {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean remove(URI uri, HttpCookie cookie) {
|
||||
// TODO Auto-generated method stub
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean removeAll() {
|
||||
// TODO Auto-generated method stub
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.baeldung.networking.cookies;
|
||||
|
||||
import java.net.*;
|
||||
|
||||
public class ProxyAcceptCookiePolicy implements CookiePolicy {
|
||||
String acceptedProxy;
|
||||
|
||||
public ProxyAcceptCookiePolicy(String acceptedProxy) {
|
||||
this.acceptedProxy = acceptedProxy;
|
||||
}
|
||||
|
||||
public boolean shouldAccept(URI uri, HttpCookie cookie) {
|
||||
String host;
|
||||
try {
|
||||
host = InetAddress.getByName(uri.getHost()).getCanonicalHostName();
|
||||
} catch (UnknownHostException e) {
|
||||
host = uri.getHost();
|
||||
}
|
||||
|
||||
if (!HttpCookie.domainMatches(acceptedProxy, host)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(uri, cookie);
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package com.baeldung.networking.udp;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
|
||||
public class EchoClient {
|
||||
private DatagramSocket socket;
|
||||
private InetAddress address;
|
||||
|
||||
private byte[] buf;
|
||||
|
||||
public EchoClient() {
|
||||
try {
|
||||
socket = new DatagramSocket();
|
||||
address = InetAddress.getByName("localhost");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public String sendEcho(String msg) {
|
||||
DatagramPacket packet = null;
|
||||
try {
|
||||
buf = msg.getBytes();
|
||||
packet = new DatagramPacket(buf, buf.length, address, 4445);
|
||||
socket.send(packet);
|
||||
packet = new DatagramPacket(buf, buf.length);
|
||||
socket.receive(packet);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
String received = new String(packet.getData(), 0, packet.getLength());
|
||||
return received;
|
||||
}
|
||||
|
||||
public void close() {
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package com.baeldung.networking.udp;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
|
||||
public class EchoServer extends Thread {
|
||||
|
||||
protected DatagramSocket socket = null;
|
||||
protected boolean running;
|
||||
protected byte[] buf = new byte[256];
|
||||
|
||||
public EchoServer() throws IOException {
|
||||
socket = new DatagramSocket(4445);
|
||||
}
|
||||
|
||||
public void run() {
|
||||
running = true;
|
||||
|
||||
while (running) {
|
||||
try {
|
||||
|
||||
DatagramPacket packet = new DatagramPacket(buf, buf.length);
|
||||
socket.receive(packet);
|
||||
InetAddress address = packet.getAddress();
|
||||
int port = packet.getPort();
|
||||
packet = new DatagramPacket(buf, buf.length, address, port);
|
||||
String received = new String(packet.getData(), 0, packet.getLength());
|
||||
if (received.equals("end")) {
|
||||
running = false;
|
||||
continue;
|
||||
}
|
||||
socket.send(packet);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
running = false;
|
||||
}
|
||||
}
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
package com.baeldung.networking.udp.broadcast;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.SocketException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class BroadcastingClient {
|
||||
private DatagramSocket socket;
|
||||
private InetAddress address;
|
||||
private int expectedServerCount;
|
||||
private byte[] buf;
|
||||
|
||||
public BroadcastingClient(int expectedServerCount) throws Exception {
|
||||
this.expectedServerCount = expectedServerCount;
|
||||
this.address = InetAddress.getByName("255.255.255.255");
|
||||
}
|
||||
|
||||
public int discoverServers(String msg) throws IOException {
|
||||
initializeSocketForBroadcasting();
|
||||
copyMessageOnBuffer(msg);
|
||||
|
||||
// When we want to broadcast not just to local network, call listAllBroadcastAddresses() and execute broadcastPacket for each value.
|
||||
broadcastPacket(address);
|
||||
|
||||
return receivePackets();
|
||||
}
|
||||
|
||||
List<InetAddress> listAllBroadcastAddresses() throws SocketException {
|
||||
List<InetAddress> broadcastList = new ArrayList<>();
|
||||
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
|
||||
while (interfaces.hasMoreElements()) {
|
||||
NetworkInterface networkInterface = interfaces.nextElement();
|
||||
|
||||
if (networkInterface.isLoopback() || !networkInterface.isUp()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
broadcastList.addAll(networkInterface.getInterfaceAddresses()
|
||||
.stream()
|
||||
.filter(address -> address.getBroadcast() != null)
|
||||
.map(address -> address.getBroadcast())
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
return broadcastList;
|
||||
}
|
||||
|
||||
private void initializeSocketForBroadcasting() throws SocketException {
|
||||
socket = new DatagramSocket();
|
||||
socket.setBroadcast(true);
|
||||
}
|
||||
|
||||
private void copyMessageOnBuffer(String msg) {
|
||||
buf = msg.getBytes();
|
||||
}
|
||||
|
||||
private void broadcastPacket(InetAddress address) throws IOException {
|
||||
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
|
||||
socket.send(packet);
|
||||
}
|
||||
|
||||
private int receivePackets() throws IOException {
|
||||
int serversDiscovered = 0;
|
||||
while (serversDiscovered != expectedServerCount) {
|
||||
receivePacket();
|
||||
serversDiscovered++;
|
||||
}
|
||||
return serversDiscovered;
|
||||
}
|
||||
|
||||
private void receivePacket() throws IOException {
|
||||
DatagramPacket packet = new DatagramPacket(buf, buf.length);
|
||||
socket.receive(packet);
|
||||
}
|
||||
|
||||
public void close() {
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
-44
@@ -1,44 +0,0 @@
|
||||
package com.baeldung.networking.udp.broadcast;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
|
||||
public class BroadcastingEchoServer extends Thread {
|
||||
|
||||
protected DatagramSocket socket = null;
|
||||
protected boolean running;
|
||||
protected byte[] buf = new byte[256];
|
||||
|
||||
public BroadcastingEchoServer() throws IOException {
|
||||
socket = new DatagramSocket(null);
|
||||
socket.setReuseAddress(true);
|
||||
socket.bind(new InetSocketAddress(4445));
|
||||
}
|
||||
|
||||
public void run() {
|
||||
running = true;
|
||||
|
||||
while (running) {
|
||||
try {
|
||||
DatagramPacket packet = new DatagramPacket(buf, buf.length);
|
||||
socket.receive(packet);
|
||||
InetAddress address = packet.getAddress();
|
||||
int port = packet.getPort();
|
||||
packet = new DatagramPacket(buf, buf.length, address, port);
|
||||
String received = new String(packet.getData(), 0, packet.getLength());
|
||||
if (received.equals("end")) {
|
||||
running = false;
|
||||
continue;
|
||||
}
|
||||
socket.send(packet);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
running = false;
|
||||
}
|
||||
}
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
package com.baeldung.networking.udp.multicast;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.InetAddress;
|
||||
import java.net.MulticastSocket;
|
||||
|
||||
public class MulticastEchoServer extends Thread {
|
||||
|
||||
protected MulticastSocket socket = null;
|
||||
protected byte[] buf = new byte[256];
|
||||
protected InetAddress group = null;
|
||||
|
||||
public MulticastEchoServer() throws IOException {
|
||||
socket = new MulticastSocket(4446);
|
||||
socket.setReuseAddress(true);
|
||||
group = InetAddress.getByName("230.0.0.0");
|
||||
socket.joinGroup(group);
|
||||
}
|
||||
|
||||
public void run() {
|
||||
try {
|
||||
while (true) {
|
||||
DatagramPacket packet = new DatagramPacket(buf, buf.length);
|
||||
socket.receive(packet);
|
||||
InetAddress address = packet.getAddress();
|
||||
int port = packet.getPort();
|
||||
packet = new DatagramPacket(buf, buf.length, address, port);
|
||||
String received = new String(packet.getData(), 0, packet.getLength());
|
||||
if (received.equals("end")) {
|
||||
break;
|
||||
}
|
||||
socket.send(packet);
|
||||
}
|
||||
socket.leaveGroup(group);
|
||||
socket.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package com.baeldung.networking.udp.multicast;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
|
||||
public class MulticastingClient {
|
||||
private DatagramSocket socket;
|
||||
private InetAddress group;
|
||||
private int expectedServerCount;
|
||||
private byte[] buf;
|
||||
|
||||
public MulticastingClient(int expectedServerCount) throws Exception {
|
||||
this.expectedServerCount = expectedServerCount;
|
||||
this.socket = new DatagramSocket();
|
||||
this.group = InetAddress.getByName("230.0.0.0");
|
||||
}
|
||||
|
||||
public int discoverServers(String msg) throws IOException {
|
||||
copyMessageOnBuffer(msg);
|
||||
multicastPacket();
|
||||
|
||||
return receivePackets();
|
||||
}
|
||||
|
||||
private void copyMessageOnBuffer(String msg) {
|
||||
buf = msg.getBytes();
|
||||
}
|
||||
|
||||
private void multicastPacket() throws IOException {
|
||||
DatagramPacket packet = new DatagramPacket(buf, buf.length, group, 4446);
|
||||
socket.send(packet);
|
||||
}
|
||||
|
||||
private int receivePackets() throws IOException {
|
||||
int serversDiscovered = 0;
|
||||
while (serversDiscovered != expectedServerCount) {
|
||||
receivePacket();
|
||||
serversDiscovered++;
|
||||
}
|
||||
return serversDiscovered;
|
||||
}
|
||||
|
||||
private void receivePacket() throws IOException {
|
||||
DatagramPacket packet = new DatagramPacket(buf, buf.length);
|
||||
socket.receive(packet);
|
||||
}
|
||||
|
||||
public void close() {
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.threadlocalrandom;
|
||||
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
public class ThreadLocalRandomBenchMarkRunner {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
Options options = new OptionsBuilder().include(ThreadLocalRandomBenchMarker.class.getSimpleName())
|
||||
.threads(1)
|
||||
.forks(1)
|
||||
.shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server")
|
||||
.build();
|
||||
|
||||
new Runner(options).run();
|
||||
|
||||
}
|
||||
}
|
||||
-64
@@ -1,64 +0,0 @@
|
||||
package com.baeldung.threadlocalrandom;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Level;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.Setup;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.annotations.Warmup;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@Warmup(iterations = 1)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
@State(Scope.Benchmark)
|
||||
public class ThreadLocalRandomBenchMarker {
|
||||
|
||||
List<Callable<Integer>> randomCallables = new ArrayList<>();
|
||||
List<Callable<Integer>> threadLocalRandomCallables = new ArrayList<>();
|
||||
|
||||
@Setup(Level.Iteration)
|
||||
public void init() {
|
||||
Random random = new Random();
|
||||
randomCallables = new ArrayList<>();
|
||||
threadLocalRandomCallables = new ArrayList<>();
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
randomCallables.add(() -> {
|
||||
return random.nextInt();
|
||||
});
|
||||
}
|
||||
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
threadLocalRandomCallables.add(() -> {
|
||||
return ThreadLocalRandom.current()
|
||||
.nextInt();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void randomValuesUsingRandom() throws InterruptedException {
|
||||
ExecutorService executor = Executors.newWorkStealingPool();
|
||||
executor.invokeAll(randomCallables);
|
||||
executor.shutdown();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void randomValuesUsingThreadLocalRandom() throws InterruptedException {
|
||||
ExecutorService executor = Executors.newWorkStealingPool();
|
||||
executor.invokeAll(threadLocalRandomCallables);
|
||||
executor.shutdown();
|
||||
}
|
||||
|
||||
}
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
package com.baeldung.constructorsstaticfactorymethods;
|
||||
|
||||
import com.baeldung.constructorsstaticfactorymethods.entities.User;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UserUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenUserClass_whenCalledcreateWithDefaultCountry_thenCorrect() {
|
||||
assertThat(User.createWithDefaultCountry("John", "john@domain.com")).isInstanceOf(User.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetName_thenCorrect() {
|
||||
User user = User.createWithDefaultCountry("John", "john@domain.com");
|
||||
assertThat(user.getName()).isEqualTo("John");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetEmail_thenCorrect() {
|
||||
User user = User.createWithDefaultCountry("John", "john@domain.com");
|
||||
assertThat(user.getEmail()).isEqualTo("john@domain.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetCountry_thenCorrect() {
|
||||
User user = User.createWithDefaultCountry("John", "john@domain.com");
|
||||
assertThat(user.getCountry()).isEqualTo("Argentina");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserInstanceCreatedWithcreateWithInstantiationTime_whenCalledcreateWithInstantiationTime_thenCorrect() {
|
||||
assertThat(User.createWithLoggedInstantiationTime("John", "john@domain.com", "Argentina")).isInstanceOf(User.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserInstanceCreatedWithgetSingletonIntance_whenCalledgetSingletonInstance_thenCorrect() {
|
||||
User user1 = User.getSingletonInstance("John", "john@domain.com", "Argentina");
|
||||
User user2 = User.getSingletonInstance("John", "john@domain.com", "Argentina");
|
||||
assertThat(user1).isEqualTo(user2);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ 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;
|
||||
@@ -48,7 +49,8 @@ public class HttpRequestLiveTest {
|
||||
in.close();
|
||||
|
||||
assertEquals("status code incorrect", status, 200);
|
||||
assertTrue("content incorrect", content.toString().contains("Example Domain"));
|
||||
assertTrue("content incorrect", content.toString()
|
||||
.contains("Example Domain"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -89,18 +91,24 @@ public class HttpRequestLiveTest {
|
||||
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"));
|
||||
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"));
|
||||
cookieManager.getCookieStore()
|
||||
.add(null, new HttpCookie("username", "john"));
|
||||
}
|
||||
|
||||
con.disconnect();
|
||||
|
||||
con = (HttpURLConnection) url.openConnection();
|
||||
con.setRequestProperty("Cookie", StringUtils.join(cookieManager.getCookieStore().getCookies(), ";"));
|
||||
con.setRequestProperty("Cookie", StringUtils.join(cookieManager.getCookieStore()
|
||||
.getCookies(), ";"));
|
||||
|
||||
int status = con.getResponseCode();
|
||||
|
||||
@@ -125,4 +133,56 @@ public class HttpRequestLiveTest {
|
||||
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>"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
-118
@@ -1,118 +0,0 @@
|
||||
package com.baeldung.java.networking.interfaces;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.net.*;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class NetworkInterfaceManualTest {
|
||||
@Test
|
||||
public void givenName_whenReturnsNetworkInterface_thenCorrect() throws SocketException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInExistentName_whenReturnsNull_thenCorrect() throws SocketException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("inexistent_name");
|
||||
assertNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIP_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
byte[] ip = new byte[] { 127, 0, 0, 1 };
|
||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByAddress(ip));
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHostName_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByName("localhost"));
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalHost_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoopBack_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLoopbackAddress());
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIndex_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByIndex(0);
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenReturnsInetAddresses_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
Enumeration<InetAddress> addressEnum = nif.getInetAddresses();
|
||||
InetAddress address = addressEnum.nextElement();
|
||||
assertEquals("127.0.0.1", address.getHostAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenReturnsInterfaceAddresses_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
|
||||
List<InterfaceAddress> addressEnum = nif.getInterfaceAddresses();
|
||||
InterfaceAddress address = addressEnum.get(0);
|
||||
InetAddress localAddress = address.getAddress();
|
||||
InetAddress broadCastAddress = address.getBroadcast();
|
||||
assertEquals("127.0.0.1", localAddress.getHostAddress());
|
||||
assertEquals("127.255.255.255", broadCastAddress.getHostAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksIfLoopback_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertTrue(nif.isLoopback());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksIfUp_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertTrue(nif.isUp());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksIfPointToPoint_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertFalse(nif.isPointToPoint());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksIfVirtual_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertFalse(nif.isVirtual());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksMulticastSupport_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertTrue(nif.supportsMulticast());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenGetsMacAddress_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
byte[] bytes = nif.getHardwareAddress();
|
||||
assertNotNull(bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenGetsMTU_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("net0");
|
||||
int mtu = nif.getMTU();
|
||||
assertEquals(1500, mtu);
|
||||
}
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
package com.baeldung.java.networking.url;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class UrlUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCanIdentifyProtocol_thenCorrect() throws MalformedURLException {
|
||||
final URL url = new URL("http://baeldung.com");
|
||||
assertEquals("http", url.getProtocol());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCanGetHost_thenCorrect() throws MalformedURLException {
|
||||
final URL url = new URL("http://baeldung.com");
|
||||
assertEquals("baeldung.com", url.getHost());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCanGetFileName_thenCorrect2() throws MalformedURLException {
|
||||
final URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
|
||||
assertEquals("/articles?topic=java&version=8", url.getFile());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCanGetFileName_thenCorrect1() throws MalformedURLException {
|
||||
final URL url = new URL("http://baeldung.com/guidelines.txt");
|
||||
assertEquals("/guidelines.txt", url.getFile());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCanGetPathParams_thenCorrect() throws MalformedURLException {
|
||||
final URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
|
||||
assertEquals("/articles", url.getPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCanGetQueryParams_thenCorrect() throws MalformedURLException {
|
||||
final URL url = new URL("http://baeldung.com/articles?topic=java");
|
||||
assertEquals("topic=java", url.getQuery());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenGetsDefaultPort_thenCorrect() throws MalformedURLException {
|
||||
final URL url = new URL("http://baeldung.com");
|
||||
assertEquals(-1, url.getPort());
|
||||
assertEquals(80, url.getDefaultPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenGetsPort_thenCorrect() throws MalformedURLException {
|
||||
final URL url = new URL("http://baeldung.com:8090");
|
||||
assertEquals(8090, url.getPort());
|
||||
assertEquals(80, url.getDefaultPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBaseUrl_whenCreatesRelativeUrl_thenCorrect() throws MalformedURLException {
|
||||
final URL baseUrl = new URL("http://baeldung.com");
|
||||
final URL relativeUrl = new URL(baseUrl, "a-guide-to-java-sockets");
|
||||
assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsoluteUrl_whenIgnoresBaseUrl_thenCorrect() throws MalformedURLException {
|
||||
final URL baseUrl = new URL("http://baeldung.com");
|
||||
final URL relativeUrl = new URL(baseUrl, "http://baeldung.com/a-guide-to-java-sockets");
|
||||
assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException {
|
||||
final String protocol = "http";
|
||||
final String host = "baeldung.com";
|
||||
final String file = "/guidelines.txt";
|
||||
final URL url = new URL(protocol, host, file);
|
||||
assertEquals("http://baeldung.com/guidelines.txt", url.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect2() throws MalformedURLException {
|
||||
final String protocol = "http";
|
||||
final String host = "baeldung.com";
|
||||
final String file = "/articles?topic=java&version=8";
|
||||
final URL url = new URL(protocol, host, file);
|
||||
assertEquals("http://baeldung.com/articles?topic=java&version=8", url.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrlComponentsWithPort_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException {
|
||||
final String protocol = "http";
|
||||
final String host = "baeldung.com";
|
||||
final int port = 9000;
|
||||
final String file = "/guidelines.txt";
|
||||
final URL url = new URL(protocol, host, port, file);
|
||||
assertEquals("http://baeldung.com:9000/guidelines.txt", url.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.forkjoin.CustomRecursiveAction;
|
||||
import com.baeldung.forkjoin.CustomRecursiveTask;
|
||||
import com.baeldung.forkjoin.util.PoolUtil;
|
||||
|
||||
public class Java8ForkJoinIntegrationTest {
|
||||
|
||||
private int[] arr;
|
||||
private CustomRecursiveTask customRecursiveTask;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
Random random = new Random();
|
||||
arr = new int[50];
|
||||
for (int i = 0; i < arr.length; i++) {
|
||||
arr[i] = random.nextInt(35);
|
||||
}
|
||||
customRecursiveTask = new CustomRecursiveTask(arr);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callPoolUtil_whenExistsAndExpectedType_thenCorrect() {
|
||||
ForkJoinPool forkJoinPool = PoolUtil.forkJoinPool;
|
||||
ForkJoinPool forkJoinPoolTwo = PoolUtil.forkJoinPool;
|
||||
|
||||
assertNotNull(forkJoinPool);
|
||||
assertEquals(2, forkJoinPool.getParallelism());
|
||||
assertEquals(forkJoinPool, forkJoinPoolTwo);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callCommonPool_whenExistsAndExpectedType_thenCorrect() {
|
||||
ForkJoinPool commonPool = ForkJoinPool.commonPool();
|
||||
ForkJoinPool commonPoolTwo = ForkJoinPool.commonPool();
|
||||
|
||||
assertNotNull(commonPool);
|
||||
assertEquals(commonPool, commonPoolTwo);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void executeRecursiveAction_whenExecuted_thenCorrect() {
|
||||
|
||||
CustomRecursiveAction myRecursiveAction = new CustomRecursiveAction("ddddffffgggghhhh");
|
||||
ForkJoinPool.commonPool().invoke(myRecursiveAction);
|
||||
|
||||
assertTrue(myRecursiveAction.isDone());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void executeRecursiveTask_whenExecuted_thenCorrect() {
|
||||
ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
|
||||
|
||||
forkJoinPool.execute(customRecursiveTask);
|
||||
int result = customRecursiveTask.join();
|
||||
assertTrue(customRecursiveTask.isDone());
|
||||
|
||||
forkJoinPool.submit(customRecursiveTask);
|
||||
int resultTwo = customRecursiveTask.join();
|
||||
assertTrue(customRecursiveTask.isDone());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void executeRecursiveTaskWithFJ_whenExecuted_thenCorrect() {
|
||||
CustomRecursiveTask customRecursiveTaskFirst = new CustomRecursiveTask(arr);
|
||||
CustomRecursiveTask customRecursiveTaskSecond = new CustomRecursiveTask(arr);
|
||||
CustomRecursiveTask customRecursiveTaskLast = new CustomRecursiveTask(arr);
|
||||
|
||||
customRecursiveTaskFirst.fork();
|
||||
customRecursiveTaskSecond.fork();
|
||||
customRecursiveTaskLast.fork();
|
||||
int result = 0;
|
||||
result += customRecursiveTaskLast.join();
|
||||
result += customRecursiveTaskSecond.join();
|
||||
result += customRecursiveTaskFirst.join();
|
||||
|
||||
assertTrue(customRecursiveTaskFirst.isDone());
|
||||
assertTrue(customRecursiveTaskSecond.isDone());
|
||||
assertTrue(customRecursiveTaskLast.isDone());
|
||||
assertTrue(result != 0);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
package com.baeldung.javanetworking.uriurl;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
|
||||
public class URIvsURLUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCreatingURIs_thenSameInfo() throws URISyntaxException {
|
||||
URI firstURI = new URI("somescheme://theuser:thepassword@someauthority:80/some/path?thequery#somefragment");
|
||||
URI secondURI = new URI("somescheme", "theuser:thepassword", "someuthority", 80, "/some/path", "thequery", "somefragment");
|
||||
|
||||
assertEquals(firstURI.getScheme(), secondURI.getScheme());
|
||||
assertEquals(firstURI.getPath(), secondURI.getPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingURLs_thenSameInfo() throws MalformedURLException {
|
||||
URL firstURL = new URL("http://theuser:thepassword@somehost:80/path/to/file?thequery#somefragment");
|
||||
URL secondURL = new URL("http", "somehost", 80, "/path/to/file");
|
||||
|
||||
assertEquals(firstURL.getHost(), secondURL.getHost());
|
||||
assertEquals(firstURL.getPath(), secondURL.getPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingURI_thenCorrect() {
|
||||
URI uri = URI.create("urn:isbn:1234567890");
|
||||
|
||||
assertNotNull(uri);
|
||||
}
|
||||
|
||||
@Test(expected = MalformedURLException.class)
|
||||
public void whenCreatingURLs_thenException() throws MalformedURLException {
|
||||
URL theURL = new URL("otherprotocol://somehost/path/to/file");
|
||||
|
||||
assertNotNull(theURL);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenObjects_whenConverting_thenCorrect() throws MalformedURLException, URISyntaxException {
|
||||
String aURIString = "http://somehost:80/path?thequery";
|
||||
URI uri = new URI(aURIString);
|
||||
URL url = new URL(aURIString);
|
||||
|
||||
URL toURL = uri.toURL();
|
||||
URI toURI = url.toURI();
|
||||
|
||||
assertNotNull(url);
|
||||
assertNotNull(uri);
|
||||
assertEquals(toURL.toString(), toURI.toString());
|
||||
}
|
||||
|
||||
@Test(expected = MalformedURLException.class)
|
||||
public void givenURI_whenConvertingToURL_thenException() throws MalformedURLException, URISyntaxException {
|
||||
URI uri = new URI("somescheme://someauthority/path?thequery");
|
||||
|
||||
URL url = uri.toURL();
|
||||
|
||||
assertNotNull(url);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenURL_whenGettingContents_thenCorrect() throws MalformedURLException, IOException {
|
||||
URL url = new URL("http://courses.baeldung.com");
|
||||
|
||||
String contents = IOUtils.toString(url.openStream());
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
package com.baeldung.javanetworking.uriurl.test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.FixMethodOrder;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.baeldung.javanetworking.uriurl.URLDemo;
|
||||
|
||||
@FixMethodOrder
|
||||
public class URIDemoLiveTest {
|
||||
private final Logger log = LoggerFactory.getLogger(URIDemoLiveTest.class);
|
||||
String URISTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
|
||||
// parsed locator
|
||||
static String URISCHEME = "https";
|
||||
String URISCHEMESPECIFIC;
|
||||
static String URIHOST = "wordpress.org";
|
||||
static String URIAUTHORITY = "wordpress.org:443";
|
||||
|
||||
static String URIPATH = "/support/topic/page-jumps-within-wordpress/";
|
||||
int URIPORT = 443;
|
||||
static int URIDEFAULTPORT = 443;
|
||||
static String URIQUERY = "replies=3";
|
||||
static String URIFRAGMENT = "post-2278484";
|
||||
static String URICOMPOUND = URISCHEME + "://" + URIHOST + ":" + URIDEFAULTPORT + URIPATH + "?" + URIQUERY + "#" + URIFRAGMENT;
|
||||
|
||||
static URI uri;
|
||||
URL url;
|
||||
BufferedReader in = null;
|
||||
String URIContent = "";
|
||||
|
||||
@BeforeClass
|
||||
public static void givenEmplyURL_whenInitializeURL_thenSuccess() throws URISyntaxException {
|
||||
uri = new URI(URICOMPOUND);
|
||||
}
|
||||
|
||||
// check parsed URL
|
||||
@Test
|
||||
public void givenURI_whenURIIsParsed_thenSuccess() {
|
||||
assertNotNull("URI is null", uri);
|
||||
assertEquals("URI string is not equal", uri.toString(), URISTRING);
|
||||
assertEquals("Scheme is not equal", uri.getScheme(), URISCHEME);
|
||||
assertEquals("Authority is not equal", uri.getAuthority(), URIAUTHORITY);
|
||||
assertEquals("Host string is not equal", uri.getHost(), URIHOST);
|
||||
assertEquals("Path string is not equal", uri.getPath(), URIPATH);
|
||||
assertEquals("Port number is not equal", uri.getPort(), URIPORT);
|
||||
assertEquals("Query string is not equal", uri.getQuery(), URIQUERY);
|
||||
assertEquals("Fragment string is not equal", uri.getFragment(), URIFRAGMENT);
|
||||
}
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
package com.baeldung.javanetworking.uriurl.test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.FixMethodOrder;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.baeldung.javanetworking.uriurl.URLDemo;
|
||||
|
||||
@FixMethodOrder
|
||||
public class URLDemoLiveTest {
|
||||
private final Logger log = LoggerFactory.getLogger(URLDemoLiveTest.class);
|
||||
static String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
|
||||
// parsed locator
|
||||
static String URLPROTOCOL = "https";
|
||||
String URLAUTHORITY = "wordpress.org:443";
|
||||
static String URLHOST = "wordpress.org";
|
||||
static String URLPATH = "/support/topic/page-jumps-within-wordpress/";
|
||||
String URLFILENAME = "/support/topic/page-jumps-within-wordpress/?replies=3";
|
||||
int URLPORT = 443;
|
||||
static int URLDEFAULTPORT = 443;
|
||||
static String URLQUERY = "replies=3";
|
||||
static String URLREFERENCE = "post-2278484";
|
||||
static String URLCOMPOUND = URLPROTOCOL + "://" + URLHOST + ":" + URLDEFAULTPORT + URLPATH + "?" + URLQUERY + "#" + URLREFERENCE;
|
||||
|
||||
static URL url;
|
||||
URLConnection urlConnection = null;
|
||||
HttpURLConnection connection = null;
|
||||
BufferedReader in = null;
|
||||
String urlContent = "";
|
||||
|
||||
@BeforeClass
|
||||
public static void givenEmplyURL_whenInitializeURL_thenSuccess() throws MalformedURLException {
|
||||
url = new URL(URLCOMPOUND);
|
||||
}
|
||||
|
||||
// check parsed URL
|
||||
@Test
|
||||
public void givenURL_whenURLIsParsed_thenSuccess() {
|
||||
assertNotNull("URL is null", url);
|
||||
assertEquals("URL string is not equal", url.toString(), URLSTRING);
|
||||
assertEquals("Protocol is not equal", url.getProtocol(), URLPROTOCOL);
|
||||
assertEquals("Authority is not equal", url.getAuthority(), URLAUTHORITY);
|
||||
assertEquals("Host string is not equal", url.getHost(), URLHOST);
|
||||
assertEquals("Path string is not equal", url.getPath(), URLPATH);
|
||||
assertEquals("File string is not equal", url.getFile(), URLFILENAME);
|
||||
assertEquals("Port number is not equal", url.getPort(), URLPORT);
|
||||
assertEquals("Default port number is not equal", url.getDefaultPort(), URLDEFAULTPORT);
|
||||
assertEquals("Query string is not equal", url.getQuery(), URLQUERY);
|
||||
assertEquals("Reference string is not equal", url.getRef(), URLREFERENCE);
|
||||
}
|
||||
|
||||
// Obtain the content from location
|
||||
@Test
|
||||
public void givenURL_whenOpenConnectionAndContentIsNotEmpty_thenSuccess() throws IOException {
|
||||
try {
|
||||
urlConnection = url.openConnection();
|
||||
} catch (IOException ex) {
|
||||
urlConnection = null;
|
||||
ex.printStackTrace();
|
||||
}
|
||||
assertNotNull("URL Connection is null", urlConnection);
|
||||
|
||||
connection = null;
|
||||
assertTrue("URLConnection is not HttpURLConnection", urlConnection instanceof HttpURLConnection);
|
||||
if (urlConnection instanceof HttpURLConnection) {
|
||||
connection = (HttpURLConnection) urlConnection;
|
||||
}
|
||||
assertNotNull("Connection is null", connection);
|
||||
|
||||
log.info(connection.getResponseCode() + " " + connection.getResponseMessage());
|
||||
|
||||
try {
|
||||
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||
} catch (IOException ex) {
|
||||
in = null;
|
||||
ex.printStackTrace();
|
||||
}
|
||||
assertNotNull("Input stream failed", in);
|
||||
|
||||
String current;
|
||||
try {
|
||||
while ((current = in.readLine()) != null) {
|
||||
urlContent += current;
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
urlContent = null;
|
||||
ex.printStackTrace();
|
||||
}
|
||||
assertNotNull("Content is null", urlContent);
|
||||
assertTrue("Content is empty", urlContent.length() > 0);
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package com.baeldung.networking.udp;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
public class UDPLiveTest {
|
||||
private EchoClient client;
|
||||
|
||||
@Before
|
||||
public void setup() throws IOException {
|
||||
new EchoServer().start();
|
||||
client = new EchoClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCanSendAndReceivePacket_thenCorrect1() {
|
||||
String echo = client.sendEcho("hello server");
|
||||
assertEquals("hello server", echo);
|
||||
echo = client.sendEcho("server is working");
|
||||
assertFalse(echo.equals("hello server"));
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
stopEchoServer();
|
||||
client.close();
|
||||
}
|
||||
|
||||
private void stopEchoServer() {
|
||||
client.sendEcho("end");
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package com.baeldung.networking.udp.broadcast;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class BroadcastLiveTest {
|
||||
private BroadcastingClient client;
|
||||
|
||||
@Test
|
||||
public void whenBroadcasting_thenDiscoverExpectedServers() throws Exception {
|
||||
int expectedServers = 4;
|
||||
initializeForExpectedServers(expectedServers);
|
||||
|
||||
int serversDiscovered = client.discoverServers("hello server");
|
||||
assertEquals(expectedServers, serversDiscovered);
|
||||
}
|
||||
|
||||
private void initializeForExpectedServers(int expectedServers) throws Exception {
|
||||
for (int i = 0; i < expectedServers; i++) {
|
||||
new BroadcastingEchoServer().start();
|
||||
}
|
||||
|
||||
client = new BroadcastingClient(expectedServers);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws IOException {
|
||||
stopEchoServer();
|
||||
client.close();
|
||||
}
|
||||
|
||||
private void stopEchoServer() throws IOException {
|
||||
client.discoverServers("end");
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package com.baeldung.networking.udp.multicast;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class MulticastLiveTest {
|
||||
private MulticastingClient client;
|
||||
|
||||
@Test
|
||||
public void whenBroadcasting_thenDiscoverExpectedServers() throws Exception {
|
||||
int expectedServers = 4;
|
||||
initializeForExpectedServers(expectedServers);
|
||||
|
||||
int serversDiscovered = client.discoverServers("hello server");
|
||||
assertEquals(expectedServers, serversDiscovered);
|
||||
}
|
||||
|
||||
private void initializeForExpectedServers(int expectedServers) throws Exception {
|
||||
for (int i = 0; i < expectedServers; i++) {
|
||||
new MulticastEchoServer().start();
|
||||
}
|
||||
|
||||
client = new MulticastingClient(expectedServers);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws IOException {
|
||||
stopEchoServer();
|
||||
client.close();
|
||||
}
|
||||
|
||||
private void stopEchoServer() throws IOException {
|
||||
client.discoverServers("end");
|
||||
}
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
package com.baeldung.thread.join;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Demonstrates Thread.join behavior.
|
||||
*
|
||||
*/
|
||||
public class ThreadJoinUnitTest {
|
||||
|
||||
final static Logger LOGGER = Logger.getLogger(ThreadJoinUnitTest.class.getName());
|
||||
|
||||
class SampleThread extends Thread {
|
||||
public int processingCount = 0;
|
||||
|
||||
SampleThread(int processingCount) {
|
||||
this.processingCount = processingCount;
|
||||
LOGGER.info("Thread " + this.getName() + " created");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
LOGGER.info("Thread " + this.getName() + " started");
|
||||
while (processingCount > 0) {
|
||||
try {
|
||||
Thread.sleep(1000); // Simulate some work being done by thread
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.info("Thread " + this.getName() + " interrupted.");
|
||||
}
|
||||
processingCount--;
|
||||
LOGGER.info("Inside Thread " + this.getName() + ", processingCount = " + processingCount);
|
||||
}
|
||||
LOGGER.info("Thread " + this.getName() + " exiting");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNewThread_whenJoinCalled_returnsImmediately() throws InterruptedException {
|
||||
Thread t1 = new SampleThread(0);
|
||||
LOGGER.info("Invoking join.");
|
||||
t1.join();
|
||||
LOGGER.info("Returned from join");
|
||||
LOGGER.info("Thread state is" + t1.getState());
|
||||
assertFalse(t1.isAlive());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStartedThread_whenJoinCalled_waitsTillCompletion()
|
||||
throws InterruptedException {
|
||||
Thread t2 = new SampleThread(1);
|
||||
t2.start();
|
||||
LOGGER.info("Invoking join.");
|
||||
t2.join();
|
||||
LOGGER.info("Returned from join");
|
||||
assertFalse(t2.isAlive());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStartedThread_whenTimedJoinCalled_waitsUntilTimedout()
|
||||
throws InterruptedException {
|
||||
Thread t3 = new SampleThread(10);
|
||||
t3.start();
|
||||
t3.join(1000);
|
||||
assertTrue(t3.isAlive());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
public void givenThreadTerminated_checkForEffect_notGuaranteed()
|
||||
throws InterruptedException {
|
||||
SampleThread t4 = new SampleThread(10);
|
||||
t4.start();
|
||||
//not guaranteed to stop even if t4 finishes.
|
||||
do {
|
||||
|
||||
} while (t4.processingCount > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJoinWithTerminatedThread_checkForEffect_guaranteed()
|
||||
throws InterruptedException {
|
||||
SampleThread t4 = new SampleThread(10);
|
||||
t4.start();
|
||||
do {
|
||||
t4.join(100);
|
||||
} while (t4.processingCount > 0);
|
||||
}
|
||||
|
||||
}
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
package com.baeldung.threadlocalrandom;
|
||||
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ThreadLocalRandomIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenUsingThreadLocalRandom_whenGeneratingRandomIntBounded_thenCorrect() {
|
||||
int leftLimit = 1;
|
||||
int rightLimit = 100;
|
||||
int generatedInt = ThreadLocalRandom.current().nextInt(leftLimit, rightLimit);
|
||||
|
||||
assertTrue(generatedInt < rightLimit && generatedInt >= leftLimit);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingThreadLocalRandom_whenGeneratingRandomIntUnbounded_thenCorrect() {
|
||||
int generatedInt = ThreadLocalRandom.current().nextInt();
|
||||
|
||||
assertTrue(generatedInt < Integer.MAX_VALUE && generatedInt >= Integer.MIN_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingThreadLocalRandom_whenGeneratingRandomLongBounded_thenCorrect() {
|
||||
long leftLimit = 1L;
|
||||
long rightLimit = 100L;
|
||||
long generatedLong = ThreadLocalRandom.current().nextLong(leftLimit, rightLimit);
|
||||
|
||||
assertTrue(generatedLong < rightLimit && generatedLong >= leftLimit);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingThreadLocalRandom_whenGeneratingRandomLongUnbounded_thenCorrect() {
|
||||
long generatedInt = ThreadLocalRandom.current().nextLong();
|
||||
|
||||
assertTrue(generatedInt < Long.MAX_VALUE && generatedInt >= Long.MIN_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingThreadLocalRandom_whenGeneratingRandomDoubleBounded_thenCorrect() {
|
||||
double leftLimit = 1D;
|
||||
double rightLimit = 100D;
|
||||
double generatedInt = ThreadLocalRandom.current().nextDouble(leftLimit, rightLimit);
|
||||
|
||||
assertTrue(generatedInt < rightLimit && generatedInt >= leftLimit);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingThreadLocalRandom_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
|
||||
double generatedInt = ThreadLocalRandom.current().nextDouble();
|
||||
|
||||
assertTrue(generatedInt < Double.MAX_VALUE && generatedInt >= Double.MIN_VALUE);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void givenUsingThreadLocalRandom_whenSettingSeed_thenThrowUnsupportedOperationException() {
|
||||
ThreadLocalRandom.current().setSeed(0l);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user