Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
54ae4fa37c
|
@ -9,7 +9,7 @@ import java.util.Map;
|
||||||
|
|
||||||
@Path("baeldung")
|
@Path("baeldung")
|
||||||
@Produces("text/xml")
|
@Produces("text/xml")
|
||||||
public class Baeldung {
|
public class CourseRepository {
|
||||||
private Map<Integer, Course> courses = new HashMap<>();
|
private Map<Integer, Course> courses = new HashMap<>();
|
||||||
|
|
||||||
{
|
{
|
||||||
|
@ -69,4 +69,4 @@ public class Baeldung {
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -7,8 +7,8 @@ import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
|
||||||
public class RestfulServer {
|
public class RestfulServer {
|
||||||
public static void main(String args[]) throws Exception {
|
public static void main(String args[]) throws Exception {
|
||||||
JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean();
|
JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean();
|
||||||
factoryBean.setResourceClasses(Baeldung.class);
|
factoryBean.setResourceClasses(CourseRepository.class);
|
||||||
factoryBean.setResourceProvider(new SingletonResourceProvider(new Baeldung()));
|
factoryBean.setResourceProvider(new SingletonResourceProvider(new CourseRepository()));
|
||||||
factoryBean.setAddress("http://localhost:8080/");
|
factoryBean.setAddress("http://localhost:8080/");
|
||||||
Server server = factoryBean.create();
|
Server server = factoryBean.create();
|
||||||
|
|
||||||
|
@ -18,4 +18,4 @@ public class RestfulServer {
|
||||||
server.destroy();
|
server.destroy();
|
||||||
System.exit(0);
|
System.exit(0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -97,6 +97,14 @@
|
||||||
<version>8.0.2</version>
|
<version>8.0.2</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.dbdoclet</groupId>
|
||||||
|
<artifactId>herold</artifactId>
|
||||||
|
<version>6.1.0</version>
|
||||||
|
<scope>system</scope>
|
||||||
|
<systemPath>${basedir}/src/test/resources/jars/herold.jar</systemPath>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>net.sf.jtidy</groupId>
|
<groupId>net.sf.jtidy</groupId>
|
||||||
<artifactId>jtidy</artifactId>
|
<artifactId>jtidy</artifactId>
|
||||||
|
@ -132,7 +140,8 @@
|
||||||
<version>${maven-surefire-plugin.version}</version>
|
<version>${maven-surefire-plugin.version}</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<excludes>
|
<excludes>
|
||||||
<exclude>**/*IntegrationTest.java</exclude>
|
<exclude>**/*IntegrationTest.java</exclude>
|
||||||
|
<exclude>**/*LiveTest.java</exclude>
|
||||||
</excludes>
|
</excludes>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
@ -141,6 +150,42 @@
|
||||||
|
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
<profiles>
|
||||||
|
<profile>
|
||||||
|
<id>integration</id>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>integration-test</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>test</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/*ManualTest.java</exclude>
|
||||||
|
</excludes>
|
||||||
|
<includes>
|
||||||
|
<include>**/*IntegrationTest.java</include>
|
||||||
|
<exclude>**/*LiveTest.java</exclude>
|
||||||
|
</includes>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<configuration>
|
||||||
|
<systemPropertyVariables>
|
||||||
|
<test.mime>json</test.mime>
|
||||||
|
</systemPropertyVariables>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</profile>
|
||||||
|
</profiles>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- persistence -->
|
<!-- persistence -->
|
||||||
<hibernate.version>4.3.11.Final</hibernate.version>
|
<hibernate.version>4.3.11.Final</hibernate.version>
|
||||||
|
|
|
@ -25,7 +25,7 @@ import org.junit.Test;
|
||||||
import org.w3c.dom.Document;
|
import org.w3c.dom.Document;
|
||||||
import org.w3c.tidy.Tidy;
|
import org.w3c.tidy.Tidy;
|
||||||
|
|
||||||
public class ApacheFOPConvertHTMLTest {
|
public class ApacheFOPConvertHTMLIntegrationTest {
|
||||||
private String inputFile = "src/test/resources/input.html";
|
private String inputFile = "src/test/resources/input.html";
|
||||||
private String style = "src/test/resources/xhtml2fo.xsl";
|
private String style = "src/test/resources/xhtml2fo.xsl";
|
||||||
private String style1 = "src/test/resources/docbook-xsl/fo/docbook.xsl";
|
private String style1 = "src/test/resources/docbook-xsl/fo/docbook.xsl";
|
|
@ -30,7 +30,7 @@ import org.dbdoclet.trafo.script.Script;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.w3c.dom.Document;
|
import org.w3c.dom.Document;
|
||||||
|
|
||||||
public class ApacheFOPHeroldTest {
|
public class ApacheFOPHeroldLiveTest {
|
||||||
private String[] inputUrls = {// @formatter:off
|
private String[] inputUrls = {// @formatter:off
|
||||||
"http://www.baeldung.com/2011/10/20/bootstraping-a-web-application-with-spring-3-1-and-java-based-configuration-part-1/",
|
"http://www.baeldung.com/2011/10/20/bootstraping-a-web-application-with-spring-3-1-and-java-based-configuration-part-1/",
|
||||||
"http://www.baeldung.com/2011/10/25/building-a-restful-web-service-with-spring-3-1-and-java-based-configuration-part-2/",
|
"http://www.baeldung.com/2011/10/25/building-a-restful-web-service-with-spring-3-1-and-java-based-configuration-part-2/",
|
|
@ -10,7 +10,7 @@ import org.junit.Test;
|
||||||
import com.baeldung.interceptor.AuditedInterceptor;
|
import com.baeldung.interceptor.AuditedInterceptor;
|
||||||
import com.baeldung.service.SuperService;
|
import com.baeldung.service.SuperService;
|
||||||
|
|
||||||
public class TestInterceptor {
|
public class InterceptorIntegrationTest {
|
||||||
Weld weld;
|
Weld weld;
|
||||||
WeldContainer container;
|
WeldContainer container;
|
||||||
|
|
|
@ -23,12 +23,16 @@ public class SpringInterceptorIntegrationTest {
|
||||||
@Autowired
|
@Autowired
|
||||||
private List<String> accumulator;
|
private List<String> accumulator;
|
||||||
|
|
||||||
|
//
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenService_whenServiceAndAspectExecuted_thenOk() {
|
public void givenService_whenServiceAndAspectExecuted_thenOk() {
|
||||||
String code = "123456";
|
String code = "123456";
|
||||||
String result = springSuperService.getInfoFromService(code);
|
String result = springSuperService.getInfoFromService(code);
|
||||||
|
|
||||||
Assert.assertThat(accumulator.size(), is(2));
|
Assert.assertThat(accumulator.size(), is(2));
|
||||||
Assert.assertThat(accumulator.get(0), is("Call to getInfoFromService"));
|
Assert.assertThat(accumulator.get(0), is("Call to getInfoFromService"));
|
||||||
Assert.assertThat(accumulator.get(1), is("Method called successfully: getInfoFromService"));
|
Assert.assertThat(accumulator.get(1), is("Method called successfully: getInfoFromService"));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,19 +0,0 @@
|
||||||
=========
|
|
||||||
|
|
||||||
## Core Java 8 Cookbooks and Examples
|
|
||||||
|
|
||||||
### Relevant Articles:
|
|
||||||
- [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
|
|
||||||
- [Java – Directory Size](http://www.baeldung.com/java-folder-size)
|
|
||||||
- [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources)
|
|
||||||
- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial)
|
|
||||||
- [Java 8 New Features](http://www.baeldung.com/java-8-new-features)
|
|
||||||
- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
|
|
||||||
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
|
|
||||||
- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams)
|
|
||||||
- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava)
|
|
||||||
- [Guide to Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
|
|
||||||
- [The Java 8 Stream API Tutorial](http://www.baeldung.com/java-8-streams)
|
|
||||||
- [New Features in Java 8](http://www.baeldung.com/java-8-new-features)
|
|
||||||
- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction)
|
|
||||||
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
|
|
|
@ -1,142 +0,0 @@
|
||||||
<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>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
<artifactId>core-java8</artifactId>
|
|
||||||
|
|
||||||
<name>core-java8</name>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
|
|
||||||
<!-- utils -->
|
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>commons-io</groupId>
|
|
||||||
<artifactId>commons-io</artifactId>
|
|
||||||
<version>2.5</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>
|
|
||||||
|
|
||||||
<!-- test scoped -->
|
|
||||||
|
|
||||||
<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.assertj</groupId>
|
|
||||||
<artifactId>assertj-core</artifactId>
|
|
||||||
<version>3.5.1</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-8</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>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
|
||||||
<version>${maven-surefire-plugin.version}</version>
|
|
||||||
</plugin>
|
|
||||||
|
|
||||||
</plugins>
|
|
||||||
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
|
|
||||||
<!-- 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-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>
|
|
|
@ -1,13 +0,0 @@
|
||||||
*.class
|
|
||||||
|
|
||||||
#folders#
|
|
||||||
/target
|
|
||||||
/neoDb*
|
|
||||||
/data
|
|
||||||
/src/main/webapp/WEB-INF/classes
|
|
||||||
*/META-INF/*
|
|
||||||
|
|
||||||
# Packaged files #
|
|
||||||
*.jar
|
|
||||||
*.war
|
|
||||||
*.ear
|
|
|
@ -1,91 +0,0 @@
|
||||||
package com.baeldung.enums;
|
|
||||||
|
|
||||||
import java.util.EnumMap;
|
|
||||||
import java.util.EnumSet;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
public class Pizza {
|
|
||||||
|
|
||||||
private static EnumSet<PizzaStatusEnum> deliveredPizzaStatuses =
|
|
||||||
EnumSet.of(PizzaStatusEnum.DELIVERED);
|
|
||||||
|
|
||||||
private PizzaStatusEnum status;
|
|
||||||
|
|
||||||
public enum PizzaStatusEnum {
|
|
||||||
ORDERED(5) {
|
|
||||||
@Override
|
|
||||||
public boolean isOrdered() {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
READY(2) {
|
|
||||||
@Override
|
|
||||||
public boolean isReady() {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
DELIVERED(0) {
|
|
||||||
@Override
|
|
||||||
public boolean isDelivered() {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
private int timeToDelivery;
|
|
||||||
|
|
||||||
public boolean isOrdered() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isReady() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isDelivered() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getTimeToDelivery() {
|
|
||||||
return timeToDelivery;
|
|
||||||
}
|
|
||||||
|
|
||||||
PizzaStatusEnum(int timeToDelivery) {
|
|
||||||
this.timeToDelivery = timeToDelivery;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public PizzaStatusEnum getStatus() {
|
|
||||||
return status;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setStatus(PizzaStatusEnum status) {
|
|
||||||
this.status = status;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isDeliverable() {
|
|
||||||
return this.status.isReady();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void printTimeToDeliver() {
|
|
||||||
System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days");
|
|
||||||
}
|
|
||||||
|
|
||||||
public static List<Pizza> getAllUndeliveredPizzas(List<Pizza> input) {
|
|
||||||
return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList());
|
|
||||||
}
|
|
||||||
|
|
||||||
public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> pzList) {
|
|
||||||
return pzList.stream().collect(
|
|
||||||
Collectors.groupingBy(Pizza::getStatus,
|
|
||||||
() -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList()));
|
|
||||||
}
|
|
||||||
|
|
||||||
public void deliver() {
|
|
||||||
if (isDeliverable()) {
|
|
||||||
PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
|
|
||||||
this.setStatus(PizzaStatusEnum.DELIVERED);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,18 +0,0 @@
|
||||||
package com.baeldung.enums;
|
|
||||||
|
|
||||||
public enum PizzaDeliveryStrategy {
|
|
||||||
EXPRESS {
|
|
||||||
@Override
|
|
||||||
public void deliver(Pizza pz) {
|
|
||||||
System.out.println("Pizza will be delivered in express mode");
|
|
||||||
}
|
|
||||||
},
|
|
||||||
NORMAL {
|
|
||||||
@Override
|
|
||||||
public void deliver(Pizza pz) {
|
|
||||||
System.out.println("Pizza will be delivered in normal mode");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
public abstract void deliver(Pizza pz);
|
|
||||||
}
|
|
|
@ -1,22 +0,0 @@
|
||||||
package com.baeldung.enums;
|
|
||||||
|
|
||||||
|
|
||||||
public enum PizzaDeliverySystemConfiguration {
|
|
||||||
INSTANCE;
|
|
||||||
|
|
||||||
PizzaDeliverySystemConfiguration() {
|
|
||||||
// Do the configuration initialization which
|
|
||||||
// involves overriding defaults like delivery strategy
|
|
||||||
}
|
|
||||||
|
|
||||||
private PizzaDeliveryStrategy deliveryStrategy = PizzaDeliveryStrategy.NORMAL;
|
|
||||||
|
|
||||||
public static PizzaDeliverySystemConfiguration getInstance() {
|
|
||||||
return INSTANCE;
|
|
||||||
}
|
|
||||||
|
|
||||||
public PizzaDeliveryStrategy getDeliveryStrategy() {
|
|
||||||
return deliveryStrategy;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
Binary file not shown.
|
@ -1,16 +0,0 @@
|
||||||
<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>
|
|
|
@ -1 +0,0 @@
|
||||||
Hello World!
|
|
|
@ -1 +0,0 @@
|
||||||
Hello World!
|
|
|
@ -1 +0,0 @@
|
||||||
My Name is John
|
|
|
@ -1 +0,0 @@
|
||||||
My Name is Tom
|
|
|
@ -1 +0,0 @@
|
||||||
My Name is Jane
|
|
|
@ -1 +0,0 @@
|
||||||
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse facilisis neque sed turpis venenatis, non dignissim risus volutpat.
|
|
|
@ -24,4 +24,15 @@
|
||||||
- [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces)
|
- [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces)
|
||||||
- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
|
- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
|
||||||
- [Random List Element](http://www.baeldung.com/java-random-list-element)
|
- [Random List Element](http://www.baeldung.com/java-random-list-element)
|
||||||
- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
|
- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
|
||||||
|
- [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
|
||||||
|
- [Java – Directory Size](http://www.baeldung.com/java-folder-size)
|
||||||
|
- [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources)
|
||||||
|
- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial)
|
||||||
|
- [Java 8 New Features](http://www.baeldung.com/java-8-new-features)
|
||||||
|
- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
|
||||||
|
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
|
||||||
|
- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams)
|
||||||
|
- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava)
|
||||||
|
- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction)
|
||||||
|
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
|
|
@ -162,6 +162,8 @@
|
||||||
<configuration>
|
<configuration>
|
||||||
<excludes>
|
<excludes>
|
||||||
<exclude>**/*IntegrationTest.java</exclude>
|
<exclude>**/*IntegrationTest.java</exclude>
|
||||||
|
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||||
|
<exclude>**/*ManualTest.java</exclude>
|
||||||
</excludes>
|
</excludes>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
@ -277,6 +279,41 @@
|
||||||
</plugins>
|
</plugins>
|
||||||
|
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
<profiles>
|
||||||
|
<profile>
|
||||||
|
<id>integration</id>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>integration-test</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>test</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/*ManualTest.java</exclude>
|
||||||
|
</excludes>
|
||||||
|
<includes>
|
||||||
|
<include>**/*IntegrationTest.java</include>
|
||||||
|
</includes>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<configuration>
|
||||||
|
<systemPropertyVariables>
|
||||||
|
<test.mime>json</test.mime>
|
||||||
|
</systemPropertyVariables>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</profile>
|
||||||
|
</profiles>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- persistence -->
|
<!-- persistence -->
|
||||||
|
|
|
@ -5,12 +5,12 @@ import java.time.LocalTime;
|
||||||
import java.time.Period;
|
import java.time.Period;
|
||||||
|
|
||||||
public class UseDuration {
|
public class UseDuration {
|
||||||
|
|
||||||
public LocalTime modifyDates(LocalTime localTime,Duration duration){
|
public LocalTime modifyDates(LocalTime localTime, Duration duration) {
|
||||||
return localTime.plus(duration);
|
return localTime.plus(duration);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Duration getDifferenceBetweenDates(LocalTime localTime1,LocalTime localTime2){
|
public Duration getDifferenceBetweenDates(LocalTime localTime1, LocalTime localTime2) {
|
||||||
return Duration.between(localTime1, localTime2);
|
return Duration.between(localTime1, localTime2);
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -7,39 +7,39 @@ import java.time.temporal.ChronoUnit;
|
||||||
import java.time.temporal.TemporalAdjusters;
|
import java.time.temporal.TemporalAdjusters;
|
||||||
|
|
||||||
public class UseLocalDate {
|
public class UseLocalDate {
|
||||||
|
|
||||||
public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth){
|
public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) {
|
||||||
return LocalDate.of(year, month, dayOfMonth);
|
return LocalDate.of(year, month, dayOfMonth);
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getLocalDateUsingParseMethod(String representation){
|
public LocalDate getLocalDateUsingParseMethod(String representation) {
|
||||||
return LocalDate.parse(representation);
|
return LocalDate.parse(representation);
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getLocalDateFromClock(){
|
public LocalDate getLocalDateFromClock() {
|
||||||
LocalDate localDate = LocalDate.now();
|
LocalDate localDate = LocalDate.now();
|
||||||
return localDate;
|
return localDate;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getNextDay(LocalDate localDate){
|
public LocalDate getNextDay(LocalDate localDate) {
|
||||||
return localDate.plusDays(1);
|
return localDate.plusDays(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getPreviousDay(LocalDate localDate){
|
public LocalDate getPreviousDay(LocalDate localDate) {
|
||||||
return localDate.minus(1, ChronoUnit.DAYS);
|
return localDate.minus(1, ChronoUnit.DAYS);
|
||||||
}
|
}
|
||||||
|
|
||||||
public DayOfWeek getDayOfWeek(LocalDate localDate){
|
public DayOfWeek getDayOfWeek(LocalDate localDate) {
|
||||||
DayOfWeek day = localDate.getDayOfWeek();
|
DayOfWeek day = localDate.getDayOfWeek();
|
||||||
return day;
|
return day;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getFirstDayOfMonth(){
|
public LocalDate getFirstDayOfMonth() {
|
||||||
LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
|
LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
|
||||||
return firstDayOfMonth;
|
return firstDayOfMonth;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDateTime getStartOfDay(LocalDate localDate){
|
public LocalDateTime getStartOfDay(LocalDate localDate) {
|
||||||
LocalDateTime startofDay = localDate.atStartOfDay();
|
LocalDateTime startofDay = localDate.atStartOfDay();
|
||||||
return startofDay;
|
return startofDay;
|
||||||
}
|
}
|
|
@ -3,8 +3,8 @@ package com.baeldung.datetime;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
public class UseLocalDateTime {
|
public class UseLocalDateTime {
|
||||||
|
|
||||||
public LocalDateTime getLocalDateTimeUsingParseMethod(String representation){
|
public LocalDateTime getLocalDateTimeUsingParseMethod(String representation) {
|
||||||
return LocalDateTime.parse(representation);
|
return LocalDateTime.parse(representation);
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,32 +4,32 @@ import java.time.LocalTime;
|
||||||
import java.time.temporal.ChronoUnit;
|
import java.time.temporal.ChronoUnit;
|
||||||
|
|
||||||
public class UseLocalTime {
|
public class UseLocalTime {
|
||||||
|
|
||||||
public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds){
|
public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
|
||||||
LocalTime localTime = LocalTime.of(hour, min, seconds);
|
LocalTime localTime = LocalTime.of(hour, min, seconds);
|
||||||
return localTime;
|
return localTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation){
|
public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
|
||||||
LocalTime localTime = LocalTime.parse(timeRepresentation);
|
LocalTime localTime = LocalTime.parse(timeRepresentation);
|
||||||
return localTime;
|
return localTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime getLocalTimeFromClock(){
|
public LocalTime getLocalTimeFromClock() {
|
||||||
LocalTime localTime = LocalTime.now();
|
LocalTime localTime = LocalTime.now();
|
||||||
return localTime;
|
return localTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime addAnHour(LocalTime localTime){
|
public LocalTime addAnHour(LocalTime localTime) {
|
||||||
LocalTime newTime = localTime.plus(1,ChronoUnit.HOURS);
|
LocalTime newTime = localTime.plus(1, ChronoUnit.HOURS);
|
||||||
return newTime;
|
return newTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getHourFromLocalTime(LocalTime localTime){
|
public int getHourFromLocalTime(LocalTime localTime) {
|
||||||
return localTime.getHour();
|
return localTime.getHour();
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute){
|
public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) {
|
||||||
return localTime.withMinute(minute);
|
return localTime.withMinute(minute);
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -4,12 +4,12 @@ import java.time.LocalDate;
|
||||||
import java.time.Period;
|
import java.time.Period;
|
||||||
|
|
||||||
public class UsePeriod {
|
public class UsePeriod {
|
||||||
|
|
||||||
public LocalDate modifyDates(LocalDate localDate,Period period){
|
public LocalDate modifyDates(LocalDate localDate, Period period) {
|
||||||
return localDate.plus(period);
|
return localDate.plus(period);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Period getDifferenceBetweenDates(LocalDate localDate1,LocalDate localDate2){
|
public Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) {
|
||||||
return Period.between(localDate1, localDate2);
|
return Period.between(localDate1, localDate2);
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -6,13 +6,13 @@ import java.util.Calendar;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
|
||||||
public class UseToInstant {
|
public class UseToInstant {
|
||||||
|
|
||||||
public LocalDateTime convertDateToLocalDate(Date date){
|
public LocalDateTime convertDateToLocalDate(Date date) {
|
||||||
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
|
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
|
||||||
return localDateTime;
|
return localDateTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDateTime convertDateToLocalDate(Calendar calendar){
|
public LocalDateTime convertDateToLocalDate(Calendar calendar) {
|
||||||
LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
|
LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
|
||||||
return localDateTime;
|
return localDateTime;
|
||||||
}
|
}
|
|
@ -5,8 +5,8 @@ import java.time.ZoneId;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
|
|
||||||
public class UseZonedDateTime {
|
public class UseZonedDateTime {
|
||||||
|
|
||||||
public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime,ZoneId zoneId){
|
public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
|
||||||
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
|
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
|
||||||
return zonedDateTime;
|
return zonedDateTime;
|
||||||
}
|
}
|
|
@ -1,11 +1,5 @@
|
||||||
package com.baeldung.enums;
|
package com.baeldung.enums;
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
import org.apache.commons.collections15.Predicate;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.EnumMap;
|
import java.util.EnumMap;
|
||||||
import java.util.EnumSet;
|
import java.util.EnumSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
@ -13,13 +7,11 @@ import java.util.stream.Collectors;
|
||||||
|
|
||||||
public class Pizza {
|
public class Pizza {
|
||||||
|
|
||||||
private static EnumSet<PizzaStatus> undeliveredPizzaStatuses =
|
private static EnumSet<PizzaStatusEnum> deliveredPizzaStatuses = EnumSet.of(PizzaStatusEnum.DELIVERED);
|
||||||
EnumSet.of(PizzaStatus.ORDERED, PizzaStatus.READY);
|
|
||||||
|
|
||||||
private PizzaStatus status;
|
private PizzaStatusEnum status;
|
||||||
|
|
||||||
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
|
public enum PizzaStatusEnum {
|
||||||
public enum PizzaStatus {
|
|
||||||
ORDERED(5) {
|
ORDERED(5) {
|
||||||
@Override
|
@Override
|
||||||
public boolean isOrdered() {
|
public boolean isOrdered() {
|
||||||
|
@ -53,21 +45,20 @@ public class Pizza {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@JsonProperty("timeToDelivery")
|
|
||||||
public int getTimeToDelivery() {
|
public int getTimeToDelivery() {
|
||||||
return timeToDelivery;
|
return timeToDelivery;
|
||||||
}
|
}
|
||||||
|
|
||||||
PizzaStatus(int timeToDelivery) {
|
PizzaStatusEnum(int timeToDelivery) {
|
||||||
this.timeToDelivery = timeToDelivery;
|
this.timeToDelivery = timeToDelivery;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public PizzaStatus getStatus() {
|
public PizzaStatusEnum getStatus() {
|
||||||
return status;
|
return status;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setStatus(PizzaStatus status) {
|
public void setStatus(PizzaStatusEnum status) {
|
||||||
this.status = status;
|
this.status = status;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -80,31 +71,18 @@ public class Pizza {
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<Pizza> getAllUndeliveredPizzas(List<Pizza> input) {
|
public static List<Pizza> getAllUndeliveredPizzas(List<Pizza> input) {
|
||||||
return input.stream().filter(
|
return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList());
|
||||||
(s) -> undeliveredPizzaStatuses.contains(s.getStatus()))
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static EnumMap<PizzaStatus, List<Pizza>>
|
public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> pzList) {
|
||||||
groupPizzaByStatus(List<Pizza> pzList) {
|
return pzList.stream().collect(Collectors.groupingBy(Pizza::getStatus, () -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList()));
|
||||||
return pzList.stream().collect(
|
|
||||||
Collectors.groupingBy(Pizza::getStatus,
|
|
||||||
() -> new EnumMap<>(PizzaStatus.class), Collectors.toList()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void deliver() {
|
public void deliver() {
|
||||||
if (isDeliverable()) {
|
if (isDeliverable()) {
|
||||||
PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
|
PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
|
||||||
this.setStatus(PizzaStatus.DELIVERED);
|
this.setStatus(PizzaStatusEnum.DELIVERED);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String getJsonString(Pizza pz) throws IOException {
|
|
||||||
ObjectMapper mapper = new ObjectMapper();
|
|
||||||
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(pz);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Predicate<Pizza> thatAreNotDelivered() {
|
|
||||||
return entry -> undeliveredPizzaStatuses.contains(entry.getStatus());
|
|
||||||
}
|
|
||||||
}
|
}
|
|
@ -30,8 +30,7 @@ public class CustomRecursiveAction extends RecursiveAction {
|
||||||
|
|
||||||
private Collection<CustomRecursiveAction> createSubtasks() {
|
private Collection<CustomRecursiveAction> createSubtasks() {
|
||||||
|
|
||||||
List<CustomRecursiveAction> subtasks =
|
List<CustomRecursiveAction> subtasks = new ArrayList<>();
|
||||||
new ArrayList<>();
|
|
||||||
|
|
||||||
String partOne = workLoad.substring(0, workLoad.length() / 2);
|
String partOne = workLoad.substring(0, workLoad.length() / 2);
|
||||||
String partTwo = workLoad.substring(workLoad.length() / 2, workLoad.length());
|
String partTwo = workLoad.substring(workLoad.length() / 2, workLoad.length());
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.forkjoin;
|
package com.baeldung.forkjoin;
|
||||||
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
|
@ -23,10 +22,7 @@ public class CustomRecursiveTask extends RecursiveTask<Integer> {
|
||||||
|
|
||||||
if (arr.length > THRESHOLD) {
|
if (arr.length > THRESHOLD) {
|
||||||
|
|
||||||
return ForkJoinTask.invokeAll(createSubtasks())
|
return ForkJoinTask.invokeAll(createSubtasks()).stream().mapToInt(ForkJoinTask::join).sum();
|
||||||
.stream()
|
|
||||||
.mapToInt(ForkJoinTask::join)
|
|
||||||
.sum();
|
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
return processing(arr);
|
return processing(arr);
|
||||||
|
@ -35,17 +31,12 @@ public class CustomRecursiveTask extends RecursiveTask<Integer> {
|
||||||
|
|
||||||
private Collection<CustomRecursiveTask> createSubtasks() {
|
private Collection<CustomRecursiveTask> createSubtasks() {
|
||||||
List<CustomRecursiveTask> dividedTasks = new ArrayList<>();
|
List<CustomRecursiveTask> dividedTasks = new ArrayList<>();
|
||||||
dividedTasks.add(new CustomRecursiveTask(
|
dividedTasks.add(new CustomRecursiveTask(Arrays.copyOfRange(arr, 0, arr.length / 2)));
|
||||||
Arrays.copyOfRange(arr, 0, arr.length / 2)));
|
dividedTasks.add(new CustomRecursiveTask(Arrays.copyOfRange(arr, arr.length / 2, arr.length)));
|
||||||
dividedTasks.add(new CustomRecursiveTask(
|
|
||||||
Arrays.copyOfRange(arr, arr.length / 2, arr.length)));
|
|
||||||
return dividedTasks;
|
return dividedTasks;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Integer processing(int[] arr) {
|
private Integer processing(int[] arr) {
|
||||||
return Arrays.stream(arr)
|
return Arrays.stream(arr).filter(a -> a > 10 && a < 27).map(a -> a * 10).sum();
|
||||||
.filter(a -> a > 10 && a < 27)
|
|
||||||
.map(a -> a * 10)
|
|
||||||
.sum();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.forkjoin.util;
|
package com.baeldung.forkjoin.util;
|
||||||
|
|
||||||
|
|
||||||
import java.util.concurrent.ForkJoinPool;
|
import java.util.concurrent.ForkJoinPool;
|
||||||
|
|
||||||
public class PoolUtil {
|
public class PoolUtil {
|
|
@ -0,0 +1,56 @@
|
||||||
|
package com.baeldung.java.networking.cookies;
|
||||||
|
|
||||||
|
import java.net.*;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class PersistentCookieStore implements CookieStore, Runnable {
|
||||||
|
CookieStore store;
|
||||||
|
|
||||||
|
public PersistentCookieStore() {
|
||||||
|
store = new CookieManager().getCookieStore();
|
||||||
|
// deserialize cookies into store
|
||||||
|
Runtime.getRuntime().addShutdownHook(new Thread(this));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
// serialize cookies to persistent storage
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void add(URI uri, HttpCookie cookie) {
|
||||||
|
store.add(uri, cookie);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<HttpCookie> get(URI uri) {
|
||||||
|
// TODO Auto-generated method stub
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<HttpCookie> getCookies() {
|
||||||
|
// TODO Auto-generated method stub
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<URI> getURIs() {
|
||||||
|
// TODO Auto-generated method stub
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean remove(URI uri, HttpCookie cookie) {
|
||||||
|
// TODO Auto-generated method stub
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean removeAll() {
|
||||||
|
// TODO Auto-generated method stub
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,26 @@
|
||||||
|
package com.baeldung.java.networking.cookies;
|
||||||
|
|
||||||
|
import java.net.*;
|
||||||
|
|
||||||
|
public class ProxyAcceptCookiePolicy implements CookiePolicy {
|
||||||
|
String acceptedProxy;
|
||||||
|
|
||||||
|
public ProxyAcceptCookiePolicy(String acceptedProxy) {
|
||||||
|
this.acceptedProxy = acceptedProxy;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean shouldAccept(URI uri, HttpCookie cookie) {
|
||||||
|
String host;
|
||||||
|
try {
|
||||||
|
host = InetAddress.getByName(uri.getHost()).getCanonicalHostName();
|
||||||
|
} catch (UnknownHostException e) {
|
||||||
|
host = uri.getHost();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!HttpCookie.domainMatches(acceptedProxy, host)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(uri, cookie);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,42 @@
|
||||||
|
package com.baeldung.java.networking.udp;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.DatagramPacket;
|
||||||
|
import java.net.DatagramSocket;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
|
||||||
|
public class EchoClient {
|
||||||
|
private DatagramSocket socket;
|
||||||
|
private InetAddress address;
|
||||||
|
|
||||||
|
private byte[] buf;
|
||||||
|
|
||||||
|
public EchoClient() {
|
||||||
|
try {
|
||||||
|
socket = new DatagramSocket();
|
||||||
|
address = InetAddress.getByName("localhost");
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public String sendEcho(String msg) {
|
||||||
|
DatagramPacket packet = null;
|
||||||
|
try {
|
||||||
|
buf=msg.getBytes();
|
||||||
|
packet = new DatagramPacket(buf, buf.length, address, 4445);
|
||||||
|
socket.send(packet);
|
||||||
|
packet = new DatagramPacket(buf, buf.length);
|
||||||
|
socket.receive(packet);
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
String received = new String(packet.getData(), 0, packet.getLength());
|
||||||
|
return received;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void close() {
|
||||||
|
socket.close();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,42 @@
|
||||||
|
package com.baeldung.java.networking.udp;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.DatagramPacket;
|
||||||
|
import java.net.DatagramSocket;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
|
||||||
|
public class EchoServer extends Thread {
|
||||||
|
|
||||||
|
protected DatagramSocket socket = null;
|
||||||
|
protected boolean running;
|
||||||
|
protected byte[] buf = new byte[256];
|
||||||
|
|
||||||
|
public EchoServer() throws IOException {
|
||||||
|
socket = new DatagramSocket(4445);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void run() {
|
||||||
|
running = true;
|
||||||
|
|
||||||
|
while (running) {
|
||||||
|
try {
|
||||||
|
|
||||||
|
DatagramPacket packet = new DatagramPacket(buf, buf.length);
|
||||||
|
socket.receive(packet);
|
||||||
|
InetAddress address = packet.getAddress();
|
||||||
|
int port = packet.getPort();
|
||||||
|
packet = new DatagramPacket(buf, buf.length, address, port);
|
||||||
|
String received = new String(packet.getData(), 0, packet.getLength());
|
||||||
|
if (received.equals("end")) {
|
||||||
|
running = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
socket.send(packet);
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
running = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
socket.close();
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,21 +1,21 @@
|
||||||
package com.baeldung.java.nio.selector;
|
package com.baeldung.java.nio.selector;
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.InetSocketAddress;
|
|
||||||
import java.nio.ByteBuffer;
|
|
||||||
import java.nio.channels.SelectionKey;
|
|
||||||
import java.nio.channels.Selector;
|
|
||||||
import java.nio.channels.ServerSocketChannel;
|
import java.nio.channels.ServerSocketChannel;
|
||||||
import java.nio.channels.SocketChannel;
|
import java.nio.channels.SocketChannel;
|
||||||
import java.util.Iterator;
|
import java.nio.channels.Selector;
|
||||||
|
import java.nio.channels.SelectionKey;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.io.IOException;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.io.File;
|
||||||
|
|
||||||
public class EchoServer {
|
public class EchoServer {
|
||||||
|
|
||||||
public static void main(String[] args)
|
public static void main(String[] args)
|
||||||
|
|
||||||
throws IOException {
|
throws IOException {
|
||||||
Selector selector = Selector.open();
|
Selector selector = Selector.open();
|
||||||
ServerSocketChannel serverSocket = ServerSocketChannel.open();
|
ServerSocketChannel serverSocket = ServerSocketChannel.open();
|
||||||
serverSocket.bind(new InetSocketAddress("localhost", 5454));
|
serverSocket.bind(new InetSocketAddress("localhost", 5454));
|
||||||
|
@ -49,6 +49,7 @@ public class EchoServer {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static Process start() throws IOException, InterruptedException {
|
public static Process start() throws IOException, InterruptedException {
|
||||||
String javaHome = System.getProperty("java.home");
|
String javaHome = System.getProperty("java.home");
|
||||||
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
|
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
|
||||||
|
@ -59,4 +60,4 @@ public class EchoServer {
|
||||||
|
|
||||||
return builder.start();
|
return builder.start();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,7 +9,7 @@ public interface Vehicle {
|
||||||
}
|
}
|
||||||
|
|
||||||
default long[] startPosition() {
|
default long[] startPosition() {
|
||||||
return new long[]{23, 15};
|
return new long[] { 23, 15 };
|
||||||
}
|
}
|
||||||
|
|
||||||
default String getOverview() {
|
default String getOverview() {
|
|
@ -1,9 +1,9 @@
|
||||||
package com.baeldung.java_8_features;
|
package com.baeldung.java_8_features;
|
||||||
|
|
||||||
public class VehicleImpl implements Vehicle {
|
public class VehicleImpl implements Vehicle {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void moveTo(long altitude, long longitude) {
|
public void moveTo(long altitude, long longitude) {
|
||||||
//do nothing
|
// do nothing
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -14,7 +14,6 @@ public class Screenshot {
|
||||||
}
|
}
|
||||||
|
|
||||||
public void getScreenshot(int timeToWait) throws Exception {
|
public void getScreenshot(int timeToWait) throws Exception {
|
||||||
Thread.sleep(timeToWait);
|
|
||||||
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
|
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
|
||||||
Robot robot = new Robot();
|
Robot robot = new Robot();
|
||||||
BufferedImage img = robot.createScreenCapture(rectangle);
|
BufferedImage img = robot.createScreenCapture(rectangle);
|
||||||
|
|
|
@ -4,39 +4,38 @@ import java.io.*;
|
||||||
import java.net.*;
|
import java.net.*;
|
||||||
|
|
||||||
public class EchoClient {
|
public class EchoClient {
|
||||||
private Socket clientSocket;
|
private Socket clientSocket;
|
||||||
private PrintWriter out;
|
private PrintWriter out;
|
||||||
private BufferedReader in;
|
private BufferedReader in;
|
||||||
|
|
||||||
public void startConnection(String ip, int port) {
|
public void startConnection(String ip, int port) {
|
||||||
try {
|
try {
|
||||||
clientSocket = new Socket(ip, port);
|
clientSocket = new Socket(ip, port);
|
||||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||||
in = new BufferedReader(new InputStreamReader(
|
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||||
clientSocket.getInputStream()));
|
} catch (IOException e) {
|
||||||
} catch (IOException e) {
|
System.out.print(e);
|
||||||
System.out.print(e);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String sendMessage(String msg) {
|
public String sendMessage(String msg) {
|
||||||
try {
|
try {
|
||||||
out.println(msg);
|
out.println(msg);
|
||||||
return in.readLine();
|
return in.readLine();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stopConnection() {
|
public void stopConnection() {
|
||||||
try {
|
try {
|
||||||
in.close();
|
in.close();
|
||||||
out.close();
|
out.close();
|
||||||
clientSocket.close();
|
clientSocket.close();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,68 +4,67 @@ import java.net.*;
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
|
|
||||||
public class EchoMultiServer {
|
public class EchoMultiServer {
|
||||||
private ServerSocket serverSocket;
|
private ServerSocket serverSocket;
|
||||||
|
|
||||||
public void start(int port) {
|
public void start(int port) {
|
||||||
try {
|
try {
|
||||||
serverSocket = new ServerSocket(port);
|
serverSocket = new ServerSocket(port);
|
||||||
while (true)
|
while (true)
|
||||||
new EchoClientHandler(serverSocket.accept()).run();
|
new EchoClientHandler(serverSocket.accept()).run();
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
} finally {
|
} finally {
|
||||||
stop();
|
stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stop() {
|
public void stop() {
|
||||||
try {
|
try {
|
||||||
|
|
||||||
serverSocket.close();
|
serverSocket.close();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class EchoClientHandler extends Thread {
|
private static class EchoClientHandler extends Thread {
|
||||||
private Socket clientSocket;
|
private Socket clientSocket;
|
||||||
private PrintWriter out;
|
private PrintWriter out;
|
||||||
private BufferedReader in;
|
private BufferedReader in;
|
||||||
|
|
||||||
public EchoClientHandler(Socket socket) {
|
public EchoClientHandler(Socket socket) {
|
||||||
this.clientSocket = socket;
|
this.clientSocket = socket;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||||
in = new BufferedReader(new InputStreamReader(
|
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||||
clientSocket.getInputStream()));
|
String inputLine;
|
||||||
String inputLine;
|
while ((inputLine = in.readLine()) != null) {
|
||||||
while ((inputLine = in.readLine()) != null) {
|
if (".".equals(inputLine)) {
|
||||||
if (".".equals(inputLine)) {
|
out.println("bye");
|
||||||
out.println("bye");
|
break;
|
||||||
break;
|
}
|
||||||
}
|
out.println(inputLine);
|
||||||
out.println(inputLine);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
in.close();
|
in.close();
|
||||||
out.close();
|
out.close();
|
||||||
clientSocket.close();
|
clientSocket.close();
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
EchoMultiServer server = new EchoMultiServer();
|
EchoMultiServer server = new EchoMultiServer();
|
||||||
server.start(5555);
|
server.start(5555);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,47 +4,46 @@ import java.net.*;
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
|
|
||||||
public class EchoServer {
|
public class EchoServer {
|
||||||
private ServerSocket serverSocket;
|
private ServerSocket serverSocket;
|
||||||
private Socket clientSocket;
|
private Socket clientSocket;
|
||||||
private PrintWriter out;
|
private PrintWriter out;
|
||||||
private BufferedReader in;
|
private BufferedReader in;
|
||||||
|
|
||||||
public void start(int port) {
|
public void start(int port) {
|
||||||
try {
|
try {
|
||||||
serverSocket = new ServerSocket(port);
|
serverSocket = new ServerSocket(port);
|
||||||
clientSocket = serverSocket.accept();
|
clientSocket = serverSocket.accept();
|
||||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||||
in = new BufferedReader(new InputStreamReader(
|
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||||
clientSocket.getInputStream()));
|
String inputLine;
|
||||||
String inputLine;
|
while ((inputLine = in.readLine()) != null) {
|
||||||
while ((inputLine = in.readLine()) != null) {
|
if (".".equals(inputLine)) {
|
||||||
if (".".equals(inputLine)) {
|
out.println("good bye");
|
||||||
out.println("good bye");
|
break;
|
||||||
break;
|
}
|
||||||
}
|
out.println(inputLine);
|
||||||
out.println(inputLine);
|
}
|
||||||
}
|
} catch (IOException e) {
|
||||||
} catch (IOException e) {
|
e.printStackTrace();
|
||||||
e.printStackTrace();
|
}
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stop() {
|
public void stop() {
|
||||||
try {
|
try {
|
||||||
in.close();
|
in.close();
|
||||||
out.close();
|
out.close();
|
||||||
clientSocket.close();
|
clientSocket.close();
|
||||||
serverSocket.close();
|
serverSocket.close();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
EchoServer server = new EchoServer();
|
EchoServer server = new EchoServer();
|
||||||
server.start(4444);
|
server.start(4444);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,39 +7,38 @@ import java.io.PrintWriter;
|
||||||
import java.net.Socket;
|
import java.net.Socket;
|
||||||
|
|
||||||
public class GreetClient {
|
public class GreetClient {
|
||||||
private Socket clientSocket;
|
private Socket clientSocket;
|
||||||
private PrintWriter out;
|
private PrintWriter out;
|
||||||
private BufferedReader in;
|
private BufferedReader in;
|
||||||
|
|
||||||
public void startConnection(String ip, int port) {
|
public void startConnection(String ip, int port) {
|
||||||
try {
|
try {
|
||||||
clientSocket = new Socket(ip, port);
|
clientSocket = new Socket(ip, port);
|
||||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||||
in = new BufferedReader(new InputStreamReader(
|
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||||
clientSocket.getInputStream()));
|
} catch (IOException e) {
|
||||||
} catch (IOException e) {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String sendMessage(String msg) {
|
}
|
||||||
try {
|
|
||||||
out.println(msg);
|
|
||||||
return in.readLine();
|
|
||||||
} catch (Exception e) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void stopConnection() {
|
public String sendMessage(String msg) {
|
||||||
try {
|
try {
|
||||||
in.close();
|
out.println(msg);
|
||||||
out.close();
|
return in.readLine();
|
||||||
clientSocket.close();
|
} catch (Exception e) {
|
||||||
} catch (IOException e) {
|
return null;
|
||||||
e.printStackTrace();
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
public void stopConnection() {
|
||||||
|
try {
|
||||||
|
in.close();
|
||||||
|
out.close();
|
||||||
|
clientSocket.close();
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,44 +4,43 @@ import java.net.*;
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
|
|
||||||
public class GreetServer {
|
public class GreetServer {
|
||||||
private ServerSocket serverSocket;
|
private ServerSocket serverSocket;
|
||||||
private Socket clientSocket;
|
private Socket clientSocket;
|
||||||
private PrintWriter out;
|
private PrintWriter out;
|
||||||
private BufferedReader in;
|
private BufferedReader in;
|
||||||
|
|
||||||
|
public void start(int port) {
|
||||||
|
try {
|
||||||
|
serverSocket = new ServerSocket(port);
|
||||||
|
clientSocket = serverSocket.accept();
|
||||||
|
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||||
|
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||||
|
String greeting = in.readLine();
|
||||||
|
if ("hello server".equals(greeting))
|
||||||
|
out.println("hello client");
|
||||||
|
else
|
||||||
|
out.println("unrecognised greeting");
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
public void start(int port) {
|
}
|
||||||
try {
|
|
||||||
serverSocket = new ServerSocket(port);
|
|
||||||
clientSocket = serverSocket.accept();
|
|
||||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
|
||||||
in = new BufferedReader(new InputStreamReader(
|
|
||||||
clientSocket.getInputStream()));
|
|
||||||
String greeting = in.readLine();
|
|
||||||
if ("hello server".equals(greeting))
|
|
||||||
out.println("hello client");
|
|
||||||
else
|
|
||||||
out.println("unrecognised greeting");
|
|
||||||
} catch (IOException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
public void stop() {
|
||||||
|
try {
|
||||||
|
in.close();
|
||||||
|
out.close();
|
||||||
|
clientSocket.close();
|
||||||
|
serverSocket.close();
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
public void stop() {
|
}
|
||||||
try {
|
|
||||||
in.close();
|
|
||||||
out.close();
|
|
||||||
clientSocket.close();
|
|
||||||
serverSocket.close();
|
|
||||||
} catch (IOException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
public static void main(String[] args) {
|
||||||
public static void main(String[] args) {
|
GreetServer server = new GreetServer();
|
||||||
GreetServer server=new GreetServer();
|
server.start(6666);
|
||||||
server.start(6666);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -44,7 +44,6 @@ public class Product {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static Stream<String> streamOf(List<String> list) {
|
public static Stream<String> streamOf(List<String> list) {
|
||||||
return (list == null || list.isEmpty()) ? Stream.empty() : list.stream();
|
return (list == null || list.isEmpty()) ? Stream.empty() : list.stream();
|
||||||
}
|
}
|
|
@ -14,9 +14,7 @@ public class CountingTask extends RecursiveTask<Integer> {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected Integer compute() {
|
protected Integer compute() {
|
||||||
return node.value + node.children.stream()
|
return node.value + node.children.stream().map(childNode -> new CountingTask(childNode).fork()).collect(Collectors.summingInt(ForkJoinTask::join));
|
||||||
.map(childNode -> new CountingTask(childNode).fork())
|
|
||||||
.collect(Collectors.summingInt(ForkJoinTask::join));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -1,7 +1,5 @@
|
||||||
package org.baeldung.equalshashcode.entities;
|
package org.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
|
@ -10,7 +8,7 @@ public class ComplexClass {
|
||||||
private List<?> genericList;
|
private List<?> genericList;
|
||||||
private Set<Integer> integerSet;
|
private Set<Integer> integerSet;
|
||||||
|
|
||||||
public ComplexClass(ArrayList<?> genericArrayList, HashSet<Integer> integerHashSet) {
|
public ComplexClass(List<?> genericArrayList, Set<Integer> integerHashSet) {
|
||||||
super();
|
super();
|
||||||
this.genericList = genericArrayList;
|
this.genericList = genericArrayList;
|
||||||
this.integerSet = integerHashSet;
|
this.integerSet = integerHashSet;
|
||||||
|
|
|
@ -4,8 +4,8 @@ import javax.swing.JOptionPane;
|
||||||
|
|
||||||
public class ExecutableMavenJar {
|
public class ExecutableMavenJar {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1);
|
JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,2 @@
|
||||||
|
line 1
|
||||||
|
a second line
|
|
@ -4,10 +4,10 @@ import org.junit.Test;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
public class CharToStringTest {
|
public class CharToStringUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenChar_whenCallingStringValueOf_shouldConvertToString(){
|
public void givenChar_whenCallingStringValueOf_shouldConvertToString() {
|
||||||
final char givenChar = 'x';
|
final char givenChar = 'x';
|
||||||
|
|
||||||
final String result = String.valueOf(givenChar);
|
final String result = String.valueOf(givenChar);
|
||||||
|
@ -16,7 +16,7 @@ public class CharToStringTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenChar_whenCallingToStringOnCharacter_shouldConvertToString(){
|
public void givenChar_whenCallingToStringOnCharacter_shouldConvertToString() {
|
||||||
final char givenChar = 'x';
|
final char givenChar = 'x';
|
||||||
|
|
||||||
final String result = Character.toString(givenChar);
|
final String result = Character.toString(givenChar);
|
||||||
|
@ -25,7 +25,7 @@ public class CharToStringTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenChar_whenCallingCharacterConstructor_shouldConvertToString3(){
|
public void givenChar_whenCallingCharacterConstructor_shouldConvertToString3() {
|
||||||
final char givenChar = 'x';
|
final char givenChar = 'x';
|
||||||
|
|
||||||
final String result = new Character(givenChar).toString();
|
final String result = new Character(givenChar).toString();
|
||||||
|
@ -34,7 +34,7 @@ public class CharToStringTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenChar_whenConcatenated_shouldConvertToString4(){
|
public void givenChar_whenConcatenated_shouldConvertToString4() {
|
||||||
final char givenChar = 'x';
|
final char givenChar = 'x';
|
||||||
|
|
||||||
final String result = givenChar + "";
|
final String result = givenChar + "";
|
||||||
|
@ -43,7 +43,7 @@ public class CharToStringTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenChar_whenFormated_shouldConvertToString5(){
|
public void givenChar_whenFormated_shouldConvertToString5() {
|
||||||
final char givenChar = 'x';
|
final char givenChar = 'x';
|
||||||
|
|
||||||
final String result = String.format("%c", givenChar);
|
final String result = String.format("%c", givenChar);
|
|
@ -6,7 +6,7 @@ import org.junit.Test;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.concurrent.ThreadLocalRandom;
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
public class RandomListElementTest {
|
public class RandomListElementUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom() {
|
public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom() {
|
||||||
|
@ -20,7 +20,7 @@ public class RandomListElementTest {
|
||||||
public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingMathRandom() {
|
public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingMathRandom() {
|
||||||
List<Integer> givenList = Lists.newArrayList(1, 2, 3);
|
List<Integer> givenList = Lists.newArrayList(1, 2, 3);
|
||||||
|
|
||||||
givenList.get((int)(Math.random() * givenList.size()));
|
givenList.get((int) (Math.random() * givenList.size()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
|
@ -1,11 +1,12 @@
|
||||||
package com.baeldung;
|
package com.baeldung;
|
||||||
|
|
||||||
import com.google.common.primitives.Ints;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
public class StringToIntOrIntegerTest {
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.google.common.primitives.Ints;
|
||||||
|
|
||||||
|
public class StringToIntOrIntegerUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_whenParsingInt_shouldConvertToInt() {
|
public void givenString_whenParsingInt_shouldConvertToInt() {
|
||||||
|
@ -16,7 +17,6 @@ public class StringToIntOrIntegerTest {
|
||||||
assertThat(result).isEqualTo(42);
|
assertThat(result).isEqualTo(42);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() {
|
public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() {
|
||||||
String givenString = "42";
|
String givenString = "42";
|
|
@ -36,198 +36,143 @@ import static java.util.stream.Collectors.toSet;
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
public class Java8CollectorsTest {
|
public class Java8CollectorsUnitTest {
|
||||||
|
|
||||||
private final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dd");
|
private final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dd");
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToList_shouldCollectToList() throws Exception {
|
public void whenCollectingToList_shouldCollectToList() throws Exception {
|
||||||
final List<String> result = givenList.stream()
|
final List<String> result = givenList.stream().collect(toList());
|
||||||
.collect(toList());
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsAll(givenList);
|
||||||
.containsAll(givenList);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToList_shouldCollectToSet() throws Exception {
|
public void whenCollectingToList_shouldCollectToSet() throws Exception {
|
||||||
final Set<String> result = givenList.stream()
|
final Set<String> result = givenList.stream().collect(toSet());
|
||||||
.collect(toSet());
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsAll(givenList);
|
||||||
.containsAll(givenList);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
|
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
|
||||||
final List<String> result = givenList.stream()
|
final List<String> result = givenList.stream().collect(toCollection(LinkedList::new));
|
||||||
.collect(toCollection(LinkedList::new));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class);
|
||||||
.containsAll(givenList)
|
|
||||||
.isInstanceOf(LinkedList.class);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
|
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
|
||||||
assertThatThrownBy(() -> {
|
assertThatThrownBy(() -> {
|
||||||
givenList.stream()
|
givenList.stream().collect(toCollection(ImmutableList::of));
|
||||||
.collect(toCollection(ImmutableList::of));
|
|
||||||
}).isInstanceOf(UnsupportedOperationException.class);
|
}).isInstanceOf(UnsupportedOperationException.class);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
|
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
|
||||||
final Map<String, Integer> result = givenList.stream()
|
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length));
|
||||||
.collect(toMap(Function.identity(), String::length));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||||
.containsEntry("a", 1)
|
|
||||||
.containsEntry("bb", 2)
|
|
||||||
.containsEntry("ccc", 3)
|
|
||||||
.containsEntry("dd", 2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
|
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
|
||||||
final Map<String, Integer> result = givenList.stream()
|
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
||||||
.collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||||
.containsEntry("a", 1)
|
|
||||||
.containsEntry("bb", 2)
|
|
||||||
.containsEntry("ccc", 3)
|
|
||||||
.containsEntry("dd", 2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingAndThen_shouldCollect() throws Exception {
|
public void whenCollectingAndThen_shouldCollect() throws Exception {
|
||||||
final List<String> result = givenList.stream()
|
final List<String> result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
||||||
.collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class);
|
||||||
.containsAll(givenList)
|
|
||||||
.isInstanceOf(ImmutableList.class);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenJoining_shouldJoin() throws Exception {
|
public void whenJoining_shouldJoin() throws Exception {
|
||||||
final String result = givenList.stream()
|
final String result = givenList.stream().collect(joining());
|
||||||
.collect(joining());
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isEqualTo("abbcccdd");
|
||||||
.isEqualTo("abbcccdd");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
|
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
|
||||||
final String result = givenList.stream()
|
final String result = givenList.stream().collect(joining(" "));
|
||||||
.collect(joining(" "));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isEqualTo("a bb ccc dd");
|
||||||
.isEqualTo("a bb ccc dd");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
|
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
|
||||||
final String result = givenList.stream()
|
final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST"));
|
||||||
.collect(joining(" ", "PRE-", "-POST"));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isEqualTo("PRE-a bb ccc dd-POST");
|
||||||
.isEqualTo("PRE-a bb ccc dd-POST");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPartitioningBy_shouldPartition() throws Exception {
|
public void whenPartitioningBy_shouldPartition() throws Exception {
|
||||||
final Map<Boolean, List<String>> result = givenList.stream()
|
final Map<Boolean, List<String>> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2));
|
||||||
.collect(partitioningBy(s -> s.length() > 2));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> {
|
||||||
.containsKeys(true, false)
|
assertThat(booleanListMap.get(true)).contains("ccc");
|
||||||
.satisfies(booleanListMap -> {
|
|
||||||
assertThat(booleanListMap.get(true))
|
|
||||||
.contains("ccc");
|
|
||||||
|
|
||||||
assertThat(booleanListMap.get(false))
|
assertThat(booleanListMap.get(false)).contains("a", "bb", "dd");
|
||||||
.contains("a", "bb", "dd");
|
});
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCounting_shouldCount() throws Exception {
|
public void whenCounting_shouldCount() throws Exception {
|
||||||
final Long result = givenList.stream()
|
final Long result = givenList.stream().collect(counting());
|
||||||
.collect(counting());
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isEqualTo(4);
|
||||||
.isEqualTo(4);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSummarizing_shouldSummarize() throws Exception {
|
public void whenSummarizing_shouldSummarize() throws Exception {
|
||||||
final DoubleSummaryStatistics result = givenList.stream()
|
final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length));
|
||||||
.collect(summarizingDouble(String::length));
|
|
||||||
|
|
||||||
assertThat(result.getAverage())
|
assertThat(result.getAverage()).isEqualTo(2);
|
||||||
.isEqualTo(2);
|
assertThat(result.getCount()).isEqualTo(4);
|
||||||
assertThat(result.getCount())
|
assertThat(result.getMax()).isEqualTo(3);
|
||||||
.isEqualTo(4);
|
assertThat(result.getMin()).isEqualTo(1);
|
||||||
assertThat(result.getMax())
|
assertThat(result.getSum()).isEqualTo(8);
|
||||||
.isEqualTo(3);
|
|
||||||
assertThat(result.getMin())
|
|
||||||
.isEqualTo(1);
|
|
||||||
assertThat(result.getSum())
|
|
||||||
.isEqualTo(8);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenAveraging_shouldAverage() throws Exception {
|
public void whenAveraging_shouldAverage() throws Exception {
|
||||||
final Double result = givenList.stream()
|
final Double result = givenList.stream().collect(averagingDouble(String::length));
|
||||||
.collect(averagingDouble(String::length));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isEqualTo(2);
|
||||||
.isEqualTo(2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSumming_shouldSum() throws Exception {
|
public void whenSumming_shouldSum() throws Exception {
|
||||||
final Double result = givenList.stream()
|
final Double result = givenList.stream().collect(summingDouble(String::length));
|
||||||
.collect(summingDouble(String::length));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isEqualTo(8);
|
||||||
.isEqualTo(8);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenMaxingBy_shouldMaxBy() throws Exception {
|
public void whenMaxingBy_shouldMaxBy() throws Exception {
|
||||||
final Optional<String> result = givenList.stream()
|
final Optional<String> result = givenList.stream().collect(maxBy(Comparator.naturalOrder()));
|
||||||
.collect(maxBy(Comparator.naturalOrder()));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isPresent().hasValue("dd");
|
||||||
.isPresent()
|
|
||||||
.hasValue("dd");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGroupingBy_shouldGroupBy() throws Exception {
|
public void whenGroupingBy_shouldGroupBy() throws Exception {
|
||||||
final Map<Integer, Set<String>> result = givenList.stream()
|
final Map<Integer, Set<String>> result = givenList.stream().collect(groupingBy(String::length, toSet()));
|
||||||
.collect(groupingBy(String::length, toSet()));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc"));
|
||||||
.containsEntry(1, newHashSet("a"))
|
|
||||||
.containsEntry(2, newHashSet("bb", "dd"))
|
|
||||||
.containsEntry(3, newHashSet("ccc"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
|
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
|
||||||
final ImmutableSet<String> result = givenList.stream()
|
final ImmutableSet<String> result = givenList.stream().collect(toImmutableSet());
|
||||||
.collect(toImmutableSet());
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd");
|
||||||
.isInstanceOf(ImmutableSet.class)
|
|
||||||
.contains("a", "bb", "ccc", "dd");
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,24 +1,26 @@
|
||||||
package com.baeldung.completablefuture;
|
package com.baeldung.completablefuture;
|
||||||
|
|
||||||
import java.util.concurrent.*;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.concurrent.CancellationException;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
public class CompletableFutureUnitTest {
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
public class CompletableFutureTest {
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException {
|
public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException {
|
||||||
|
|
||||||
Future<String> completableFuture = calculateAsync();
|
Future<String> completableFuture = calculateAsync();
|
||||||
|
|
||||||
String result = completableFuture.get();
|
String result = completableFuture.get();
|
||||||
assertEquals("Hello", result);
|
assertEquals("Hello", result);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Future<String> calculateAsync() throws InterruptedException {
|
public Future<String> calculateAsync() throws InterruptedException {
|
||||||
|
@ -35,15 +37,12 @@ public class CompletableFutureTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenRunningCompletableFutureWithResult_thenGetMethodReturnsImmediately() throws InterruptedException, ExecutionException {
|
public void whenRunningCompletableFutureWithResult_thenGetMethodReturnsImmediately() throws InterruptedException, ExecutionException {
|
||||||
|
|
||||||
Future<String> completableFuture = CompletableFuture.completedFuture("Hello");
|
Future<String> completableFuture = CompletableFuture.completedFuture("Hello");
|
||||||
|
|
||||||
String result = completableFuture.get();
|
String result = completableFuture.get();
|
||||||
assertEquals("Hello", result);
|
assertEquals("Hello", result);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public Future<String> calculateAsyncWithCancellation() throws InterruptedException {
|
public Future<String> calculateAsyncWithCancellation() throws InterruptedException {
|
||||||
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
||||||
|
|
||||||
|
@ -56,90 +55,67 @@ public class CompletableFutureTest {
|
||||||
return completableFuture;
|
return completableFuture;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test(expected = CancellationException.class)
|
@Test(expected = CancellationException.class)
|
||||||
public void whenCancelingTheFuture_thenThrowsCancellationException() throws ExecutionException, InterruptedException {
|
public void whenCancelingTheFuture_thenThrowsCancellationException() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
Future<String> future = calculateAsyncWithCancellation();
|
Future<String> future = calculateAsyncWithCancellation();
|
||||||
future.get();
|
future.get();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() throws ExecutionException, InterruptedException {
|
public void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello");
|
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello");
|
||||||
|
|
||||||
assertEquals("Hello", future.get());
|
assertEquals("Hello", future.get());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
public void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
||||||
|
|
||||||
CompletableFuture<Void> future = completableFuture.thenAccept(s -> System.out.println("Computation returned: " + s));
|
CompletableFuture<Void> future = completableFuture.thenAccept(s -> System.out.println("Computation returned: " + s));
|
||||||
|
|
||||||
future.get();
|
future.get();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
public void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
||||||
|
|
||||||
CompletableFuture<Void> future = completableFuture.thenRun(() -> System.out.println("Computation finished."));
|
CompletableFuture<Void> future = completableFuture.thenRun(() -> System.out.println("Computation finished."));
|
||||||
|
|
||||||
future.get();
|
future.get();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenAddingThenApplyToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
public void whenAddingThenApplyToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
||||||
|
|
||||||
CompletableFuture<String> future = completableFuture.thenApply(s -> s + " World");
|
CompletableFuture<String> future = completableFuture.thenApply(s -> s + " World");
|
||||||
|
|
||||||
assertEquals("Hello World", future.get());
|
assertEquals("Hello World", future.get());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException {
|
public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException {
|
||||||
|
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
|
||||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
|
|
||||||
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
|
|
||||||
|
|
||||||
assertEquals("Hello World", completableFuture.get());
|
assertEquals("Hello World", completableFuture.get());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
|
public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
|
||||||
|
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2);
|
||||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
|
|
||||||
.thenCombine(CompletableFuture.supplyAsync(() -> " World"),
|
|
||||||
(s1, s2) -> s1 + s2);
|
|
||||||
|
|
||||||
assertEquals("Hello World", completableFuture.get());
|
assertEquals("Hello World", completableFuture.get());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
|
public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
|
||||||
|
CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> System.out.println(s1 + s2));
|
||||||
CompletableFuture.supplyAsync(() -> "Hello")
|
|
||||||
.thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"),
|
|
||||||
(s1, s2) -> System.out.println(s1 + s2));
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenFutureCombinedWithAllOfCompletes_thenAllFuturesAreDone() throws ExecutionException, InterruptedException {
|
public void whenFutureCombinedWithAllOfCompletes_thenAllFuturesAreDone() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
|
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
|
||||||
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Beautiful");
|
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Beautiful");
|
||||||
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "World");
|
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "World");
|
||||||
|
@ -154,17 +130,13 @@ public class CompletableFutureTest {
|
||||||
assertTrue(future2.isDone());
|
assertTrue(future2.isDone());
|
||||||
assertTrue(future3.isDone());
|
assertTrue(future3.isDone());
|
||||||
|
|
||||||
String combined = Stream.of(future1, future2, future3)
|
String combined = Stream.of(future1, future2, future3).map(CompletableFuture::join).collect(Collectors.joining(" "));
|
||||||
.map(CompletableFuture::join)
|
|
||||||
.collect(Collectors.joining(" "));
|
|
||||||
|
|
||||||
assertEquals("Hello Beautiful World", combined);
|
assertEquals("Hello Beautiful World", combined);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenFutureThrows_thenHandleMethodReceivesException() throws ExecutionException, InterruptedException {
|
public void whenFutureThrows_thenHandleMethodReceivesException() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
String name = null;
|
String name = null;
|
||||||
|
|
||||||
// ...
|
// ...
|
||||||
|
@ -177,12 +149,10 @@ public class CompletableFutureTest {
|
||||||
}).handle((s, t) -> s != null ? s : "Hello, Stranger!");
|
}).handle((s, t) -> s != null ? s : "Hello, Stranger!");
|
||||||
|
|
||||||
assertEquals("Hello, Stranger!", completableFuture.get());
|
assertEquals("Hello, Stranger!", completableFuture.get());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test(expected = ExecutionException.class)
|
@Test(expected = ExecutionException.class)
|
||||||
public void whenCompletingFutureExceptionally_thenGetMethodThrows() throws ExecutionException, InterruptedException {
|
public void whenCompletingFutureExceptionally_thenGetMethodThrows() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
||||||
|
|
||||||
// ...
|
// ...
|
||||||
|
@ -192,18 +162,15 @@ public class CompletableFutureTest {
|
||||||
// ...
|
// ...
|
||||||
|
|
||||||
completableFuture.get();
|
completableFuture.get();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenAddingThenApplyAsyncToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
public void whenAddingThenApplyAsyncToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
||||||
|
|
||||||
CompletableFuture<String> future = completableFuture.thenApplyAsync(s -> s + " World");
|
CompletableFuture<String> future = completableFuture.thenApplyAsync(s -> s + " World");
|
||||||
|
|
||||||
assertEquals("Hello World", future.get());
|
assertEquals("Hello World", future.get());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -14,7 +14,7 @@ import java.time.temporal.ChronoUnit;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
public class JavaUtilTimeTest {
|
public class JavaUtilTimeUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void currentTime() {
|
public void currentTime() {
|
|
@ -7,7 +7,7 @@ import java.time.Month;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class UseLocalDateTimeTest {
|
public class UseLocalDateTimeUnitTest {
|
||||||
|
|
||||||
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
|
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
|
||||||
|
|
|
@ -3,12 +3,11 @@ package com.baeldung.datetime;
|
||||||
import java.time.DayOfWeek;
|
import java.time.DayOfWeek;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.Month;
|
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class UseLocalDateTest {
|
public class UseLocalDateUnitTest {
|
||||||
|
|
||||||
UseLocalDate useLocalDate = new UseLocalDate();
|
UseLocalDate useLocalDate = new UseLocalDate();
|
||||||
|
|
|
@ -5,7 +5,7 @@ import java.time.LocalTime;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class UseLocalTimeTest {
|
public class UseLocalTimeUnitTest {
|
||||||
|
|
||||||
UseLocalTime useLocalTime = new UseLocalTime();
|
UseLocalTime useLocalTime = new UseLocalTime();
|
||||||
|
|
|
@ -1,15 +1,12 @@
|
||||||
package com.baeldung.datetime;
|
package com.baeldung.datetime;
|
||||||
|
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.time.Period;
|
import java.time.Period;
|
||||||
import java.time.ZoneId;
|
|
||||||
import java.time.ZonedDateTime;
|
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class UsePeriodTest {
|
public class UsePeriodUnitTest {
|
||||||
UsePeriod usingPeriod=new UsePeriod();
|
UsePeriod usingPeriod=new UsePeriod();
|
||||||
|
|
||||||
@Test
|
@Test
|
|
@ -7,7 +7,7 @@ import java.time.ZonedDateTime;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class UseZonedDateTimeTest {
|
public class UseZonedDateTimeUnitTest {
|
||||||
|
|
||||||
UseZonedDateTime zonedDateTime=new UseZonedDateTime();
|
UseZonedDateTime zonedDateTime=new UseZonedDateTime();
|
||||||
|
|
|
@ -13,7 +13,7 @@ import java.util.function.BiFunction;
|
||||||
|
|
||||||
import static com.baeldung.doublecolon.ComputerUtils.*;
|
import static com.baeldung.doublecolon.ComputerUtils.*;
|
||||||
|
|
||||||
public class TestComputerUtils {
|
public class ComputerUtilsUnitTest {
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setup() {
|
public void setup() {
|
|
@ -7,7 +7,6 @@ import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.io.UnsupportedEncodingException;
|
import java.io.UnsupportedEncodingException;
|
||||||
import java.net.MalformedURLException;
|
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
import java.net.URLDecoder;
|
import java.net.URLDecoder;
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
|
@ -15,13 +14,13 @@ import java.nio.charset.StandardCharsets;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.function.Function;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
public class EncoderDecoder {
|
import static java.util.stream.Collectors.joining;
|
||||||
|
|
||||||
private static final String URL = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253";
|
public class EncoderDecoderUnitTest {
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(EncoderDecoder.class);
|
|
||||||
|
private static final Logger LOGGER = LoggerFactory.getLogger(EncoderDecoderUnitTest.class);
|
||||||
|
private static final String testUrl = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253";
|
||||||
|
|
||||||
private String encodeValue(String value) {
|
private String encodeValue(String value) {
|
||||||
String encoded = null;
|
String encoded = null;
|
||||||
|
@ -46,7 +45,7 @@ public class EncoderDecoder {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenURL_whenAnalyze_thenCorrect() throws Exception {
|
public void givenURL_whenAnalyze_thenCorrect() throws Exception {
|
||||||
URL url = new URL(URL);
|
URL url = new URL(testUrl);
|
||||||
|
|
||||||
Assert.assertThat(url.getProtocol(), CoreMatchers.is("http"));
|
Assert.assertThat(url.getProtocol(), CoreMatchers.is("http"));
|
||||||
Assert.assertThat(url.getHost(), CoreMatchers.is("www.baeldung.com"));
|
Assert.assertThat(url.getHost(), CoreMatchers.is("www.baeldung.com"));
|
||||||
|
@ -60,25 +59,25 @@ public class EncoderDecoder {
|
||||||
requestParams.put("key2", "value@!$2");
|
requestParams.put("key2", "value@!$2");
|
||||||
requestParams.put("key3", "value%3");
|
requestParams.put("key3", "value%3");
|
||||||
|
|
||||||
String encodedQuery = requestParams.keySet().stream()
|
String encodedURL = requestParams.keySet().stream()
|
||||||
.map(key -> key + "=" + encodeValue(requestParams.get(key)))
|
.map(key -> key + "=" + encodeValue(requestParams.get(key)))
|
||||||
.collect(Collectors.joining("&"));
|
.collect(joining("&", "http://www.baeldung.com?", ""));
|
||||||
String encodedURL = "http://www.baeldung.com?" + encodedQuery;
|
|
||||||
|
|
||||||
Assert.assertThat(URL, CoreMatchers.is(encodedURL));
|
Assert.assertThat(testUrl, CoreMatchers.is(encodedURL));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenRequestParam_whenUTF8Scheme_thenDecodeRequestParams() throws Exception {
|
public void givenRequestParam_whenUTF8Scheme_thenDecodeRequestParams() throws Exception {
|
||||||
URL url = new URL(URL);
|
URL url = new URL(testUrl);
|
||||||
|
|
||||||
String query = url.getQuery();
|
String query = url.getQuery();
|
||||||
|
|
||||||
String decodedQuery = Arrays.stream(query.split("&"))
|
String decodedQuery = Arrays.stream(query.split("&"))
|
||||||
.map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1]))
|
.map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1]))
|
||||||
.collect(Collectors.joining("&"));
|
.collect(joining("&"));
|
||||||
|
|
||||||
Assert.assertEquals(
|
Assert.assertEquals(
|
||||||
"http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery);
|
"http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -9,7 +9,7 @@ import java.util.List;
|
||||||
|
|
||||||
import static junit.framework.TestCase.assertTrue;
|
import static junit.framework.TestCase.assertTrue;
|
||||||
|
|
||||||
public class PizzaTest {
|
public class PizzaUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPizaOrder_whenReady_thenDeliverable() {
|
public void givenPizaOrder_whenReady_thenDeliverable() {
|
|
@ -1,11 +1,5 @@
|
||||||
package com.baeldung.file;
|
package com.baeldung.file;
|
||||||
|
|
||||||
import org.apache.commons.io.FileUtils;
|
|
||||||
import org.hamcrest.CoreMatchers;
|
|
||||||
import org.hamcrest.Matchers;
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.FileInputStream;
|
import java.io.FileInputStream;
|
||||||
|
@ -20,7 +14,13 @@ import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
public class FileOperationsTest {
|
import org.apache.commons.io.FileUtils;
|
||||||
|
import org.hamcrest.CoreMatchers;
|
||||||
|
import org.hamcrest.Matchers;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class FileOperationsUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenFileName_whenUsingClassloader_thenFileData() throws IOException {
|
public void givenFileName_whenUsingClassloader_thenFileData() throws IOException {
|
||||||
|
@ -30,15 +30,15 @@ public class FileOperationsTest {
|
||||||
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
||||||
InputStream inputStream = new FileInputStream(file);
|
InputStream inputStream = new FileInputStream(file);
|
||||||
String data = readFromInputStream(inputStream);
|
String data = readFromInputStream(inputStream);
|
||||||
|
|
||||||
Assert.assertEquals(expectedData, data.trim());
|
Assert.assertEquals(expectedData, data.trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException {
|
public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException {
|
||||||
String expectedData = "Hello World from fileTest.txt!!!";
|
String expectedData = "Hello World from fileTest.txt!!!";
|
||||||
|
|
||||||
Class clazz = FileOperationsTest.class;
|
Class clazz = FileOperationsUnitTest.class;
|
||||||
InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
|
InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
|
||||||
String data = readFromInputStream(inputStream);
|
String data = readFromInputStream(inputStream);
|
||||||
|
|
||||||
|
@ -69,44 +69,44 @@ public class FileOperationsTest {
|
||||||
|
|
||||||
Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException {
|
public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException {
|
||||||
String expectedData = "Hello World from fileTest.txt!!!";
|
String expectedData = "Hello World from fileTest.txt!!!";
|
||||||
|
|
||||||
ClassLoader classLoader = getClass().getClassLoader();
|
ClassLoader classLoader = getClass().getClassLoader();
|
||||||
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
||||||
String data = FileUtils.readFileToString(file);
|
String data = FileUtils.readFileToString(file);
|
||||||
|
|
||||||
Assert.assertEquals(expectedData, data.trim());
|
Assert.assertEquals(expectedData, data.trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException {
|
public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException {
|
||||||
String expectedData = "Hello World from fileTest.txt!!!";
|
String expectedData = "Hello World from fileTest.txt!!!";
|
||||||
|
|
||||||
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
||||||
|
|
||||||
byte[] fileBytes = Files.readAllBytes(path);
|
byte[] fileBytes = Files.readAllBytes(path);
|
||||||
String data = new String(fileBytes);
|
String data = new String(fileBytes);
|
||||||
|
|
||||||
Assert.assertEquals(expectedData, data.trim());
|
Assert.assertEquals(expectedData, data.trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException {
|
public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException {
|
||||||
String expectedData = "Hello World from fileTest.txt!!!";
|
String expectedData = "Hello World from fileTest.txt!!!";
|
||||||
|
|
||||||
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
||||||
|
|
||||||
StringBuilder data = new StringBuilder();
|
StringBuilder data = new StringBuilder();
|
||||||
Stream<String> lines = Files.lines(path);
|
Stream<String> lines = Files.lines(path);
|
||||||
lines.forEach(line -> data.append(line).append("\n"));
|
lines.forEach(line -> data.append(line).append("\n"));
|
||||||
lines.close();
|
lines.close();
|
||||||
|
|
||||||
Assert.assertEquals(expectedData, data.toString().trim());
|
Assert.assertEquals(expectedData, data.toString().trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
private String readFromInputStream(InputStream inputStream) throws IOException {
|
private String readFromInputStream(InputStream inputStream) throws IOException {
|
||||||
StringBuilder resultStringBuilder = new StringBuilder();
|
StringBuilder resultStringBuilder = new StringBuilder();
|
||||||
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
|
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
|
|
@ -1,7 +1,8 @@
|
||||||
package com.baeldung.functionalinterface;
|
package com.baeldung.functionalinterface;
|
||||||
|
|
||||||
import com.google.common.util.concurrent.Uninterruptibles;
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
import org.junit.Test;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
@ -13,54 +14,43 @@ import java.util.function.Supplier;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class FunctionalInterfaceTest {
|
import com.google.common.util.concurrent.Uninterruptibles;
|
||||||
|
|
||||||
|
public class FunctionalInterfaceUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
|
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
|
||||||
|
|
||||||
Map<String, Integer> nameMap = new HashMap<>();
|
Map<String, Integer> nameMap = new HashMap<>();
|
||||||
Integer value = nameMap.computeIfAbsent("John", s -> s.length());
|
Integer value = nameMap.computeIfAbsent("John", s -> s.length());
|
||||||
|
|
||||||
assertEquals(new Integer(4), nameMap.get("John"));
|
assertEquals(new Integer(4), nameMap.get("John"));
|
||||||
assertEquals(new Integer(4), value);
|
assertEquals(new Integer(4), value);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPassingMethodReferenceToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
|
public void whenPassingMethodReferenceToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
|
||||||
|
|
||||||
Map<String, Integer> nameMap = new HashMap<>();
|
Map<String, Integer> nameMap = new HashMap<>();
|
||||||
Integer value = nameMap.computeIfAbsent("John", String::length);
|
Integer value = nameMap.computeIfAbsent("John", String::length);
|
||||||
|
|
||||||
assertEquals(new Integer(4), nameMap.get("John"));
|
assertEquals(new Integer(4), nameMap.get("John"));
|
||||||
assertEquals(new Integer(4), value);
|
assertEquals(new Integer(4), value);
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public byte[] transformArray(short[] array, ShortToByteFunction function) {
|
|
||||||
byte[] transformedArray = new byte[array.length];
|
|
||||||
for (int i = 0; i < array.length; i++) {
|
|
||||||
transformedArray[i] = function.applyAsByte(array[i]);
|
|
||||||
}
|
|
||||||
return transformedArray;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingCustomFunctionalInterfaceForPrimitives_thenCanUseItAsLambda() {
|
public void whenUsingCustomFunctionalInterfaceForPrimitives_thenCanUseItAsLambda() {
|
||||||
|
|
||||||
short[] array = {(short) 1, (short) 2, (short) 3};
|
short[] array = { (short) 1, (short) 2, (short) 3 };
|
||||||
byte[] transformedArray = transformArray(array, s -> (byte) (s * 2));
|
byte[] transformedArray = transformArray(array, s -> (byte) (s * 2));
|
||||||
|
|
||||||
byte[] expectedArray = {(byte) 2, (byte) 4, (byte) 6};
|
byte[] expectedArray = { (byte) 2, (byte) 4, (byte) 6 };
|
||||||
assertArrayEquals(expectedArray, transformedArray);
|
assertArrayEquals(expectedArray, transformedArray);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingBiFunction_thenCanUseItToReplaceMapValues() {
|
public void whenUsingBiFunction_thenCanUseItToReplaceMapValues() {
|
||||||
|
|
||||||
Map<String, Integer> salaries = new HashMap<>();
|
Map<String, Integer> salaries = new HashMap<>();
|
||||||
salaries.put("John", 40000);
|
salaries.put("John", 40000);
|
||||||
salaries.put("Freddy", 30000);
|
salaries.put("Freddy", 30000);
|
||||||
|
@ -71,22 +61,18 @@ public class FunctionalInterfaceTest {
|
||||||
assertEquals(new Integer(50000), salaries.get("John"));
|
assertEquals(new Integer(50000), salaries.get("John"));
|
||||||
assertEquals(new Integer(30000), salaries.get("Freddy"));
|
assertEquals(new Integer(30000), salaries.get("Freddy"));
|
||||||
assertEquals(new Integer(60000), salaries.get("Samuel"));
|
assertEquals(new Integer(60000), salaries.get("Samuel"));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPassingLambdaToThreadConstructor_thenLambdaInferredToRunnable() {
|
public void whenPassingLambdaToThreadConstructor_thenLambdaInferredToRunnable() {
|
||||||
|
|
||||||
Thread thread = new Thread(() -> System.out.println("Hello From Another Thread"));
|
Thread thread = new Thread(() -> System.out.println("Hello From Another Thread"));
|
||||||
thread.start();
|
thread.start();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingSupplierToGenerateNumbers_thenCanUseItInStreamGenerate() {
|
public void whenUsingSupplierToGenerateNumbers_thenCanUseItInStreamGenerate() {
|
||||||
|
|
||||||
int[] fibs = {0, 1};
|
int[] fibs = { 0, 1 };
|
||||||
Stream<Integer> fibonacci = Stream.generate(() -> {
|
Stream<Integer> fibonacci = Stream.generate(() -> {
|
||||||
int result = fibs[1];
|
int result = fibs[1];
|
||||||
int fib3 = fibs[0] + fibs[1];
|
int fib3 = fibs[0] + fibs[1];
|
||||||
|
@ -95,55 +81,44 @@ public class FunctionalInterfaceTest {
|
||||||
return result;
|
return result;
|
||||||
});
|
});
|
||||||
|
|
||||||
List<Integer> fibonacci5 = fibonacci.limit(5)
|
List<Integer> fibonacci5 = fibonacci.limit(5).collect(Collectors.toList());
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertEquals(new Integer(1), fibonacci5.get(0));
|
assertEquals(new Integer(1), fibonacci5.get(0));
|
||||||
assertEquals(new Integer(1), fibonacci5.get(1));
|
assertEquals(new Integer(1), fibonacci5.get(1));
|
||||||
assertEquals(new Integer(2), fibonacci5.get(2));
|
assertEquals(new Integer(2), fibonacci5.get(2));
|
||||||
assertEquals(new Integer(3), fibonacci5.get(3));
|
assertEquals(new Integer(3), fibonacci5.get(3));
|
||||||
assertEquals(new Integer(5), fibonacci5.get(4));
|
assertEquals(new Integer(5), fibonacci5.get(4));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingConsumerInForEach_thenConsumerExecutesForEachListElement() {
|
public void whenUsingConsumerInForEach_thenConsumerExecutesForEachListElement() {
|
||||||
|
|
||||||
List<String> names = Arrays.asList("John", "Freddy", "Samuel");
|
List<String> names = Arrays.asList("John", "Freddy", "Samuel");
|
||||||
names.forEach(name -> System.out.println("Hello, " + name));
|
names.forEach(name -> System.out.println("Hello, " + name));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingBiConsumerInForEach_thenConsumerExecutesForEachMapElement() {
|
public void whenUsingBiConsumerInForEach_thenConsumerExecutesForEachMapElement() {
|
||||||
|
|
||||||
Map<String, Integer> ages = new HashMap<>();
|
Map<String, Integer> ages = new HashMap<>();
|
||||||
ages.put("John", 25);
|
ages.put("John", 25);
|
||||||
ages.put("Freddy", 24);
|
ages.put("Freddy", 24);
|
||||||
ages.put("Samuel", 30);
|
ages.put("Samuel", 30);
|
||||||
|
|
||||||
ages.forEach((name, age) -> System.out.println(name + " is " + age + " years old"));
|
ages.forEach((name, age) -> System.out.println(name + " is " + age + " years old"));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() {
|
public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() {
|
||||||
|
|
||||||
List<String> names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David");
|
List<String> names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David");
|
||||||
|
|
||||||
List<String> namesWithA = names.stream()
|
List<String> namesWithA = names.stream().filter(name -> name.startsWith("A")).collect(Collectors.toList());
|
||||||
.filter(name -> name.startsWith("A"))
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertEquals(2, namesWithA.size());
|
assertEquals(2, namesWithA.size());
|
||||||
assertTrue(namesWithA.contains("Angela"));
|
assertTrue(namesWithA.contains("Angela"));
|
||||||
assertTrue(namesWithA.contains("Aaron"));
|
assertTrue(namesWithA.contains("Aaron"));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingUnaryOperatorWithReplaceAll_thenAllValuesInTheListAreReplaced() {
|
public void whenUsingUnaryOperatorWithReplaceAll_thenAllValuesInTheListAreReplaced() {
|
||||||
|
|
||||||
List<String> names = Arrays.asList("bob", "josh", "megan");
|
List<String> names = Arrays.asList("bob", "josh", "megan");
|
||||||
|
|
||||||
names.replaceAll(String::toUpperCase);
|
names.replaceAll(String::toUpperCase);
|
||||||
|
@ -151,7 +126,6 @@ public class FunctionalInterfaceTest {
|
||||||
assertEquals("BOB", names.get(0));
|
assertEquals("BOB", names.get(0));
|
||||||
assertEquals("JOSH", names.get(1));
|
assertEquals("JOSH", names.get(1));
|
||||||
assertEquals("MEGAN", names.get(2));
|
assertEquals("MEGAN", names.get(2));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -159,8 +133,7 @@ public class FunctionalInterfaceTest {
|
||||||
|
|
||||||
List<Integer> values = Arrays.asList(3, 5, 8, 9, 12);
|
List<Integer> values = Arrays.asList(3, 5, 8, 9, 12);
|
||||||
|
|
||||||
int sum = values.stream()
|
int sum = values.stream().reduce(0, (i1, i2) -> i1 + i2);
|
||||||
.reduce(0, (i1, i2) -> i1 + i2);
|
|
||||||
|
|
||||||
assertEquals(37, sum);
|
assertEquals(37, sum);
|
||||||
|
|
||||||
|
@ -178,10 +151,6 @@ public class FunctionalInterfaceTest {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public double squareLazy(Supplier<Double> lazyValue) {
|
|
||||||
return Math.pow(lazyValue.get(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingSupplierToGenerateValue_thenValueIsGeneratedLazily() {
|
public void whenUsingSupplierToGenerateValue_thenValueIsGeneratedLazily() {
|
||||||
|
|
||||||
|
@ -196,4 +165,18 @@ public class FunctionalInterfaceTest {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
|
||||||
|
public double squareLazy(Supplier<Double> lazyValue) {
|
||||||
|
return Math.pow(lazyValue.get(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] transformArray(short[] array, ShortToByteFunction function) {
|
||||||
|
byte[] transformedArray = new byte[array.length];
|
||||||
|
for (int i = 0; i < array.length; i++) {
|
||||||
|
transformedArray[i] = function.applyAsByte(array[i]);
|
||||||
|
}
|
||||||
|
return transformedArray;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -0,0 +1,39 @@
|
||||||
|
package com.baeldung.java.networking.udp;
|
||||||
|
|
||||||
|
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
|
||||||
|
public class UDPIntegrationTest {
|
||||||
|
private EchoClient client;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() throws IOException {
|
||||||
|
new EchoServer().start();
|
||||||
|
client = new EchoClient();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCanSendAndReceivePacket_thenCorrect1() {
|
||||||
|
String echo = client.sendEcho("hello server");
|
||||||
|
assertEquals("hello server", echo);
|
||||||
|
echo = client.sendEcho("server is working");
|
||||||
|
assertFalse(echo.equals("hello server"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDown() {
|
||||||
|
stopEchoServer();
|
||||||
|
client.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void stopEchoServer() {
|
||||||
|
client.sendEcho("end");
|
||||||
|
}
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue