Python support in IntelliJ IDEA

This article shows you how to make IntelliJ IDEA support and run Python. P.S Make sure Python SDK is installed, later we need to link this Python SDK to IntelliJ IDEA. 1. Plugins In IntelliJ IDEA. File -> Settings -> Plugins. 2. Python Community Edition Clicks Marketplace, search python, install the Python Community Edition by …

Read more

Java AES encryption and decryption

The Advanced Encryption Standard (AES, Rijndael) is a block cipher encryption and decryption algorithm, the most used encryption algorithm in the worldwide. The AES processes block of 128 bits using a secret key of 128, 192, or 256 bits. This article shows you a few of Java AES encryption and decryption examples: AES String encryption …

Read more

JUnit 5 Tutorials

JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage P.S JUnit 5 requires Java 8 (or higher) at runtime 1. JUnit 5 + Maven See this full JUnit 5 + Maven examples. pom.xml <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.5.2</version> <scope>test</scope> </dependency> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M3</version> </plugin> </plugins> </build> P.S The maven-surefire-plugin must be …

Read more

What is docker –rm option

On Docker, –rm option means automatically remove the container when it exits. $ docker run –rm <container_id> Done 🙂 Please read on to understand more about –rm. 1. Remove a container On Docker, the container is an instance of an image, and we can create multiple containers from an image. If the container is exited …

Read more

How to list containers in Docker?

In Docker, we can use docker ps to show all running containers, docker ps -a to show all running and stopped containers. Here are some of the commonly used examples: Terminal # common $ docker ps // show only running containers $ docker ps -a // show all containers (running and stopped or exited) # …

Read more

What is new in Java 12

Java 12 reached General Availability on 19 March 2019, download Java 12 here or this openJDK archived. Java 12 features. 1. JEP 189: Shenandoah: A Low-Pause-Time Garbage Collector (Experimental) 2. JEP 230: Microbenchmark Suite 3. JEP 325: Switch Expressions (Preview) 4. JEP 334: JVM Constants API 5. JEP 340: One AArch64 Port, Not Two 6. …

Read more

How to exit JShell in Java?

To exit JShell, type /exit. I stuck in JShell for minutes, commands like exit, ctrl + c, end, q!, q, quit all failed, the correct syntax to quit or exit the JShell is /exit. Terminal C:\Users\mkyong>jshell | Welcome to JShell — Version 11.0.1 | For an introduction type: /help intro jshell> exit | Error: | …

Read more

What is new in Java 11

Java 11 reached General Availability on 25 September 2018, this is a Long Term Support (LTS) version, download Java 11 here or this openJDK archived. Java 11 features. 1. JEP 181: Nest-Based Access Control 2. JEP 309: Dynamic Class-File Constants 3. JEP 315: Improve Aarch64 Intrinsics 4. JEP 318: Epsilon: A No-Op Garbage Collector (Experimental) …

Read more

Java SSLSocket TLS 1.3 example

This Java 11 JEP 332 adds support for TLS 1.3 protocol. SSLSocket + TLS 1.3 An SSLSocket client with TLS1.3 protocol and TLS_AES_128_GCM_SHA256 stream cipher, to send a request to https://google.com and print the response. JavaTLS13.java package com.mkyong.java11.jep332; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import java.io.*; // Java 11 public class JavaTLS13 { private static final String[] …

Read more

How to generate serialVersionUID in Intellij IDEA

In IntelliJ IDEA, we need to enable this auto-generate serialVersionUID option manually. P.S Tested with IntelliJ IDEA 2019.3.4, it should work the same in other versions. Intellij IDEA Settings File -> Settings -> Editor -> Inspections -> Java -> Serialization issues: Find serialization class without serialVersionUID and check it. Back to the editor, clicks on …

Read more

Java – How to generate a random 12 bytes?

