Tag Archives: java8

Notes for migrating Oracle jdk8 to openjdk11

Java 8 upgrade Java 11

Because orcle stopped the free follow-up security update of jdk8, the decision to upgrade JDK to 11 was adopted after the decision.

Specific version:

current version

java -version
java version "1.8.0_201"
Java(TM) SE Runtime Environment (build 1.8.0_201-b09)
Java HotSpot(TM) 64-Bit Server VM (build 25.201-b09, mixed mode)

Target version

java -version
openjdk version "11.0.2" 2019-01-15
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.2+9)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.2+9, mixed mode)

Upgrade process:

Download and install jdk11

JDK download
the selection of jdk11 version is: adptopen JDK 11.0.2 + 9
1 https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/tag/jdk-11.0.2+9
Download
https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.2%2B9/OpenJDK11U-jdk_ x64_ windows_ hotspot_ 11.0.2_ 9. Zip
latest or more versions: GitHub view all the released versions of open JDK (change the environment variable to jdk11, if you don’t start a java program such as Tomcat on the command line, you can skip this step, generally you don’t need to use ide on Windows)

Add jdk11: Ctrl Shift Alt + s — & gt; SDKs –> + Select JDK — & gt; Make sure that the compiler of the specified project in the directory is jdk11: Ctrl Shift Alt + S – & gt; Project ——> The project SDK and project SDK level are changed to the newly added 11, and the rest remain unchanged (the project is controlled by Maven’s pom.xml)
update the project compiler to jdk11pom.xml. See the following for the detailed process

Pom.xml transformation

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <release>11</release>
    </configuration>
</plugin> 

This plug-in is used to compile the source code; The configuration in it represents the use of 11 to compile

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>2.22.0</version>
    <configuration>
        <argLine>
            --illegal-access=permit
        </argLine>
    </configuration>
</plugin>

Surefire plug-in is used to execute unit test of an application in the test phase of Maven build life cycle. It will produce two different forms of test results

<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.23.1-GA</version>
</dependency>

The questions are listed as follows:

if the method provided in this paper can not be solved, you can try the following </ H6>
    1. clean the whole project/project and recompile it with Java 11
    1. in idea:
    1. build — build artifacts — all — clean
    1. build — build artifacts — all — build delete the corresponding components under Tomcat/webapps (clear the cache) </ OL>

Question 1

Symptom
resource cannot be resolved to a type
javax. Annotation. Resource
cause
resource class cannot be found; Java 11 has been removed as an alternative solution

Solutions

Add in pom.xml:

<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.1</version>
</dependency>

Reference from stack overflow


Question 2

E rror:java : symbol not found
symbol: class resource
location: package javax.annotation

Solution:

        <dependency>
			<groupId>javax.annotation</groupId>
			<artifactId>javax.annotation-api</artifactId>
			<version>1.3.1</version>
		</dependency>   


Question 3

JAXB (Java. XML. Bind) problems are as follows:

Error:(10, 33) java: Package javax.xml.bind.annotation does not exist
Error:(24, 2) java: Symbol not found
  Symbol: Class XmlRootElement
Error:(28, 6) java: Symbol not found
  Symbol: Class XmlElement
  Location: Class com.xxx.xxx.xxxx.xxx.entity.xxx
  .....

Reasons
openjdk11 has deleted some packages. The following is an announcement:

Removal Of Java EE Modules
There used to be a lot of code in Java SE that was actually related to Java EE. It ended up in six modules that were deprecated for removal in Java 9 and removed from Java 11. Here are the removed technologies and packages:)
 
 
the JavaBeans Activation Framework (JAF) in javax.activation
CORBA in the packages javax.activity, javax.rmi, javax.rmi.CORBA, and org.omg.*
the Java Transaction API (JTA) in the package javax.transaction
JAXB in the packages javax.xml.bind.*   ############ This package is the cause of the problem
JAX-WS in the packages javax.jws, javax.jws.soap, javax.xml.soap, and javax.xml.ws.*
Commons Annotation in the package javax.annotation

The corresponding version is as follows:

<!-- Java 6 = JAXB version 2.0   -->
<!-- Java 7 = JAXB version 2.2.3 -->
<!-- Java 8 = JAXB version 2.2.8 -->
<!-- Java 9 = JAXB version 2.3.0 -->

Note: before the project is which version of JDK to introduce which version, for example, I was java8, so I want to introduce the JAXB version of 2.2.8

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.2.8</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-core</artifactId>
    <version>2.2.8</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.2.8</version>
</dependency>

Reference from stack overflow


Question 4

Warning: (54,44) newinstance() in Java: Java. Lang. class is obsolete

Solution:

Check the source code of newinstance() in open JDK 11 Java. Lang. class. Some comments are as follows

    /* can be replaced by
     *
     * <pre>{@code
     * clazz.getDeclaredConstructor().newInstance()
     *}</pre>
     */

It can be replaced by the above method

clazz.newInstance();

replace with

clazz.getDeclaredConstructor().newInstance();

Question 5
After starting Tomcat
Artifact upm-web:war: Error during artifact deployment. See server log for details.
View the logs as follows.

19-Mar-2019 09:50:31.061 [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.StandardContext.listenerStart Error configuring application listener of class [com.xxx.xxx.xxx.WebContextLoaderListener]
 java.lang.UnsupportedClassVersionError: com/xxx/xxx/xxx/WebContextLoaderListener has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0 (unable to load class [com.xxx.xxx.xxx.WebContextLoaderListener])
	at org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2377)
	at org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:846)
	...
