Java 9 new features (#660)

* initial push for core-java-9 tutorials

* Fixed Maven build with experimental java 9 Maven compiler plug-in. Minor
code changes

* Running maven build and changes to some of tests.

* Fixed maven build and modifications ot some tests

* Removing unnecessary files
This commit is contained in:
anton-k11 2016-09-04 13:30:35 +03:00 committed by Grzegorz Piwowarek
parent 98ffbc1f37
commit c68e1bfbc8
16 changed files with 659 additions and 0 deletions

13
core-java-9/.gitignore vendored Normal file
View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

5
core-java-9/README.md Normal file
View File

@ -0,0 +1,5 @@
=========
## Core Java 9 Examples
http://inprogress.baeldung.com/java-9-new-features/

102
core-java-9/pom.xml Normal file
View File

@ -0,0 +1,102 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java9</artifactId>
<version>0.2-SNAPSHOT</version>
<name>core-java9</name>
<pluginRepositories>
<pluginRepository>
<id>apache.snapshots</id>
<url>http://repository.apache.org/snapshots/</url>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-9</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.9</source>
<target>1.9</target>
<verbose>true</verbose>
<!-- <executable>C:\develop\jdks\jdk-9_ea122\bin\javac</executable>
<compilerVersion>1.9</compilerVersion> -->
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</build>
<properties>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.0.13</logback.version>
<!-- maven plugins -->
<!--
<maven-war-plugin.version>2.6</maven-war-plugin.version>
maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version> -->
<maven-compiler-plugin.version>3.6-jigsaw-SNAPSHOT</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
</properties>
</project>

13
core-java-9/src/main/java/.gitignore vendored Normal file
View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -0,0 +1,23 @@
package com.baeldung.java9.language;
public interface PrivateInterface {
private static String staticPrivate() {
return "static private";
}
private String instancePrivate() {
return "instance private";
}
public default void check(){
String result = staticPrivate();
if (!result.equals("static private"))
throw new AssertionError("Incorrect result for static private interface method");
PrivateInterface pvt = new PrivateInterface() {
};
result = pvt.instancePrivate();
if (!result.equals("instance private"))
throw new AssertionError("Incorrect result for instance private interface method");
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.java9.process;
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.stream.Stream;
public class ProcessUtils {
public static String getClassPath(){
String cp = System.getProperty("java.class.path");
System.out.println("ClassPath is "+cp);
return cp;
}
public static File getJavaCmd() throws IOException{
String javaHome = System.getProperty("java.home");
File javaCmd;
if(System.getProperty("os.name").startsWith("Win")){
javaCmd = new File(javaHome, "bin/java.exe");
}else{
javaCmd = new File(javaHome, "bin/java");
}
if(javaCmd.canExecute()){
return javaCmd;
}else{
throw new UnsupportedOperationException(javaCmd.getCanonicalPath() + " is not executable");
}
}
public static String getMainClass(){
return System.getProperty("sun.java.command");
}
public static String getSystemProperties(){
StringBuilder sb = new StringBuilder();
System.getProperties().forEach((s1, s2) -> sb.append(s1 +" - "+ s2) );
return sb.toString();
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.java9.process;
import java.util.Optional;
public class ServiceMain {
public static void main(String[] args) throws InterruptedException {
ProcessHandle thisProcess = ProcessHandle.current();
long pid = thisProcess.getPid();
Optional<String[]> opArgs = Optional.ofNullable(args);
String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command"));
for (int i = 0; i < 10000; i++) {
System.out.println("Process " + procName + " with ID " + pid + " is running!");
Thread.sleep(10000);
}
}
}

View File

@ -0,0 +1,16 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<!-- <logger name="org.springframework" level="WARN" /> -->
<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
</configuration>

View File

@ -0,0 +1,48 @@
package com.baeldung.java9;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import java.awt.Image;
import java.awt.image.BaseMultiResolutionImage;
import java.awt.image.BufferedImage;
import java.awt.image.MultiResolutionImage;
import java.util.List;
import org.junit.Test;
public class MultiResultionImageTest {
@Test
public void baseMultiResImageTest() {
int baseIndex = 1;
int length = 4;
BufferedImage[] resolutionVariants = new BufferedImage[length];
for (int i = 0; i < length; i++) {
resolutionVariants[i] = createImage(i);
}
MultiResolutionImage bmrImage = new BaseMultiResolutionImage(baseIndex, resolutionVariants);
List<Image> rvImageList = bmrImage.getResolutionVariants();
assertEquals("MultiResoltion Image shoudl contain the same number of resolution variants!", rvImageList.size(), length);
for (int i = 0; i < length; i++) {
int imageSize = getSize(i);
Image testRVImage = bmrImage.getResolutionVariant(imageSize, imageSize);
assertSame("Images should be the same", testRVImage, resolutionVariants[i]);
}
}
private static int getSize(int i) {
return 8 * (i + 1);
}
private static BufferedImage createImage(int i) {
return new BufferedImage(getSize(i), getSize(i),
BufferedImage.TYPE_INT_RGB);
}
}

View File

@ -0,0 +1,126 @@
package com.baeldung.java9.httpclient;
import static java.net.HttpURLConnection.HTTP_OK;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import org.junit.Before;
import org.junit.Test;
public class SimpleHttpRequestsTest {
private URI httpURI;
@Before
public void init() throws URISyntaxException {
httpURI = new URI("http://www.baeldung.com/");
}
@Test
public void quickGet() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.create( httpURI ).GET();
HttpResponse response = request.response();
int responseStatusCode = response.statusCode();
String responseBody = response.body(HttpResponse.asString());
assertTrue("Get response status code is bigger then 400", responseStatusCode < 400);
}
@Test
public void asynchronousGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException{
HttpRequest request = HttpRequest.create(httpURI).GET();
long before = System.currentTimeMillis();
CompletableFuture<HttpResponse> futureResponse = request.responseAsync();
futureResponse.thenAccept( response -> {
String responseBody = response.body(HttpResponse.asString());
});
HttpResponse resp = futureResponse.get();
HttpHeaders hs = resp.headers();
assertTrue("There should be more then 1 header.", hs.map().size() >1);
}
@Test
public void postMehtod() throws URISyntaxException, IOException, InterruptedException {
HttpRequest.Builder requestBuilder = HttpRequest.create(httpURI);
requestBuilder.body(HttpRequest.fromString("param1=foo,param2=bar")).followRedirects(HttpClient.Redirect.SECURE);
HttpRequest request = requestBuilder.POST();
HttpResponse response = request.response();
int statusCode = response.statusCode();
assertTrue("HTTP return code", statusCode == HTTP_OK);
}
@Test
public void configureHttpClient() throws NoSuchAlgorithmException, URISyntaxException, IOException, InterruptedException{
CookieManager cManager = new CookieManager();
cManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
SSLParameters sslParam = new SSLParameters (new String[] { "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" }, new String[] { "TLSv1.2" });
HttpClient.Builder hcBuilder = HttpClient.create();
hcBuilder.cookieManager(cManager).sslContext(SSLContext.getDefault()).sslParameters(sslParam);
HttpClient httpClient = hcBuilder.build();
HttpRequest.Builder reqBuilder = httpClient.request(new URI("https://www.facebook.com"));
HttpRequest request = reqBuilder.followRedirects(HttpClient.Redirect.ALWAYS).GET();
HttpResponse response = request.response();
int statusCode = response.statusCode();
assertTrue("HTTP return code", statusCode == HTTP_OK);
}
SSLParameters getDefaultSSLParameters() throws NoSuchAlgorithmException{
SSLParameters sslP1 = SSLContext.getDefault().getSupportedSSLParameters();
String [] proto = sslP1.getApplicationProtocols();
String [] cifers = sslP1.getCipherSuites();
System.out.println(printStringArr(proto));
System.out.println(printStringArr(cifers));
return sslP1;
}
String printStringArr(String ... args ){
if(args == null){
return null;
}
StringBuilder sb = new StringBuilder();
for (String s : args){
sb.append(s);
sb.append("\n");
}
return sb.toString();
}
String printHeaders(HttpHeaders h){
if(h == null){
return null;
}
StringBuilder sb = new StringBuilder();
Map<String, List<String>> hMap = h.map();
for(String k : hMap.keySet()){
sb.append(k).append(":");
List<String> l = hMap.get(k);
if( l != null ){
l.forEach( s -> { sb.append(s).append(","); } );
}
sb.append("\n");
}
return sb.toString();
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.java9.language;
import org.junit.Test;
public class DiamondTest {
static class FooClass<X> {
FooClass(X x) {
}
<Z> FooClass(X x, Z z) {
}
}
@Test
public void diamondTest() {
FooClass<Integer> fc = new FooClass<>(1) {
};
FooClass<? extends Integer> fc0 = new FooClass<>(1) {
};
FooClass<?> fc1 = new FooClass<>(1) {
};
FooClass<? super Integer> fc2 = new FooClass<>(1) {
};
FooClass<Integer> fc3 = new FooClass<>(1, "") {
};
FooClass<? extends Integer> fc4 = new FooClass<>(1, "") {
};
FooClass<?> fc5 = new FooClass<>(1, "") {
};
FooClass<? super Integer> fc6 = new FooClass<>(1, "") {
};
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.java9.language;
import com.baeldung.java9.language.PrivateInterface;
import org.junit.Test;
public class PrivateInterfaceTest {
@Test
public void test() {
PrivateInterface piClass = new PrivateInterface() {
};
piClass.check();
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.java9.language;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class TryWithResourcesTest {
static int closeCount = 0;
static class MyAutoCloseable implements AutoCloseable{
final FinalWrapper finalWrapper = new FinalWrapper();
public void close() {
closeCount++;
}
static class FinalWrapper {
public final AutoCloseable finalCloseable = new AutoCloseable() {
@Override
public void close() throws Exception {
closeCount++;
}
};
}
}
@Test
public void tryWithResourcesTest() {
MyAutoCloseable mac = new MyAutoCloseable();
try (mac) {
assertEquals("Expected and Actual does not match", 0, closeCount);
}
try (mac.finalWrapper.finalCloseable) {
assertEquals("Expected and Actual does not match", 1, closeCount);
} catch (Exception ex) {
}
try (new MyAutoCloseable() { }.finalWrapper.finalCloseable) {
assertEquals("Expected and Actual does not match", 2, closeCount);
} catch (Exception ex) {
}
try ((closeCount > 0 ? mac : new MyAutoCloseable()).finalWrapper.finalCloseable) {
assertEquals("Expected and Actual does not match", 3, closeCount);
} catch (Exception ex) {
}
try {
throw new CloseableException();
} catch (CloseableException ex) {
try (ex) {
assertEquals("Expected and Actual does not match", 4, closeCount);
}
}
assertEquals("Expected and Actual does not match", 5, closeCount);
}
static class CloseableException extends Exception implements AutoCloseable {
@Override
public void close() {
closeCount++;
}
}
}

View File

@ -0,0 +1,112 @@
package com.baeldung.java9.process;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
import junit.framework.Assert;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ProcessApi {
@Before
public void init() {
}
@Test
public void processInfoExample()throws NoSuchAlgorithmException{
ProcessHandle self = ProcessHandle.current();
long PID = self.getPid();
ProcessHandle.Info procInfo = self.info();
Optional<String[]> args = procInfo.arguments();
Optional<String> cmd = procInfo.commandLine();
Optional<Instant> startTime = procInfo.startInstant();
Optional<Duration> cpuUsage = procInfo.totalCpuDuration();
waistCPU();
System.out.println("Args "+ args);
System.out.println("Command " +cmd.orElse("EmptyCmd"));
System.out.println("Start time: "+ startTime.get().toString());
System.out.println(cpuUsage.get().toMillis());
Stream<ProcessHandle> allProc = ProcessHandle.current().children();
allProc.forEach(p -> {
System.out.println("Proc "+ p.getPid());
});
}
@Test
public void createAndDestroyProcess() throws IOException, InterruptedException{
int numberOfChildProcesses = 5;
for(int i=0; i < numberOfChildProcesses; i++){
createNewJVM(ServiceMain.class, i).getPid();
}
Stream<ProcessHandle> childProc = ProcessHandle.current().children();
assertEquals( childProc.count(), numberOfChildProcesses);
childProc = ProcessHandle.current().children();
childProc.forEach(processHandle -> {
assertTrue("Process "+ processHandle.getPid() +" should be alive!", processHandle.isAlive());
CompletableFuture<ProcessHandle> onProcExit = processHandle.onExit();
onProcExit.thenAccept(procHandle -> {
System.out.println("Process with PID "+ procHandle.getPid() + " has stopped");
});
});
Thread.sleep(10000);
childProc = ProcessHandle.current().children();
childProc.forEach(procHandle -> {
assertTrue("Could not kill process "+procHandle.getPid(), procHandle.destroy());
});
Thread.sleep(5000);
childProc = ProcessHandle.current().children();
childProc.forEach(procHandle -> {
assertFalse("Process "+ procHandle.getPid() +" should not be alive!", procHandle.isAlive());
});
}
private Process createNewJVM(Class mainClass, int number) throws IOException{
ArrayList<String> cmdParams = new ArrayList<String>(5);
cmdParams.add(ProcessUtils.getJavaCmd().getAbsolutePath());
cmdParams.add("-cp");
cmdParams.add(ProcessUtils.getClassPath());
cmdParams.add(mainClass.getName());
cmdParams.add("Service "+ number);
ProcessBuilder myService = new ProcessBuilder(cmdParams);
myService.inheritIO();
return myService.start();
}
private void waistCPU() throws NoSuchAlgorithmException{
ArrayList<Integer> randArr = new ArrayList<Integer>(4096);
SecureRandom sr = SecureRandom.getInstanceStrong();
Duration somecpu = Duration.ofMillis(4200L);
Instant end = Instant.now().plus(somecpu);
while (Instant.now().isBefore(end)) {
//System.out.println(sr.nextInt());
randArr.add( sr.nextInt() );
}
}
}

View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -22,6 +22,7 @@
<module>cdi</module>
<module>core-java</module>
<module>core-java-8</module>
<module>core-java-9</module>
<module>couchbase-sdk-intro</module>
<module>couchbase-sdk-spring-service</module>