initial push for core-java-9 tutorials

This commit is contained in:
i032048 2016-07-28 18:03:48 +03:00
parent b53e46246b
commit 7c0af73604
18 changed files with 767 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/

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

@ -0,0 +1,138 @@
<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.1-SNAPSHOT</version>
<name>core-java9</name>
<dependencies>
<!-- utils
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
-->
<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>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</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>
<!-- various -->
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<!-- <maven-compiler-plugin.version>3.6-jigsaw-SNAPSHOT</maven-compiler-plugin.version> -->
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.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,48 @@
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;
import org.junit.Before;
import org.junit.Test;
import junit.framework.Assert;
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,10 @@
@echo off
REM C:\develop\jdks\jdk-9_ea123\bin\javac
REM
REM C:\develop\jdks\jdk1.8.0_45\bin\javac
@echo on
C:\develop\jdks\jdk-9_ea123\bin\javac -Werror -cp C:\Users\i032048\.m2\repository\org\hamcrest\hamcrest-library\1.3\hamcrest-library-1.3.jar;C:\Users\i032048\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Users\i032048\.m2\repository\junit\junit\4.4\junit-4.4.jar;C:\develop\git-repos\baeldung-tutorials\core-java-9\target\test-classes;C:\develop\git-repos\baeldung-tutorials\core-java-9\src\test %1
@echo off
REM com\baeldung\java9\language\TryWithResourcesTest.java

View File

@ -0,0 +1,22 @@
package com.baeldung.java9;
import com.baeldung.java9.language.PrivateInterface;
import com.baeldung.java9.language.TryWithResourcesTest;
public class Main {
public static void main(String args[]){
PrivateInterface pi =new PrivateInterface() {
};
pi.check();
}
// public static void main(String[] args) throws Exception {
// MultiResultionImageTest mri = new MultiResultionImageTest();
// mri.baseMultiResImageTest();
//
// TryWithResourcesTest tt = new TryWithResourcesTest();
// // tt.test1();
// }
}

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,14 @@
package com.baeldung.java9.httpclient;
public class Main {
public static void main(String[] args) throws Exception {
SimpleHttpRequests shr = new SimpleHttpRequests();
shr.quickGet();
shr.PostMehtod();
shr.configureHttpClient();
shr.asyncGet();
}
}

View File

@ -0,0 +1,146 @@
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 SimpleHttpRequests {
// private URI httpURI =
@Before
public void init() {
}
@Test
public void quickGet() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.create(new URI("http://localhost:8080")).GET();
HttpResponse response = request.response();
System.out.println(printHeaders(response.headers()));
String responseBody = response.body(HttpResponse.asString());
assertTrue("Get response body size", responseBody.length() > 10);
}
@Test
public void asyncGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException{
HttpRequest request = HttpRequest.create(new URI("http://localhost:8080")).GET();
long before = System.currentTimeMillis();
CompletableFuture<HttpResponse> futureResponse = request.responseAsync();
futureResponse.thenAccept( response -> {
HttpHeaders hs = response.headers();
System.out.println(Thread.currentThread()+"\nHeaders:----------------------\n"+ printHeaders(hs));
String responseBody = response.body(HttpResponse.asString());
//System.out.println(responseBody);
});
long after = System.currentTimeMillis();
System.out.println(Thread.currentThread()+" waits "+ (after - before));
assertTrue("Thread waits", (after - before) < 1500);
futureResponse.join();
// Calculate some other thing in this Thread
//HttpResponse response = futureResponse.get();
long afterAfter = System.currentTimeMillis();
System.out.println(Thread.currentThread()+ "(afterAfter - before)"+ (afterAfter - before));
//String responseBody = response.body(HttpResponse.asString());
//HttpHeaders hs = response.headers();
//System.out.println(responseBody);
// assertTrue("Get response body size", responseBody.length() > 10);
}
@Test
public void PostMehtod() throws URISyntaxException, IOException, InterruptedException {
HttpRequest.Builder requestBuilder = HttpRequest.create(new URI("http://localhost:8080"));
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://localhost:8443"));
HttpRequest request = reqBuilder.followRedirects(HttpClient.Redirect.ALWAYS).GET();
HttpResponse response = request.response();
int statusCode = response.statusCode();
System.out.println(response.body(HttpResponse.asString()));
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,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,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,18 @@
package com.baeldung.java9.process;
import java.security.NoSuchAlgorithmException;
public class Main {
public static void main(String[] args) throws Exception {
ProcessApi procApi = new ProcessApi();
procApi.createAndDestroyProcess();
procApi.processInfoExample();
Thread.sleep(40200);
System.out.println("_______END!___________");
}
}

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