Merge remote-tracking branch 'upstream/master' into craedel-enterprise-patterns/front-controller
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
@@ -0,0 +1,5 @@
|
||||
=========
|
||||
|
||||
## Core Java 9 Examples
|
||||
|
||||
http://inprogress.baeldung.com/java-9-new-features/
|
||||
@@ -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>
|
||||
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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>
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class Java9OptionalsStreamTest {
|
||||
|
||||
private static List<Optional<String>> listOfOptionals = Arrays.asList(Optional.empty(), Optional.of("foo"), Optional.empty(), Optional.of("bar"));
|
||||
|
||||
@Test
|
||||
public void filterOutPresentOptionalsWithFilter() {
|
||||
assertEquals(4, listOfOptionals.size());
|
||||
|
||||
List<String> filteredList = listOfOptionals.stream()
|
||||
.filter(Optional::isPresent)
|
||||
.map(Optional::get)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(2, filteredList.size());
|
||||
assertEquals("foo", filteredList.get(0));
|
||||
assertEquals("bar", filteredList.get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterOutPresentOptionalsWithFlatMap() {
|
||||
assertEquals(4, listOfOptionals.size());
|
||||
|
||||
List<String> filteredList = listOfOptionals.stream()
|
||||
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
|
||||
.collect(Collectors.toList());
|
||||
assertEquals(2, filteredList.size());
|
||||
|
||||
assertEquals("foo", filteredList.get(0));
|
||||
assertEquals("bar", filteredList.get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterOutPresentOptionalsWithJava9() {
|
||||
assertEquals(4, listOfOptionals.size());
|
||||
|
||||
List<String> filteredList = listOfOptionals.stream()
|
||||
.flatMap(Optional::stream)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(2, filteredList.size());
|
||||
assertEquals("foo", filteredList.get(0));
|
||||
assertEquals("bar", filteredList.get(1));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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, "") {
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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++;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -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() );
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.java.reflection;
|
||||
|
||||
public abstract class Animal implements Eating {
|
||||
|
||||
public static final String CATEGORY = "domestic";
|
||||
|
||||
private String name;
|
||||
|
||||
public Animal(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
protected abstract String getSound();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.java.reflection;
|
||||
|
||||
public class Bird extends Animal {
|
||||
private boolean walks;
|
||||
|
||||
public Bird() {
|
||||
super("bird");
|
||||
}
|
||||
|
||||
public Bird(String name, boolean walks) {
|
||||
super(name);
|
||||
setWalks(walks);
|
||||
}
|
||||
|
||||
public Bird(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String eats() {
|
||||
return "grains";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getSound() {
|
||||
return "chaps";
|
||||
}
|
||||
|
||||
public boolean walks() {
|
||||
return walks;
|
||||
}
|
||||
|
||||
public void setWalks(boolean walks) {
|
||||
this.walks = walks;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.java.reflection;
|
||||
|
||||
public interface Eating {
|
||||
String eats();
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.java.reflection;
|
||||
|
||||
public class Goat extends Animal implements Locomotion {
|
||||
|
||||
public Goat(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getSound() {
|
||||
return "bleat";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLocomotion() {
|
||||
return "walks";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String eats() {
|
||||
return "grass";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.java.reflection;
|
||||
|
||||
public interface Locomotion {
|
||||
String getLocomotion();
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.java.reflection;
|
||||
|
||||
public class Person {
|
||||
private String name;
|
||||
private int age;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,63 +1,65 @@
|
||||
package org.baeldung.java.collections;
|
||||
|
||||
import com.google.common.collect.Sets;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.*;
|
||||
|
||||
import static java.util.stream.Collectors.*;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.core.IsNot.not;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ArrayListTest {
|
||||
|
||||
List<String> stringsToSearch;
|
||||
private List<String> stringsToSearch;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
List<String> xs = LongStream.range(0, 16)
|
||||
.boxed()
|
||||
.map(Long::toHexString)
|
||||
.collect(Collectors.toList());
|
||||
stringsToSearch = new ArrayList<>(xs);
|
||||
stringsToSearch.addAll(xs);
|
||||
List<String> list = LongStream.range(0, 16)
|
||||
.boxed()
|
||||
.map(Long::toHexString)
|
||||
.collect(toCollection(ArrayList::new));
|
||||
stringsToSearch = new ArrayList<>(list);
|
||||
stringsToSearch.addAll(list);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNewArrayList_whenCheckCapacity_thenDefaultValue() {
|
||||
List<String> xs = new ArrayList<>();
|
||||
assertTrue(xs.isEmpty());
|
||||
List<String> list = new ArrayList<>();
|
||||
assertTrue(list.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCollection_whenProvideItToArrayListCtor_thenArrayListIsPopulatedWithItsElements() {
|
||||
Collection<Integer> numbers =
|
||||
IntStream.range(0, 10).boxed().collect(Collectors.toSet());
|
||||
IntStream.range(0, 10).boxed().collect(toSet());
|
||||
|
||||
List<Integer> xs = new ArrayList<>(numbers);
|
||||
assertEquals(10, xs.size());
|
||||
assertTrue(numbers.containsAll(xs));
|
||||
List<Integer> list = new ArrayList<>(numbers);
|
||||
assertEquals(10, list.size());
|
||||
assertTrue(numbers.containsAll(list));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenAddToArrayList_thenIsAdded() {
|
||||
List<Long> xs = new ArrayList<>();
|
||||
List<Long> list = new ArrayList<>();
|
||||
|
||||
xs.add(1L);
|
||||
xs.add(2L);
|
||||
xs.add(1, 3L);
|
||||
list.add(1L);
|
||||
list.add(2L);
|
||||
list.add(1, 3L);
|
||||
|
||||
assertThat(Arrays.asList(1L, 3L, 2L), equalTo(xs));
|
||||
assertThat(Arrays.asList(1L, 3L, 2L), equalTo(list));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCollection_whenAddToArrayList_thenIsAdded() {
|
||||
List<Long> xs = new ArrayList<>(Arrays.asList(1L, 2L, 3L));
|
||||
Collection<Long> ys = LongStream.range(4, 10).boxed().collect(Collectors.toList());
|
||||
xs.addAll(0, ys);
|
||||
List<Long> list = new ArrayList<>(Arrays.asList(1L, 2L, 3L));
|
||||
LongStream.range(4, 10).boxed()
|
||||
.collect(collectingAndThen(toCollection(ArrayList::new), ys -> list.addAll(0, ys)));
|
||||
|
||||
assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(xs));
|
||||
assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(list));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -87,9 +89,9 @@ public class ArrayListTest {
|
||||
Set<String> matchingStrings = new HashSet<>(Arrays.asList("a", "c", "9"));
|
||||
|
||||
List<String> result = stringsToSearch
|
||||
.stream()
|
||||
.filter(matchingStrings::contains)
|
||||
.collect(Collectors.toList());
|
||||
.stream()
|
||||
.filter(matchingStrings::contains)
|
||||
.collect(toCollection(ArrayList::new));
|
||||
|
||||
assertEquals(6, result.size());
|
||||
}
|
||||
@@ -104,37 +106,33 @@ public class ArrayListTest {
|
||||
|
||||
@Test
|
||||
public void givenIndex_whenRemove_thenCorrectElementRemoved() {
|
||||
List<Integer> xs = new ArrayList<>(
|
||||
IntStream.range(0, 10).boxed().collect(Collectors.toList())
|
||||
);
|
||||
Collections.reverse(xs);
|
||||
List<Integer> list = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
|
||||
Collections.reverse(list);
|
||||
|
||||
xs.remove(0);
|
||||
assertThat(xs.get(0), equalTo(8));
|
||||
list.remove(0);
|
||||
assertThat(list.get(0), equalTo(8));
|
||||
|
||||
xs.remove(Integer.valueOf(0));
|
||||
assertFalse(xs.contains(0));
|
||||
list.remove(Integer.valueOf(0));
|
||||
assertFalse(list.contains(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListIterator_whenReverseTraversal_thenRetrieveElementsInOppositeOrder() {
|
||||
List<Integer> xs = new ArrayList<>(
|
||||
IntStream.range(0, 10).boxed().collect(Collectors.toList())
|
||||
);
|
||||
ListIterator<Integer> it = xs.listIterator(xs.size());
|
||||
List<Integer> result = new ArrayList<>(xs.size());
|
||||
List<Integer> list = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
|
||||
ListIterator<Integer> it = list.listIterator(list.size());
|
||||
List<Integer> result = new ArrayList<>(list.size());
|
||||
while (it.hasPrevious()) {
|
||||
result.add(it.previous());
|
||||
}
|
||||
|
||||
Collections.reverse(xs);
|
||||
assertThat(result, equalTo(xs));
|
||||
Collections.reverse(list);
|
||||
assertThat(result, equalTo(list));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCondition_whenIterateArrayList_thenRemoveAllElementsSatisfyingCondition() {
|
||||
Set<String> matchingStrings
|
||||
= new HashSet<>(Arrays.asList("a", "b", "c", "d", "e", "f"));
|
||||
= Sets.newHashSet("a", "b", "c", "d", "e", "f");
|
||||
|
||||
Iterator<String> it = stringsToSearch.iterator();
|
||||
while (it.hasNext()) {
|
||||
|
||||
@@ -5,63 +5,59 @@ import java.util.HashSet;
|
||||
|
||||
public class ComplexClass {
|
||||
|
||||
private ArrayList<?> genericArrayList;
|
||||
private HashSet<Integer> integerHashSet;
|
||||
private ArrayList<?> genericArrayList;
|
||||
private HashSet<Integer> integerHashSet;
|
||||
|
||||
public ComplexClass(ArrayList<?> genericArrayList,
|
||||
HashSet<Integer> integerHashSet) {
|
||||
super();
|
||||
this.genericArrayList = genericArrayList;
|
||||
this.integerHashSet = integerHashSet;
|
||||
}
|
||||
public ComplexClass(ArrayList<?> genericArrayList, HashSet<Integer> integerHashSet) {
|
||||
super();
|
||||
this.genericArrayList = genericArrayList;
|
||||
this.integerHashSet = integerHashSet;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime
|
||||
* result
|
||||
+ ((genericArrayList == null) ? 0 : genericArrayList.hashCode());
|
||||
result = prime * result
|
||||
+ ((integerHashSet == null) ? 0 : integerHashSet.hashCode());
|
||||
return result;
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((genericArrayList == null) ? 0 : genericArrayList.hashCode());
|
||||
result = prime * result + ((integerHashSet == null) ? 0 : integerHashSet.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (!(obj instanceof ComplexClass))
|
||||
return false;
|
||||
ComplexClass other = (ComplexClass) obj;
|
||||
if (genericArrayList == null) {
|
||||
if (other.genericArrayList != null)
|
||||
return false;
|
||||
} else if (!genericArrayList.equals(other.genericArrayList))
|
||||
return false;
|
||||
if (integerHashSet == null) {
|
||||
if (other.integerHashSet != null)
|
||||
return false;
|
||||
} else if (!integerHashSet.equals(other.integerHashSet))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (!(obj instanceof ComplexClass))
|
||||
return false;
|
||||
ComplexClass other = (ComplexClass) obj;
|
||||
if (genericArrayList == null) {
|
||||
if (other.genericArrayList != null)
|
||||
return false;
|
||||
} else if (!genericArrayList.equals(other.genericArrayList))
|
||||
return false;
|
||||
if (integerHashSet == null) {
|
||||
if (other.integerHashSet != null)
|
||||
return false;
|
||||
} else if (!integerHashSet.equals(other.integerHashSet))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
protected ArrayList<?> getGenericArrayList() {
|
||||
return genericArrayList;
|
||||
}
|
||||
protected ArrayList<?> getGenericArrayList() {
|
||||
return genericArrayList;
|
||||
}
|
||||
|
||||
protected void setGenericArrayList(ArrayList<?> genericArrayList) {
|
||||
this.genericArrayList = genericArrayList;
|
||||
}
|
||||
protected void setGenericArrayList(ArrayList<?> genericArrayList) {
|
||||
this.genericArrayList = genericArrayList;
|
||||
}
|
||||
|
||||
protected HashSet<Integer> getIntegerHashSet() {
|
||||
return integerHashSet;
|
||||
}
|
||||
protected HashSet<Integer> getIntegerHashSet() {
|
||||
return integerHashSet;
|
||||
}
|
||||
|
||||
protected void setIntegerHashSet(HashSet<Integer> integerHashSet) {
|
||||
this.integerHashSet = integerHashSet;
|
||||
}
|
||||
protected void setIntegerHashSet(HashSet<Integer> integerHashSet) {
|
||||
this.integerHashSet = integerHashSet;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,53 +2,53 @@ package org.baeldung.equalshashcode.entities;
|
||||
|
||||
public class PrimitiveClass {
|
||||
|
||||
private boolean primitiveBoolean;
|
||||
private int primitiveInt;
|
||||
private boolean primitiveBoolean;
|
||||
private int primitiveInt;
|
||||
|
||||
public PrimitiveClass(boolean primitiveBoolean, int primitiveInt) {
|
||||
super();
|
||||
this.primitiveBoolean = primitiveBoolean;
|
||||
this.primitiveInt = primitiveInt;
|
||||
}
|
||||
public PrimitiveClass(boolean primitiveBoolean, int primitiveInt) {
|
||||
super();
|
||||
this.primitiveBoolean = primitiveBoolean;
|
||||
this.primitiveInt = primitiveInt;
|
||||
}
|
||||
|
||||
protected boolean isPrimitiveBoolean() {
|
||||
return primitiveBoolean;
|
||||
}
|
||||
protected boolean isPrimitiveBoolean() {
|
||||
return primitiveBoolean;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + (primitiveBoolean ? 1231 : 1237);
|
||||
result = prime * result + primitiveInt;
|
||||
return result;
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + (primitiveBoolean ? 1231 : 1237);
|
||||
result = prime * result + primitiveInt;
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
PrimitiveClass other = (PrimitiveClass) obj;
|
||||
if (primitiveBoolean != other.primitiveBoolean)
|
||||
return false;
|
||||
if (primitiveInt != other.primitiveInt)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
PrimitiveClass other = (PrimitiveClass) obj;
|
||||
if (primitiveBoolean != other.primitiveBoolean)
|
||||
return false;
|
||||
if (primitiveInt != other.primitiveInt)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
protected void setPrimitiveBoolean(boolean primitiveBoolean) {
|
||||
this.primitiveBoolean = primitiveBoolean;
|
||||
}
|
||||
protected void setPrimitiveBoolean(boolean primitiveBoolean) {
|
||||
this.primitiveBoolean = primitiveBoolean;
|
||||
}
|
||||
|
||||
protected int getPrimitiveInt() {
|
||||
return primitiveInt;
|
||||
}
|
||||
protected int getPrimitiveInt() {
|
||||
return primitiveInt;
|
||||
}
|
||||
|
||||
protected void setPrimitiveInt(int primitiveInt) {
|
||||
this.primitiveInt = primitiveInt;
|
||||
}
|
||||
protected void setPrimitiveInt(int primitiveInt) {
|
||||
this.primitiveInt = primitiveInt;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,62 +1,60 @@
|
||||
package org.baeldung.equalshashcode.entities;
|
||||
|
||||
public class Rectangle extends Shape {
|
||||
private double width;
|
||||
private double length;
|
||||
private double width;
|
||||
private double length;
|
||||
|
||||
public Rectangle(double width, double length) {
|
||||
this.width = width;
|
||||
this.length = length;
|
||||
}
|
||||
public Rectangle(double width, double length) {
|
||||
this.width = width;
|
||||
this.length = length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double area() {
|
||||
// A = w * l
|
||||
return width * length;
|
||||
}
|
||||
@Override
|
||||
public double area() {
|
||||
// A = w * l
|
||||
return width * length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double perimeter() {
|
||||
// P = 2(w + l)
|
||||
return 2 * (width + length);
|
||||
}
|
||||
@Override
|
||||
public double perimeter() {
|
||||
// P = 2(w + l)
|
||||
return 2 * (width + length);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
long temp;
|
||||
temp = Double.doubleToLongBits(length);
|
||||
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||
temp = Double.doubleToLongBits(width);
|
||||
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||
return result;
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
long temp;
|
||||
temp = Double.doubleToLongBits(length);
|
||||
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||
temp = Double.doubleToLongBits(width);
|
||||
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Rectangle other = (Rectangle) obj;
|
||||
if (Double.doubleToLongBits(length) != Double
|
||||
.doubleToLongBits(other.length))
|
||||
return false;
|
||||
if (Double.doubleToLongBits(width) != Double
|
||||
.doubleToLongBits(other.width))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Rectangle other = (Rectangle) obj;
|
||||
if (Double.doubleToLongBits(length) != Double.doubleToLongBits(other.length))
|
||||
return false;
|
||||
if (Double.doubleToLongBits(width) != Double.doubleToLongBits(other.width))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
protected double getWidth() {
|
||||
return width;
|
||||
}
|
||||
protected double getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
protected double getLength() {
|
||||
return length;
|
||||
}
|
||||
protected double getLength() {
|
||||
return length;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package org.baeldung.equalshashcode.entities;
|
||||
|
||||
public abstract class Shape {
|
||||
public abstract double area();
|
||||
public abstract double area();
|
||||
|
||||
public abstract double perimeter();
|
||||
public abstract double perimeter();
|
||||
}
|
||||
|
||||
@@ -4,44 +4,55 @@ import java.awt.Color;
|
||||
|
||||
public class Square extends Rectangle {
|
||||
|
||||
Color color;
|
||||
Color color;
|
||||
|
||||
public Square(double width, Color color) {
|
||||
super(width, width);
|
||||
this.color = color;
|
||||
}
|
||||
public Square(double width, Color color) {
|
||||
super(width, width);
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = super.hashCode();
|
||||
result = prime * result + ((color == null) ? 0 : color.hashCode());
|
||||
return result;
|
||||
}
|
||||
/* (non-Javadoc)
|
||||
* @see java.lang.Object#hashCode()
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = super.hashCode();
|
||||
result = prime * result + ((color == null) ? 0 : color.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (!super.equals(obj))
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Square other = (Square) obj;
|
||||
if (color == null) {
|
||||
if (other.color != null)
|
||||
return false;
|
||||
} else if (!color.equals(other.color))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
/* (non-Javadoc)
|
||||
* @see java.lang.Object#equals(java.lang.Object)
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (!super.equals(obj)) {
|
||||
return false;
|
||||
}
|
||||
if (!(obj instanceof Square)) {
|
||||
return false;
|
||||
}
|
||||
Square other = (Square) obj;
|
||||
if (color == null) {
|
||||
if (other.color != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!color.equals(other.color)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
protected Color getColor() {
|
||||
return color;
|
||||
}
|
||||
protected Color getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
protected void setColor(Color color) {
|
||||
this.color = color;
|
||||
}
|
||||
protected void setColor(Color color) {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -8,32 +8,27 @@ import org.junit.Test;
|
||||
|
||||
public class ComplexClassTest {
|
||||
|
||||
@Test
|
||||
public void testEqualsAndHashcodes() {
|
||||
|
||||
ArrayList<String> strArrayList = new ArrayList<String>();
|
||||
strArrayList.add("abc");
|
||||
strArrayList.add("def");
|
||||
ComplexClass aObject = new ComplexClass(strArrayList, new HashSet<Integer>(45,67));
|
||||
ComplexClass bObject = new ComplexClass(strArrayList, new HashSet<Integer>(45,67));
|
||||
ComplexClass cObject = new ComplexClass(strArrayList, new HashSet<Integer>(45,67));
|
||||
|
||||
ArrayList<String> strArrayListD = new ArrayList<String>();
|
||||
strArrayListD.add("lmn");
|
||||
strArrayListD.add("pqr");
|
||||
ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet<Integer>(45,67));
|
||||
|
||||
// equals()
|
||||
Assert.assertTrue(aObject.equals(aObject));
|
||||
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
|
||||
Assert.assertTrue(aObject.equals(bObject));
|
||||
Assert.assertTrue(bObject.equals(cObject));
|
||||
Assert.assertTrue(aObject.equals(cObject));
|
||||
// hashCode()
|
||||
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
|
||||
// non-equal objects are not equals() and have different hashCode()
|
||||
Assert.assertFalse(aObject.equals(dObject));
|
||||
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
|
||||
}
|
||||
@Test
|
||||
public void testEqualsAndHashcodes() {
|
||||
|
||||
ArrayList<String> strArrayList = new ArrayList<String>();
|
||||
strArrayList.add("abc");
|
||||
strArrayList.add("def");
|
||||
ComplexClass aObject = new ComplexClass(strArrayList, new HashSet<Integer>(45, 67));
|
||||
ComplexClass bObject = new ComplexClass(strArrayList, new HashSet<Integer>(45, 67));
|
||||
|
||||
ArrayList<String> strArrayListD = new ArrayList<String>();
|
||||
strArrayListD.add("lmn");
|
||||
strArrayListD.add("pqr");
|
||||
ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet<Integer>(45, 67));
|
||||
|
||||
// equals()
|
||||
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
|
||||
// hashCode()
|
||||
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
|
||||
// non-equal objects are not equals() and have different hashCode()
|
||||
Assert.assertFalse(aObject.equals(dObject));
|
||||
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user