Java – How to download web page from internet?

A simple Java source code to download a web page from the internet. JavaDownloadWebPage.java package com.mkyong; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; public class JavaDownloadWebPage { public static void main(String[] args) throws IOException { String result = downloadWebPage("https://mkyong.com"); System.out.println(result); } private static String downloadWebPage(String url) throws IOException { StringBuilder …

Read more

How to escape HTML in Java

In Java, we can use Apache commons-text, StringEscapeUtils.escapeHtml4(str) to escape HTML characters. pom.xml <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> <version>1.8</version> </dependency> JavaEscapeHtmlExample.java package com.mkyong.html; // make sure import the correct commons-text package import org.apache.commons.text.StringEscapeUtils; // @deprecated as of 3.6, use commons-text StringEscapeUtils instead //import org.apache.commons.lang3.StringEscapeUtils; public class JavaEscapeHtmlExample { public static void main(String[] args) { String html = …

Read more

Java – How to get all links from a web page?

A jsoup HTML parser example to show you how to parse and get all HTML hyperlinks from a web page: pom.xml <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.12.1</version> </dependency> JsoupFindLinkSample.java package com.mkyong; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class JsoupFindLinkSample { public static void main(String[] args) throws IOException { …

Read more

Java – Pretty Print HTML

In Java, we can use jsoup, a Java HTML parser, to parse a HTML code and pretty print it. pom.xml <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.12.1</version> </dependency> JavaPrettyPrintHTML.java package com.mkyong; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; public class JavaPrettyPrintHTML { public static void main(String[] args) { String html = "<html><body><h1>hello world</h1></body></html>"; System.out.println(html); // original Document doc = Jsoup.parse(html); // …

Read more

Java – How to read input from console using Scanner

This example shows you how to read input from the console using the standard java.util.Scanner class. JavaScanner.java package com.mkyong.io; import java.util.Scanner; public class JavaScanner { public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { System.out.print("Please enter your name: "); String input = scanner.nextLine(); System.out.println("name : " + input); System.out.print("Please enter your …

Read more

Java – How to read input from System.console()

In Java, we can use System.console() to read input from the console. JavaSample.java package com.mkyong.io; import java.io.Console; public class JavaSample { public static void main(String[] args) { // jdk 1.6 Console console = System.console(); System.out.print("Enter your name: "); String name = console.readLine(); System.out.println("Name is: " + name); System.out.print("Enter your password: "); // Reads a password …

Read more

Java – Server returned HTTP response code: 403 for URL

A simple Java program tries to download something from the internet: try (InputStream is = new URL(url).openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is))) { while ((line = br.readLine()) != null) { result.append(line); } } But, some web servers return the following HTTP 403 errors? Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 …

Read more

Java – How to print name 1000 times without looping?

Here’s a Java example to print a name 1000 times without looping or recursion, instead, use String concatenation and simple math. Just for fun. JavaNoLoop.java package com.mkyong.samples; public class JavaNoLoop { public static void main(String[] args) { String s1 = "Mkyong\n"; String s3 = s1 + s1 + s1; String s10 = s3 + s3 …

Read more

JUnit 5 + AssertJ examples

In this article, we will show you how to write test assertions with AssertJ. P.S Tested with JUnit 5.5.2 and AssertJ 3.14.0 pom.xml <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.5.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>3.14.0</version> <scope>test</scope> </dependency> 1. JUnit 5 assertions to AssertJ It’s easy to convert JUnit 5 assertions to AssetJ, see the following syntax: JUnit …

Read more

JUnit 5 Display Names

In JUnit 5, we can use @DisplayName to declare custom display names for test classes and test methods. P.S Tested with JUnit 5.5.2 1. @DisplayName 1.1 Default name of test classes and methods. DisplayNameTest.java package com.mkyong.display; import org.junit.jupiter.api.Test; public class DisplayNameTest { @Test void test_spaces_ok() { } @Test void test_spaces_fail() { } } Output +– …

Read more

JUnit 5 Timeouts Examples

In JUnit 5, we can use @Timeout to fail a test if the execution time exceeds a given duration. P.S Tested with JUnit 5.5.2 1. @Timeout TimeOutExample1.java package com.mkyong.timeout; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import java.util.concurrent.TimeUnit; public class TimeOutExample1 { // timed out after 5 seconds @BeforeEach @Timeout(5) void setUpDB() throws InterruptedException { //TimeUnit.SECONDS.sleep(10); …

Read more

JUnit 5 Expected Exception

In JUnit 5, we can use assertThrows to assert an exception is thrown. P.S Tested with JUnit 5.5.2 1. Unchecked Exception 1.1 JUnit example of catching a runtime exception. ExceptionExample1.java package com.mkyong.assertions; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class ExceptionExample1 { @Test void test_exception() { Exception exception = assertThrows( ArithmeticException.class, () -> divide(1, 0)); assertEquals("/ …

Read more

JUnit 5 Parameterized Tests

This article shows you how to run a test multiple times with different arguments, so-called ‘Parameterized Tests’, let see the following ways to provide arguments to the test: @ValueSource @EnumSource @MethodSource @CsvSource @CsvFileSource @ArgumentsSource We need junit-jupiter-params to support parameterized tests. pom.xml <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.5.2</version> <scope>test</scope> </dependency> <!– Parameterized Tests –> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-params</artifactId> …

Read more

JUnit 5 ConsoleLauncher examples

This article shows you how to use the JUnit 5 ConsoleLauncher to run tests from a command line. Tested with JUnit 5.5.2 junit-platform-console-standalone 1.5.2 1. Download JAR To run tests from the command line, we can download the junit-platform-console-standalone.jar from Maven central repository manually. P.S This example is using version 1.5.2. https://repo1.maven.org/maven2/org/junit/platform/junit-platform-console-standalone/1.5.2/ 2. Usages Usually, …

Read more

JUnit 5 Repeated Tests

This article shows you how to use the JUnit 5 @RepeatedTest to repeat a test a specified number of times. P.S Tested with JUnit 5.5.2 1. @RepeatedTest 1.1 The @RepeatedTest test method is just like a regular @Test method, the same life cycle. RepeatedSample1Test.java package com.mkyong.repeated; import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.assertEquals; public class RepeatedSample1Test { …

Read more

JUnit 5 Nested Tests

This article shows you how to use the JUnit 5 @Nested annotation to group tests together. P.S Tested with JUnit 5.5.2 Why nested tests? It’s optional to create nested tests. Still, it helps to create hierarchical contexts to structure the related unit tests together; in short, it helps to keep the tests clean and readable. …

Read more

JUnit 5 Test Execution Order

This article shows you how to control the JUnit 5 test execution order via the following MethodOrderer classes: Alphanumeric OrderAnnotation Random Custom Order P.S Tested with JUnit 5.5.2 1. Alphanumeric 1.1 It sorts test methods alphanumerically. MethodAlphanumericTest.java package com.mkyong.order; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import static org.junit.jupiter.api.Assertions.assertEquals; @TestMethodOrder(MethodOrderer.Alphanumeric.class) public class MethodAlphanumericTest { @Test void …

Read more

JUnit 5 Tagging and Filtering, @Tag examples

This article shows you how to use the JUnit 5 tagging and filtering via the @Tag annotation. Tested with JUnit 5.5.2 Maven 3.6.0 Gradle 5.6.2 1. @Tag A simple tagging for demo. TagMethodTest.java package com.mkyong.tags; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @Tag("branch-20") public class TagMethodTest { @Test @Tag("feature-168") void test1Plus1() { assertEquals(2, 1 + …

Read more

JUnit 5 – How to disable tests?

JUnit 5 @Disabled example to disable tests on the entire test class or individual test methods. P.S Tested with JUnit 5.5.2 Note You can also disable tests based on conditions. 1. @Disabled on Method 1.1 The test method testCustomerServiceGet is disabled. DisabledMethodTest.java package com.mkyong.disable; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class DisabledMethodTest { …

Read more

JUnit 5 Conditional Test Examples

This article shows you how to use JUnit 5 to enable or disable tests based on conditions. P.S Tested with JUnit 5.5.2 1. Operating System 1.1 Enabled or disabled tests based on a particular operating system via @EnabledOnOs and @DisabledOnOs annotations. OperatingSystemTest.java package com.mkyong.conditional; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.EnabledOnOs; import org.junit.jupiter.api.condition.OS; public class OperatingSystemTest …

Read more

Maven error – invalid target release: 1.11

Maven compiles and hits the following fatal error messages: Terminal mvn compile Fatal error compiling: error: invalid target release: 1.11 pom.xml <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.11</source> <target>1.11</target> </configuration> </plugin> Solution For maven-compiler-plugin, the correct JDK version is 1.8, 1.9, 1.10, 10, 11, 12 … 17 … pom.xml <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <source>11</source> <target>11</target> …

Read more

Maven – The POM for maven-compiler-plugin:jar:3.8.1 is missing

Maven compiles and hits the following maven-compiler-plugin error? The POM for org.apache.maven.plugins:maven-compiler-plugin:jar:3.8.1 is missing, no dependency information available pom.xml <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> Terminal > mvn compile [INFO] Scanning for projects… [INFO] [INFO] ——————–< com.mkyong.core:junit5-maven >——————– [INFO] Building junit5-maven 1.0 [INFO] ——————————–[ jar ]——————————— [WARNING] The POM for org.apache.maven.plugins:maven-compiler-plugin:jar:3.8.1 is …

Read more

Java – How to enable the preview language features?

This article shows you how to use –enable-preview to enable the preview language features in Java 12, 13 and above. Note Read this JEP 12: Preview Language and VM Features P.S All preview features are disabled by default. On JDK 12: # compile javac Example.java // Do not enable any preview features javac –release 12 …

Read more

Java Ternary Operator examples

This example shows you how to write Java ternary operator. Here’s the syntax condition ? get_this_if_true : get_this_if_false Java ternary operator syntax (n > 18) ? true : false; (n == true) ? 1 : 0; (n == null) ? n.getValue() : 0; 1. Java ternary operator 1.1 Java example without ternary operator. JavaExample1.java package …

Read more

Python – How to split string into a dict

Few Python examples to show you how to split a string into a dictionary. 1.1 Split a string into a dict. #!/usr/bin/python str = "key1=value1;key2=value2;key3=value3" d = dict(x.split("=") for x in str.split(";")) for k, v in d.items(): print(k, v) Output key1 value1 key2 value2 key3 value3 1.2 Convert two list into a dict. #!/usr/bin/python str1 …

Read more

Java – How to search a string in a List?

In Java, we can combine a normal loop and .contains(), .startsWith() or .matches() to search for a string in ArrayList. JavaExample1.java package com.mkyong.test; import java.util.ArrayList; import java.util.List; public class JavaExample1 { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("Java"); list.add("Kotlin"); list.add("Clojure"); list.add("Groovy"); list.add("Scala"); List<String> result = new ArrayList<>(); for (String s …

Read more

Java 11 HttpClient Examples

This article shows you how to use the new Java 11 HttpClient APIs to send HTTP GET/POST requests, and some frequent used examples. HttpClient httpClient = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .followRedirects(HttpClient.Redirect.NORMAL) .connectTimeout(Duration.ofSeconds(20)) .proxy(ProxySelector.of(new InetSocketAddress("proxy.yourcompany.com", 80))) .authenticator(Authenticator.getDefault()) .build(); 1. Synchronous Example This example sends a GET request to https://httpbin.org/get, and print out the response header, status code, and …

Read more

OkHttp – How to send HTTP requests

This article shows you how to use the OkHttp library to send an HTTP GET/POST requests and some frequent used examples. P.S Tested with OkHttp 4.2.2 pom.xml <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.2.2</version> </dependency> 1. Synchronous Get Request OkHttpExample1.java package com.mkyong.http; import okhttp3.Headers; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import java.io.IOException; public class OkHttpExample1 { // only …

Read more

Apache HttpClient Basic Authentication Examples

This article shows you how to use Apache HttpClient to perform an HTTP basic authentication. P.S Tested with HttpClient 4.5.10 pom.xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.10</version> </dependency> Start a simple Spring Security WebApp providing HTTP basic authentication, and test it with the HttpClient 1. Basic Authentication The key is to configure CredentialsProvider and pass it to …

Read more

Python Ternary Conditional Operator

This article shows you how to write Python ternary operator, also called conditional expressions. <expression1> if <condition> else <expression2> expression1 will be evaluated if the condition is true, otherwise expression2 will be evaluated. 1. Ternary Operator 1.1 This example will print whether a number is odd or even. n = 5 print("Even") if n % …

Read more

Java 13 – Switch Expressions

In Java 13, the JEP 354: Switch Expressions extends the previous Java 12 Switch Expressions by adding a new yield keyword to return a value from the switch expression. P.S Switch expressions are a preview feature and are disabled by default. Note This is a standard feature in Java 14. 1. No more value breaks! …

Read more

What is new in Java 13

Java 13 reached General Availability on 17 September 2019, download Java 13 here or this openJDK archived. Java 13 features. 1. JEP 350 Dynamic CDS Archives 2. JEP 351 ZGC: Uncommit Unused Memory 3. JEP-353 Reimplement the Legacy Socket API 4. JEP-354 Switch Expressions (Preview) 5. JEP-355 Text Blocks (Preview) Java 13 developer features. Switch …

Read more

How to change the IntelliJ IDEA JDK version?

This article shows you how to update the IntelliJ IDEA to use the new JDK 13. 1. On the menu, clicks File -> Project Structure 2. Platform Settings -> SDKs, add and point to the JDK 13 installed folder. 3. Project Settings -> Project, change both Project SDK and Project language level to JDK 13. …

Read more

Python – Get the last element of a list

In Python, we can use index -1 to get the last element of a list. #!/usr/bin/python nums = [1, 2, 3, 4, 5] print(nums[-1]) print(nums[-2]) print(nums[-3]) print(nums[-4]) print(nums[-5]) print(nums[0]) print(nums[1]) print(nums[2]) print(nums[3]) print(nums[4]) Output 5 4 3 2 1 1 2 3 4 5 Yet another example. #!/usr/bin/python # getting list of nums from the …

Read more

JUnit 5 + Gradle examples

This article shows you how to add JUnit 5 in a Gradle project. Technologies used: Gradle 5.4.1 Java 8 JUnit 5.5.2 1. Gradle + JUnit 5 1. Add the JUni 5 jupiter engine, and define the useJUnitPlatform() like the following: gradle.build plugins { id ‘java’ id ‘eclipse’ // optional, for Eclipse project id ‘idea’ // …

Read more