In Java, we can use SecureRandom.nextBytes(byte[] bytes) to generate a user-specified number of random bytes. This SecureRandom is a cryptographically secure random number generator (RNG). 1. Random 12 bytes (96 bits) 1.1 Generates a random 12 bytes (96 bits) nonce. HelloCryptoApp.java package com.mkyong.crypto; import java.security.SecureRandom; public class HelloCryptoApp { public static void main(String[] args) { …

Read more

Java 11 – ChaCha20-Poly1305 encryption examples

This article shows you how to encrypt and decrypt a message with the ChaCha20-Poly1305 algorithm, defined in RFC 7539. P.S The ChaCha20-Poly1305 encryption algorithm is available at Java 11. 1. FAQs Some commonly asked questions: 1.1 What is ChaCha20-Poly1305? ChaCha20-Poly1305 means the ChaCha20 (encryption and decryption algorithm) running in AEAD mode with the Poly1305 authenticator. …

Read more

Docker run but no output?

docker run a container, but it displayed nothing, no output, no error? docker ps shows no running container? Terminal $ docker run -d -p 80:8080 -p 443:8443 -t markdownhtml:1.1 8eba06d44bf236109cf65b7b93842e9c898370cac1740aa2bab557a0fc8e52b9 $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES Solution Most of the time, the container hit an error and exited automatically. We …

Read more

Java – How to join and split byte arrays, byte[]

In this example, we will show you how to join and split byte arrays with ByteBuffer and System.arraycopy. ByteBuffer public static byte[] joinByteArray(byte[] byte1, byte[] byte2) { return ByteBuffer.allocate(byte1.length + byte2.length) .put(byte1) .put(byte2) .array(); } public static void splitByteArray(byte[] input) { ByteBuffer bb = ByteBuffer.wrap(input); byte[] cipher = new byte[8]; byte[] nonce = new byte[4]; …

Read more

Java – Convert byte[] to int and vice versa

In Java, we can use ByteBuffer to convert int to byte[] and vice versa. int to byte[] int num = 1; // int need 4 bytes, default ByteOrder.BIG_ENDIAN byte[] result = ByteBuffer.allocate(4).putInt(number).array(); byte[] to int byte[] byteArray = new byte[] {00, 00, 00, 01}; int num = ByteBuffer.wrap(bytes).getInt(); 1. int to byte[] This Java example …

Read more

Java Serialization and Deserialization Examples

In Java, Serialization means converting Java objects into a byte stream; Deserialization means converting the serialized object’s byte stream back to the original Java object. Table of contents. 1. Hello World Java Serialization 2. java.io.NotSerializableException 3. What is serialVersionUID? 4. What is transient? 5. Serialize Object to File 6. Why need Serialization in Java? 7. …

Read more

Java 11 – Java Flight Recorder

Java Flight Recorder (JFR) is a Java profiling tool that used to monitor and diagnose a running Java application, it collects data about the running environment, JVM and Java application and dumps the recorded data into a .jfr file, and we can use Java Mission Control (JMC) to analyze and visualize the .jfr file. Tested …

Read more

Python – How to convert int to a binary string?

In Python, we can use bin() or format() to convert an integer into a binary string representation. print(bin(1)) # 0b1 print(bin(-1)) # -0b1 print(bin(10)) # 0b1010 print(bin(-10)) # -0b1010 print("{0:b}".format(10)) # 1010 print("{0:#b}".format(10)) # 0b1010 , with 0b prefix print("{0:b}".format(10).zfill(8)) # 00001010 , pad zero, show 8 bits print(format(10, "b")) # 1010 print(format(10, "#b")) # …

Read more

Docker – exec: "bash": executable file not found in $PATH

If bash shell is not working, try sh. Terminal $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 3d1588519433 markdownhtml:0.1 "java -jar app.jar" About an hour ago Up About an hour 0.0.0.0:80->8080/tcp gracious_haibt $ docker exec -it 3d1588519433 bash OCI runtime exec failed: exec failed: container_linux.go:349: starting container process caused "exec: \"bash\": executable …

Read more

Java – What is transient fields?

In Java, transient fields are excluded in the serialization process. In short, when we save an object into a file (serialization), all transient fields are ignored. 1. POJO + transient Review the following Person class; the salary field is transient. public class Person implements Serializable { private static final long serialVersionUID = 1L; private String …

Read more

Java – jcmd not found?

The jcmd is available at the JDK/bin, not JRE. Make sure the installed Java is JDK, not JRE. Let review the following example, try to use jcmd to enable Java Flight Recorder inside a docker container. 1. DockerFile A simple Dokcerfile. Dockerfile FROM adoptopenjdk/openjdk11:alpine-jre ARG JAR_FILE=target/markdown.jar WORKDIR /opt/app COPY ${JAR_FILE} app.jar ENTRYPOINT ["java","-jar","app.jar"] 2. Docker …

Read more

Nginx + WordPress, 404 errors for all pages?

We installed Nginx, MariaDB, PHP, and WordPress on Mac OS. The homepage is displayed fine, but all other pages are returning 404 errors? Tested with Nginx 1.17.9 WordPress 5.4 PHP 7.4 Review the current Nginx + WordPress integration. nginx.conf server { listen 8080; server_name localhost; root /usr/local/var/www/wordpress; location / { index index.html index.htm index.php; } …

Read more

Python MD5 Hashing Example

The MD5, defined in RFC 1321, is a hash algorithm to turn inputs into a fixed 128-bit (16 bytes) length of the hash value. Note MD5 is not collision-resistant – Two different inputs may producing the same hash value. Read this MD5 vulnerabilities. In Python, we can use hashlib.md5() to generate a MD5 hash value …

Read more

Java 11 – Nest-Based Access Control

This JEP 181: Nest-Based Access Control, supports private access within nest members directly, no more via an auto-generated bridge method access$000. Furthermore, new nest APIs for validation and allowed private reflection access within nest members. P.S No need to change the code, it is a Java compiler’s optimization to remove the bridge method access. 1. …

Read more

Java 8 – How to convert Iterator to Stream

In Java 8, we can use StreamSupport.stream to convert an Iterator into a Stream. // Iterator -> Spliterators -> Stream Stream<String> stream = StreamSupport.stream( Spliterators.spliteratorUnknownSize( iterator, Spliterator.ORDERED) , false); Review the StreamSupport.stream method signature, it accepts a Spliterator. StreamSupport.java public static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel) { Objects.requireNonNull(spliterator); return new ReferencePipeline.Head<>(spliterator, StreamOpFlag.fromCharacteristics(spliterator), parallel); } …

Read more

Java Iterator examples

A few of Java Iterator and ListIterator examples. 1. Iterator 1.1 Get Iterator from a List or Set, and loop over it. JavaIteratorExample1a.java package com.mkyong; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class JavaIteratorExample1a { public static void main(String[] args) { /* Set<Integer> set = new HashSet<>(); set.add(1); set.add(2); set.add(3); set.add(4); set.add(5); Iterator<Integer> iterator = …

Read more

What is new in Java 14

Java 14 reached General Availability on 17 March 2020, download Java 14 here. Java 14 features. 1. JEP 305: Pattern Matching for instanceof (Preview) 2. JEP 343: Packaging Tool (Incubator) 3. JEP 345: NUMA-Aware Memory Allocation for G1 4. JEP 349: JFR Event Streaming 5. JEP 352: Non-Volatile Mapped Byte Buffers 6. JEP 358: Helpful …

Read more

Java List throws UnsupportedOperationException

Typically, we use Arrays.asList or the new Java 9 List.of to create a List. However, both methods return a fixed size or immutable List, it means we can’t modify it, else it throws UnsupportedOperationException. JavaListExample.java package com.mkyong; import java.util.Arrays; import java.util.List; public class JavaListExample { public static void main(String[] args) { // immutable list, cant …

Read more

What is java.util.Arrays$ArrayList?

The java.util.Arrays$ArrayList is a nested class inside the Arrays class. It is a fixed size or immutable list backed by an array. Arrays.java public static <T> List<T> asList(T… a) { return new ArrayList<>(a); } /** * @serial include */ private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable { private static final long serialVersionUID = …

Read more

Java 8 – Find duplicate elements in a Stream

This article shows you three algorithms to find duplicate elements in a Stream. Set.add() Collectors.groupingBy Collections.frequency At the end of the article, we use the JMH benchmark to test which one is the fastest algorithm. 1. Filter & Set.add() The Set.add() returns false if the element was already in the set; let see the benchmark …

Read more

Java 8 – Get the last element of a Stream?

In Java 8, we can use reduce or skip to get the last element of a Stream. 1. Stream.reduce Java8Example1.java package com.mkyong; import java.util.Arrays; import java.util.List; public class Java8Example1 { public static void main(String[] args) { List<String> list = Arrays.asList("node", "java", "c++", "react", "javascript"); String result = list.stream().reduce((first, second) -> second).orElse("no last element"); System.out.println(result); } …

Read more

Is Comparator a function interface, but it has two abstract methods?

Review the Comparator class; it has two abstract methods, why it can be a function interface? Comparator.java package java.util; @FunctionalInterface public interface Comparator<T> { // abstract method int compare(T o1, T o2); // abstract method boolean equals(Object obj); // few default and static methods } Definition of function interface Conceptually, a functional interface has exactly …

Read more

Java – How to display % in String.Format?

This example shows you how to display a percentage % in String.format. JavaStringFormat1.java package com.mkyong; public class JavaStringFormat1 { public static void main(String[] args) { String result = String.format("%d%", 100); System.out.println(result); } } Output Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = ‘%’ at java.base/java.util.Formatter.checkText(Formatter.java:2732) at java.base/java.util.Formatter.parse(Formatter.java:2718) at java.base/java.util.Formatter.format(Formatter.java:2655) at java.base/java.util.Formatter.format(Formatter.java:2609) at java.base/java.lang.String.format(String.java:2897) Solution To display …

Read more

How to pad a String in Java?

This article shows you how to use the JDK1.5 String.format() and Apache Common Lang to left or right pad a String in Java. 1. String.format By default, the String.format() fills extra with spaces \u0020. Normally, we use replace() to pad with other chars, but it will replace the spaces in between the given string. JavaPadString1.java …

Read more