19-Mar-2019 09:50:31.061 [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.StandardContext.listenerStart Skipped installing application listeners due to previous error(s)

Reason
according to the description of exception information (unsupported version of XXX. Class), it means that the current class version to be loaded is 55 (Java 11), which cannot be loaded. The current Java runtime supports 52 (Java 8) versions of. Class files at most
where the java version corresponds to the class version as follows:

J2SE 11 = 55 (0x33 hex),
J2SE 10 = 54 (0x33 hex),
J2SE 9 = 53 (0x33 hex),
J2SE 8 = 52 (0x33 hex),
J2SE 7 = 51 (0x33 hex),
J2SE 6.0 = 50 (0x32 hex),
J2SE 5.0 = 49 (0x31 hex),
JDK 1.4 = 48 (0x30 hex),
JDK 1.3 = 47 (0x2F hex),
JDK 1.2 = 46 (0x2E hex),
JDK 1.1 = 45 (0x2D hex).

It can be seen that the actual cause of the problem is that the program compiled by java8 (Tomcat) calls the program compiled by java11.

Solution:

Using higher version Tomcat 9

Detailed process:

Go to Tomcat official website to download tomcat9, unzip the downloaded zip (modify the Tomcat environment variable and do not use it in the command line, which can be skipped). Modify the Tomcat set in IDE to the newly installed tomcat9. Take idea as an example:

Run edit configurations on the top right — configure on the right side of application server… Click on the top left + add the file location of newly installed tomcat9, OK, confirm to save the modification below, change JRE to newly added JDK 11, save the settings (note whether there are errors in the prompt area below) and run to check whether the configuration is correct


The above is my JDK version upgrade problems. Welcome to add!

Java 8 Stream – Read a file line by line

In Java 8, you can use Files. lines to read file as Stream.

c://lines.txt – A simple text file for testing

line1
line2
line3
line4
line5

1. Java 8 Read File + Stream

TestReadFile.java

package com.mkyong.java8;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class TestReadFile {

	public static void main(String args[]) {

		String fileName = "c://lines.txt";

		//read file into stream, try-with-resources
		try (Stream<String> stream = Files.lines(Paths.get(fileName))) {

			stream.forEach(System.out::println);

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

Output

line1
line2
line3
line4
line5

2. Java 8 Read File + Stream + Extra
This example shows you how to use Stream to filter content, convert the entire content to upper case and return it as a List.

TestReadFile2.java

package com.mkyong.java8;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TestReadFile2 {

	public static void main(String args[]) {

		String fileName = "c://lines.txt";
		List<String> list = new ArrayList<>();

		try (Stream<String> stream = Files.lines(Paths.get(fileName))) {

			//1. filter line 3
			//2. convert all content to upper case
			//3. convert it into a List
			list = stream
					.filter(line -> !line.startsWith("line3"))
					.map(String::toUpperCase)
					.collect(Collectors.toList());

		} catch (IOException e) {
			e.printStackTrace();
		}

		list.forEach(System.out::println);

	}

}

Output

LINE1
LINE2
LINE4
LINE5

3. BufferedReader + Stream
A new method lines() has been added since 1.8, it lets BufferedReader returns content as Stream.

TestReadFile3.java

package com.mkyong.java8;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class TestReadFile3{

	public static void main(String args[]) {

		String fileName = "c://lines.txt";
		List<String> list = new ArrayList<>();

		try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName))) {

			//br returns as stream and convert it into a List
			list = br.lines().collect(Collectors.toList());

		} catch (IOException e) {
			e.printStackTrace();
		}

		list.forEach(System.out::println);

	}

}

Output

line1
line2
line3
line4
line5

4. Classic BufferedReader And Scanner
Enough of Java 8 and Stream, let revisit the classic BufferedReader (JDK1.1) and Scanner (JDK1.5) examples to read a file line by line, it is working still, just developers are moving toward Stream.
4.1 BufferedReader + try-with-resources example.

TestReadFile4.java

package com.mkyong.core;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TestReadFile4{

	public static void main(String args[]) {

		String fileName = "c://lines.txt";

		try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {

			String line;
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

4.2 Scanner + try-with-resources example.

TestReadFile5.java

package com.mkyong.core;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class TestReadFile5 {

	public static void main(String args[]) {

		String fileName = "c://lines.txt";

		try (Scanner scanner = new Scanner(new File(fileName))) {

			while (scanner.hasNext()){
				System.out.println(scanner.nextLine());
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

References

    Java 8 File.lines()Java 8 StreamJava BufferedReader

link: https://www.mkyong.com/java8/java-8-stream-read-a-file-line-by-line/

Local date time conversion in java8

note : LocalDateTime is

1. LocalDateTime converted to custom time format string

public static String getDateTimeAsString(LocalDateTime localDateTime, String format) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
    return localDateTime.format(formatter);
}

2. Convert long type timestamp to LocalDateTime

public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {
    Instant instant = Instant.ofEpochMilli(timestamp);
    ZoneId zone = ZoneId.systemDefault();
    return LocalDateTime.ofInstant(instant, zone);
}

3. LocalDateTime to long type timestamp

public static long getTimestampOfDateTime(LocalDateTime localDateTime) {
    ZoneId zone = ZoneId.systemDefault();
    Instant instant = localDateTime.atZone(zone).toInstant();
    return instant.toEpochMilli();
}

4. LocalDateTime

converts a time string to a custom time format

public static LocalDateTime parseStringToDateTime(String time, String format) {
    DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
    return LocalDateTime.parse(time, df);
}