Merge branch 'eugenp:master' into master

This commit is contained in:
Maiklins 2021-08-17 09:45:20 +02:00 committed by GitHub
commit 5d69f00f86
763 changed files with 18966 additions and 1921 deletions

11
.gitignore vendored
View File

@ -89,5 +89,14 @@ testing-modules/report-*.json
libraries-2/*.db
apache-spark/data/output
logs/
libraries-data-io/*.docx
persistence-modules/spring-hibernate-5/com.*
spring-boot-modules/spring-boot-react/frontend/build
spring-boot-modules/spring-boot-react/frontend/node
spring-boot-modules/spring-boot-react/frontend/yarn.lock
spring-boot-modules/spring-boot-properties-3/*.log
# SDKMan
.sdkmanrc
.sdkmanrc

View File

@ -20,19 +20,16 @@
<version>${org.assertj.core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
@ -43,13 +40,11 @@
<artifactId>converter-jackson</artifactId>
<version>${retrofit.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.lang3.version}</version>
</dependency>
<dependency>
<groupId>pl.pragmatists</groupId>
<artifactId>JUnitParams</artifactId>

View File

@ -39,7 +39,6 @@
<artifactId>junit-platform-commons</artifactId>
<version>${junit.platform.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>

View File

@ -12,7 +12,7 @@ public class BinarySearch {
while (low <= high) {
int mid = (low + high) / 2;
int mid = low + ((high - low) / 2);
if (sortedArray[mid] < key) {
low = mid + 1;
@ -28,7 +28,7 @@ public class BinarySearch {
public int runBinarySearchRecursively(int[] sortedArray, int key, int low, int high) {
int middle = (low + high) / 2;
int middle = low + ((high - low) / 2);
if (high < low) {
return -1;
}

View File

@ -20,4 +20,4 @@
</dependency>
</dependencies>
</project>
</project>

View File

@ -37,4 +37,4 @@
</plugins>
</build>
</project>
</project>

View File

@ -52,4 +52,4 @@
<httpclient.version>4.5.2</httpclient.version>
</properties>
</project>
</project>

View File

@ -107,4 +107,4 @@
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
</properties>
</project>
</project>

View File

@ -38,4 +38,4 @@
<cxf.version>3.1.8</cxf.version>
</properties>
</project>
</project>

View File

@ -18,4 +18,4 @@
<module>sse-jaxrs-client</module>
</modules>
</project>
</project>

View File

@ -14,7 +14,6 @@
</parent>
<dependencies>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
@ -33,7 +32,6 @@
<version>${bind-api.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
@ -85,4 +83,4 @@
<bind-api.version>1.0</bind-api.version>
</properties>
</project>
</project>

View File

@ -183,7 +183,6 @@
</execution>
</executions>
</plugin>
<!-- meecrowave -->
<plugin>
<groupId>org.apache.meecrowave</groupId>
@ -216,4 +215,4 @@
<solr.solr-solrj.version>6.4.0</solr.solr-solrj.version>
</properties>
</project>
</project>

View File

@ -6,7 +6,12 @@ spring:
application-path: /odata
jpa:
defer-datasource-initialization: true
show-sql: true
open-in-view: false
hibernate:
ddl-auto: update
ddl-auto: update
sql:
init:
mode: always

View File

@ -25,4 +25,5 @@
<geode.core>1.6.0</geode.core>
<rocketmq.version>2.0.4</rocketmq.version>
</properties>
</project>

View File

@ -94,20 +94,20 @@
<repositories>
<repository>
<id>SparkPackagesRepo</id>
<url>http://dl.bintray.com/spark-packages/maven</url>
<url>https://repos.spark-packages.org</url>
</repository>
</repositories>
<properties>
<org.apache.spark.spark-core.version>2.3.0</org.apache.spark.spark-core.version>
<org.apache.spark.spark-sql.version>2.3.0</org.apache.spark.spark-sql.version>
<org.apache.spark.spark-streaming.version>2.3.0</org.apache.spark.spark-streaming.version>
<org.apache.spark.spark-mllib.version>2.3.0</org.apache.spark.spark-mllib.version>
<org.apache.spark.spark-graphx.version>2.3.0</org.apache.spark.spark-graphx.version>
<graphframes.version>0.7.0-spark2.4-s_2.11</graphframes.version>
<org.apache.spark.spark-streaming-kafka.version>2.3.0</org.apache.spark.spark-streaming-kafka.version>
<com.datastax.spark.spark-cassandra-connector.version>2.3.0</com.datastax.spark.spark-cassandra-connector.version>
<com.datastax.spark.spark-cassandra-connector-java.version>1.5.2</com.datastax.spark.spark-cassandra-connector-java.version>
<org.apache.spark.spark-core.version>2.4.8</org.apache.spark.spark-core.version>
<org.apache.spark.spark-sql.version>2.4.8</org.apache.spark.spark-sql.version>
<org.apache.spark.spark-streaming.version>2.4.8</org.apache.spark.spark-streaming.version>
<org.apache.spark.spark-mllib.version>2.4.8</org.apache.spark.spark-mllib.version>
<org.apache.spark.spark-graphx.version>2.4.8</org.apache.spark.spark-graphx.version>
<graphframes.version>0.8.1-spark3.0-s_2.12</graphframes.version>
<org.apache.spark.spark-streaming-kafka.version>2.4.8</org.apache.spark.spark-streaming-kafka.version>
<com.datastax.spark.spark-cassandra-connector.version>2.5.2</com.datastax.spark.spark-cassandra-connector.version>
<com.datastax.spark.spark-cassandra-connector-java.version>1.6.0-M1</com.datastax.spark.spark-cassandra-connector-java.version>
</properties>
</project>

View File

@ -77,7 +77,6 @@
<optimize>true</optimize>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
@ -88,7 +87,6 @@
</systemPropertyVariables>
</configuration>
</plugin>
<!-- Run the application using "mvn jetty:run" -->
<plugin>
<groupId>org.mortbay.jetty</groupId>
@ -119,7 +117,6 @@
<id>jboss</id>
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
<!-- This repository is only needed when the Tapestry version is a preview release, rather than
a final release. -->
<repository>

View File

@ -68,4 +68,4 @@
<asciidoctorj-pdf.plugin.version>1.5.0-alpha.15</asciidoctorj-pdf.plugin.version>
</properties>
</project>
</project>

View File

@ -31,4 +31,4 @@
<atomix-all.version>1.0.0-rc9</atomix-all.version>
</properties>
</project>
</project>

View File

@ -20,4 +20,4 @@
<module>todo-reminder/ToDoFunction</module>
</modules>
</project>
</project>

View File

@ -1,15 +1,12 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>helloworld</groupId>
<artifactId>HelloWorld</artifactId>
<artifactId>ToDoFunction</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>To Do Application Example.</name>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<name>ToDoFunction</name>
<dependencies>
<dependency>
@ -18,9 +15,9 @@
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
<version>3.6.0</version>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>uk.org.webcompere</groupId>
@ -58,10 +55,10 @@
<version>5.0.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>uk.org.webcompere</groupId>
@ -84,22 +81,28 @@
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<configuration>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<configuration>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
</project>

View File

@ -93,4 +93,5 @@
<spring.version>2.2.1.RELEASE</spring.version>
<awssdk.version>2.10.27</awssdk.version>
</properties>
</project>

View File

@ -83,39 +83,6 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.bazaarvoice.maven.plugins</groupId>
<artifactId>process-exec-maven-plugin</artifactId>
<version>${process-exec-maven-plugin.version}</version>
<executions>
<!--Start Blade -->
<execution>
<id>blade-process</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
<configuration>
<name>Blade</name>
<waitForInterrupt>false</waitForInterrupt>
<arguments>
<argument>java</argument>
<argument>-jar</argument>
<argument>blade.jar</argument>
</arguments>
</configuration>
</execution>
<!--Stop all processes in reverse order -->
<execution>
<id>stop-all</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop-all</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>${assembly.plugin.version}</version>

View File

@ -48,13 +48,11 @@
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
</plugin>
</plugins>
</build>

View File

@ -1,6 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.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>
@ -20,4 +19,4 @@
<module>cf-uaa-oauth2-resource-server</module>
</modules>
</project>
</project>

View File

@ -161,21 +161,6 @@
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>bintray</id>
<name>Groovy Bintray</name>
<url>https://dl.bintray.com/groovy/maven</url>
<releases>
<!-- avoid automatic updates -->
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<properties>
<junit.platform.version>1.0.0</junit.platform.version>
<hsqldb.version>2.4.0</hsqldb.version>

View File

@ -55,6 +55,23 @@
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>jakarta.xml.ws</groupId>
<artifactId>jakarta.xml.ws-api</artifactId>
<version>${jakarta.ws-api.version}</version>
</dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<version>${jaxws-rt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-ri</artifactId>
<version>${jaxws-ri.version}</version>
<type>pom</type>
</dependency>
</dependencies>
<build>
@ -68,6 +85,20 @@
<target>${maven.compiler.target.version}</target>
</configuration>
</plugin>
<!-- jax-ws maven plugin -->
<plugin>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>${jaxws-maven-plugin.version}</version>
<configuration>
<wsdlUrls>
<wsdlUrl>http://localhost:8888/ws/country?wsdl</wsdlUrl>
</wsdlUrls>
<keep>true</keep>
<packageName>com.baeldung.soap.ws.client.generated</packageName>
<sourceDestDir>src/main/java</sourceDestDir>
</configuration>
</plugin>
</plugins>
</build>
@ -79,6 +110,10 @@
<assertj.version>3.17.2</assertj.version>
<mockserver.version>5.11.1</mockserver.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
<jakarta.ws-api.version>3.0.0</jakarta.ws-api.version>
<jaxws-rt.version>3.0.0</jaxws-rt.version>
<jaxws-ri.version>2.3.1</jaxws-ri.version>
<jaxws-maven-plugin.version>2.3.2</jaxws-maven-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,135 @@
package com.baeldung.soap.ws.client.generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for country complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="country"&gt;
* &lt;complexContent&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
* &lt;sequence&gt;
* &lt;element name="capital" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt;
* &lt;element name="currency" type="{http://server.ws.soap.baeldung.com/}currency" minOccurs="0"/&gt;
* &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt;
* &lt;element name="population" type="{http://www.w3.org/2001/XMLSchema}int"/&gt;
* &lt;/sequence&gt;
* &lt;/restriction&gt;
* &lt;/complexContent&gt;
* &lt;/complexType&gt;
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "country", propOrder = {
"capital",
"currency",
"name",
"population"
})
public class Country {
protected String capital;
@XmlSchemaType(name = "string")
protected Currency currency;
protected String name;
protected int population;
/**
* Gets the value of the capital property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCapital() {
return capital;
}
/**
* Sets the value of the capital property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCapital(String value) {
this.capital = value;
}
/**
* Gets the value of the currency property.
*
* @return
* possible object is
* {@link Currency }
*
*/
public Currency getCurrency() {
return currency;
}
/**
* Sets the value of the currency property.
*
* @param value
* allowed object is
* {@link Currency }
*
*/
public void setCurrency(Currency value) {
this.currency = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the population property.
*
*/
public int getPopulation() {
return population;
}
/**
* Sets the value of the population property.
*
*/
public void setPopulation(int value) {
this.population = value;
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.soap.ws.client.generated;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.Action;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.3.2
* Generated source version: 2.2
*
*/
@WebService(name = "CountryService", targetNamespace = "http://server.ws.soap.baeldung.com/")
@SOAPBinding(style = SOAPBinding.Style.RPC)
@XmlSeeAlso({
ObjectFactory.class
})
public interface CountryService {
/**
*
* @param arg0
* @return
* returns com.baeldung.soap.ws.client.generated.Country
*/
@WebMethod
@WebResult(partName = "return")
@Action(input = "http://server.ws.soap.baeldung.com/CountryService/findByNameRequest", output = "http://server.ws.soap.baeldung.com/CountryService/findByNameResponse")
public Country findByName(
@WebParam(name = "arg0", partName = "arg0")
String arg0);
}

View File

@ -0,0 +1,94 @@
package com.baeldung.soap.ws.client.generated;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.3.2
* Generated source version: 2.2
*
*/
@WebServiceClient(name = "CountryServiceImplService", targetNamespace = "http://server.ws.soap.baeldung.com/", wsdlLocation = "http://localhost:8888/ws/country?wsdl")
public class CountryServiceImplService
extends Service
{
private final static URL COUNTRYSERVICEIMPLSERVICE_WSDL_LOCATION;
private final static WebServiceException COUNTRYSERVICEIMPLSERVICE_EXCEPTION;
private final static QName COUNTRYSERVICEIMPLSERVICE_QNAME = new QName("http://server.ws.soap.baeldung.com/", "CountryServiceImplService");
static {
URL url = null;
WebServiceException e = null;
try {
url = new URL("http://localhost:8888/ws/country?wsdl");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
COUNTRYSERVICEIMPLSERVICE_WSDL_LOCATION = url;
COUNTRYSERVICEIMPLSERVICE_EXCEPTION = e;
}
public CountryServiceImplService() {
super(__getWsdlLocation(), COUNTRYSERVICEIMPLSERVICE_QNAME);
}
public CountryServiceImplService(WebServiceFeature... features) {
super(__getWsdlLocation(), COUNTRYSERVICEIMPLSERVICE_QNAME, features);
}
public CountryServiceImplService(URL wsdlLocation) {
super(wsdlLocation, COUNTRYSERVICEIMPLSERVICE_QNAME);
}
public CountryServiceImplService(URL wsdlLocation, WebServiceFeature... features) {
super(wsdlLocation, COUNTRYSERVICEIMPLSERVICE_QNAME, features);
}
public CountryServiceImplService(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public CountryServiceImplService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
super(wsdlLocation, serviceName, features);
}
/**
*
* @return
* returns CountryService
*/
@WebEndpoint(name = "CountryServiceImplPort")
public CountryService getCountryServiceImplPort() {
return super.getPort(new QName("http://server.ws.soap.baeldung.com/", "CountryServiceImplPort"), CountryService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns CountryService
*/
@WebEndpoint(name = "CountryServiceImplPort")
public CountryService getCountryServiceImplPort(WebServiceFeature... features) {
return super.getPort(new QName("http://server.ws.soap.baeldung.com/", "CountryServiceImplPort"), CountryService.class, features);
}
private static URL __getWsdlLocation() {
if (COUNTRYSERVICEIMPLSERVICE_EXCEPTION!= null) {
throw COUNTRYSERVICEIMPLSERVICE_EXCEPTION;
}
return COUNTRYSERVICEIMPLSERVICE_WSDL_LOCATION;
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.soap.ws.client.generated;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for currency.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* &lt;simpleType name="currency"&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt;
* &lt;enumeration value="EUR"/&gt;
* &lt;enumeration value="INR"/&gt;
* &lt;enumeration value="USD"/&gt;
* &lt;/restriction&gt;
* &lt;/simpleType&gt;
* </pre>
*
*/
@XmlType(name = "currency")
@XmlEnum
public enum Currency {
EUR,
INR,
USD;
public String value() {
return name();
}
public static Currency fromValue(String v) {
return valueOf(v);
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.soap.ws.client.generated;
import javax.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the com.baeldung.soap.ws.client.generated package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.baeldung.soap.ws.client.generated
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link Country }
*
*/
public Country createCountry() {
return new Country();
}
}

View File

@ -0,0 +1,2 @@
@javax.xml.bind.annotation.XmlSchema(namespace = "http://server.ws.soap.baeldung.com/")
package com.baeldung.soap.ws.client.generated;

View File

@ -0,0 +1,41 @@
package com.baeldung.soap.ws.server;
public class Country {
protected String name;
protected int population;
protected String capital;
protected Currency currency;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
public String getCapital() {
return capital;
}
public void setCapital(String capital) {
this.capital = capital;
}
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.soap.ws.server;
import java.util.HashMap;
import java.util.Map;
public class CountryRepository {
private static final Map<String, Country> countries = new HashMap<>();
{
initData();
}
private final static void initData() {
Country usa = new Country();
usa.setName("USA");
usa.setCapital("Washington D.C.");
usa.setCurrency(Currency.USD);
usa.setPopulation(323947000);
countries.put(usa.getName(), usa);
Country india = new Country();
india.setName("India");
india.setCapital("New Delhi");
india.setCurrency(Currency.INR);
india.setPopulation(1295210000);
countries.put(india.getName(), india);
Country france = new Country();
france.setName("France");
france.setCapital("Paris");
france.setCurrency(Currency.EUR);
france.setPopulation(66710000);
countries.put(france.getName(), france);
}
public Country findCountry(String name) {
return countries.get(name);
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.soap.ws.server;
import jakarta.jws.WebMethod;
import jakarta.jws.WebService;
import jakarta.jws.soap.SOAPBinding;
import jakarta.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style=Style.RPC)
public interface CountryService {
@WebMethod
Country findByName(String name);
}

View File

@ -0,0 +1,15 @@
package com.baeldung.soap.ws.server;
import jakarta.jws.WebService;
@WebService(endpointInterface = "com.baeldung.soap.ws.server.CountryService")
public class CountryServiceImpl implements CountryService {
private CountryRepository countryRepository = new CountryRepository();
@Override
public Country findByName(String name) {
return countryRepository.findCountry(name);
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.soap.ws.server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.xml.ws.Endpoint;
public class CountryServicePublisher {
private static final Logger logger = LoggerFactory.getLogger(CountryServicePublisher.class);
public static void main(String[] args) {
Endpoint endpoint = Endpoint.create(new CountryServiceImpl());
endpoint.publish("http://localhost:8888/ws/country");
logger.info("Country web service ready to consume requests!");
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.soap.ws.server;
public enum Currency {
EUR, INR, USD;
public String value() {
return name();
}
public static Currency fromValue(String v) {
return valueOf(v);
}
}

View File

@ -9,7 +9,7 @@ public class VersionUnitTest {
@Test
public void givenJava_whenUsingRuntime_thenGetVersion() {
String expectedVersion = "11";
String expectedVersion = "15";
Runtime.Version runtimeVersion = Runtime.version();
String version = String.valueOf(runtimeVersion.version().get(0));
Assertions.assertThat(version).isEqualTo(expectedVersion);

View File

@ -17,8 +17,8 @@ import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.Disabled;
public class HttpRequestUnitTest {
@ -51,10 +51,10 @@ public class HttpRequestUnitTest {
/*
* This test will fail as soon as the given URL returns a HTTP 2 response.
* Therefore, let's leave it commented out.
* Therefore, let's leave it ignored.
* */
@Test
@Disabled
@Test
@Ignore
public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))

View File

@ -1,49 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>
<artifactId>core-java-12</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-12</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
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>
<artifactId>core-java-12</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-12</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
<compilerArgs>--enable-preview</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
<compilerArgs>--enable-preview</compilerArgs>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>12</maven.compiler.source.version>
<maven.compiler.target.version>12</maven.compiler.target.version>
<assertj.version>3.6.1</assertj.version>
</properties>
<properties>
<maven.compiler.source.version>12</maven.compiler.source.version>
<maven.compiler.target.version>12</maven.compiler.target.version>
<assertj.version>3.6.1</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,88 @@
package com.baeldung.file.content.comparison;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
public class CompareFileContents {
public static long filesCompareByByte(Path path1, Path path2) throws IOException {
if (path1.getFileSystem()
.provider()
.isSameFile(path1, path2)) {
return -1;
}
try (BufferedInputStream fis1 = new BufferedInputStream(new FileInputStream(path1.toFile()));
BufferedInputStream fis2 = new BufferedInputStream(new FileInputStream(path2.toFile()))) {
int ch = 0;
long pos = 1;
while ((ch = fis1.read()) != -1) {
if (ch != fis2.read()) {
return pos;
}
pos++;
}
if (fis2.read() == -1) {
return -1;
} else {
return pos;
}
}
}
public static long filesCompareByLine(Path path1, Path path2) throws IOException {
if (path1.getFileSystem()
.provider()
.isSameFile(path1, path2)) {
return -1;
}
try (BufferedReader bf1 = Files.newBufferedReader(path1);
BufferedReader bf2 = Files.newBufferedReader(path2)) {
long lineNumber = 1;
String line1 = "", line2 = "";
while ((line1 = bf1.readLine()) != null) {
line2 = bf2.readLine();
if (line2 == null || !line1.equals(line2)) {
return lineNumber;
}
lineNumber++;
}
if (bf2.readLine() == null) {
return -1;
} else {
return lineNumber;
}
}
}
public static boolean compareByMemoryMappedFiles(Path path1, Path path2) throws IOException {
try (RandomAccessFile randomAccessFile1 = new RandomAccessFile(path1.toFile(), "r");
RandomAccessFile randomAccessFile2 = new RandomAccessFile(path2.toFile(), "r")) {
FileChannel ch1 = randomAccessFile1.getChannel();
FileChannel ch2 = randomAccessFile2.getChannel();
if (ch1.size() != ch2.size()) {
return false;
}
long size = ch1.size();
MappedByteBuffer m1 = ch1.map(FileChannel.MapMode.READ_ONLY, 0L, size);
MappedByteBuffer m2 = ch2.map(FileChannel.MapMode.READ_ONLY, 0L, size);
return m1.equals(m2);
}
}
}

View File

@ -0,0 +1,88 @@
package com.baeldung.file.content.comparison;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class CampareFileContentsApacheIOUnitTest {
public static Path path1 = null;
public static Path path2 = null;
@BeforeAll
public static void setup() throws IOException {
path1 = Files.createTempFile("file1Test", ".txt");
path2 = Files.createTempFile("file2Test", ".txt");
}
@Test
public void whenFilesIdentical_thenReturnTrue() throws IOException {
InputStream inputStream1 = new FileInputStream(path1.toFile());
InputStream inputStream2 = new FileInputStream(path2.toFile());
Files.writeString(path1, "testing line 1" + System.lineSeparator() + "line 2");
Files.writeString(path2, "testing line 1" + System.lineSeparator() + "line 2");
assertTrue(IOUtils.contentEquals(inputStream1, inputStream2));
}
@Test
public void whenFilesDifferent_thenReturnFalse() throws IOException {
InputStream inputStream1 = new FileInputStream(path1.toFile());
InputStream inputStream2 = new FileInputStream(path2.toFile());
Files.writeString(path1, "testing line " + System.lineSeparator() + "line 2");
Files.writeString(path2, "testing line 1" + System.lineSeparator() + "line 2");
assertFalse(IOUtils.contentEquals(inputStream1, inputStream2));
}
@Test
public void whenFilesIdenticalIgnoreEOF_thenReturnTrue() throws IOException {
Files.writeString(path1, "testing line 1 \n line 2");
Files.writeString(path2, "testing line 1 \r\n line 2");
Reader reader1 = new BufferedReader(new FileReader(path1.toFile()));
Reader reader2 = new BufferedReader(new FileReader(path2.toFile()));
assertTrue(IOUtils.contentEqualsIgnoreEOL(reader1, reader2));
}
@Test
public void whenFilesNotIdenticalIgnoreEOF_thenReturnFalse() throws IOException {
Files.writeString(path1, "testing line \n line 2");
Files.writeString(path2, "testing line 1 \r\n line 2");
Reader reader1 = new BufferedReader(new FileReader(path1.toFile()));
Reader reader2 = new BufferedReader(new FileReader(path2.toFile()));
assertFalse(IOUtils.contentEqualsIgnoreEOL(reader1, reader2));
}
@AfterAll
public static void shutDown() {
path1.toFile()
.deleteOnExit();
path2.toFile()
.deleteOnExit();
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.file.content.comparison;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class CompareByMemoryMappedFilesUnitTest {
public static Path path1 = null;
public static Path path2 = null;
@BeforeAll
public static void setup() throws IOException {
path1 = Files.createTempFile("file1Test", ".txt");
path2 = Files.createTempFile("file2Test", ".txt");
}
@Test
public void whenFilesIdentical_thenReturnTrue() throws IOException {
Files.writeString(path1, "testing line 1" + System.lineSeparator() + "line 2");
Files.writeString(path2, "testing line 1" + System.lineSeparator() + "line 2");
assertTrue(CompareFileContents.compareByMemoryMappedFiles(path1, path2));
}
@Test
public void whenFilesDifferent_thenReturnFalse() throws IOException {
Files.writeString(path1, "testing line " + System.lineSeparator() + "line 2");
Files.writeString(path2, "testing line 1" + System.lineSeparator() + "line 2");
assertFalse(CompareFileContents.compareByMemoryMappedFiles(path1, path2));
}
}

View File

@ -0,0 +1,96 @@
package com.baeldung.file.content.comparison;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class CompareFileContentsByBytesUnitTest {
public static Path path1 = null;
public static Path path2 = null;
@BeforeAll
public static void setup() throws IOException {
path1 = Files.createTempFile("file1Test", ".txt");
path2 = Files.createTempFile("file2Test", ".txt");
}
@Test
public void whenFirstFileShorter_thenPositionInSecondFile() throws IOException {
Files.writeString(path1, "testing");
Files.writeString(path2, "testing1");
assertEquals(8, CompareFileContents.filesCompareByByte(path1, path2));
}
@Test
public void whenSecondFileShorter_thenPositionInFirstFile() throws IOException {
Files.writeString(path1, "testing1");
Files.writeString(path2, "testing");
assertEquals(8, CompareFileContents.filesCompareByByte(path1, path2));
}
@Test
public void whenFilesIdentical_thenSuccess() throws IOException {
Files.writeString(path1, "testing");
Files.writeString(path2, "testing");
assertEquals(-1, CompareFileContents.filesCompareByByte(path1, path2));
}
@Test
public void whenFilesDifferent_thenPosition() throws IOException {
Files.writeString(path1, "tesXing");
Files.writeString(path2, "testing");
assertEquals(4, CompareFileContents.filesCompareByByte(path1, path2));
}
@Test
public void whenBothFilesEmpty_thenEqual() throws IOException {
Files.writeString(path1, "");
Files.writeString(path2, "");
assertEquals(-1, CompareFileContents.filesCompareByByte(path1, path2));
}
@Test
public void whenFirstEmpty_thenPositionFirst() throws IOException {
Files.writeString(path1, "");
Files.writeString(path2, "test");
assertEquals(1, CompareFileContents.filesCompareByByte(path1, path2));
}
@Test
public void whenSecondEmpty_thenPositionFirst() throws IOException {
Files.writeString(path1, "test");
Files.writeString(path2, "");
assertEquals(1, CompareFileContents.filesCompareByByte(path1, path2));
}
@AfterAll
public static void shutDown() {
path1.toFile().deleteOnExit();
path2.toFile().deleteOnExit();
}
}

View File

@ -0,0 +1,94 @@
package com.baeldung.file.content.comparison;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class CompareFileContentsByLinesUnitTest {
public static Path path1 = null;
public static Path path2 = null;
@BeforeAll
public static void setup() throws IOException {
path1 = Files.createTempFile("file1Test", ".txt");
path2 = Files.createTempFile("file2Test", ".txt");
}
@Test
public void whenFirstFileShorter_thenLineNumbersFirstFile() throws IOException {
Files.writeString(path1, "testing line 1");
Files.writeString(path2, "testing1 line 1" + System.lineSeparator() + "line 2");
assertEquals(1, CompareFileContents.filesCompareByLine(path1, path2));
}
@Test
public void whenSecondFileShorter_thenLineNumbersSecondFile() throws IOException {
Files.writeString(path1, "testing1 line 1" + System.lineSeparator() + "line 2");
Files.writeString(path2, "testing line 1");
assertEquals(1, CompareFileContents.filesCompareByLine(path1, path2));
}
@Test
public void whenFileIdentical_thenLineSuccess() throws IOException {
Files.writeString(path1, "testing1 line 1" + System.lineSeparator() + "line 2");
Files.writeString(path2, "testing1 line 1" + System.lineSeparator() + "line 2");
assertEquals(-1, CompareFileContents.filesCompareByLine(path1, path2));
}
@Test
public void whenFilesDifferent_thenLineNumber() throws IOException {
Files.writeString(path1, "testing1 line 1" + System.lineSeparator() + "line 2");
Files.writeString(path2, "testing1 line 1" + System.lineSeparator() + "linX 2");
assertEquals(2, CompareFileContents.filesCompareByLine(path1, path2));
}
@Test
public void whenBothFilesEmpty_thenEqual() throws IOException {
Files.writeString(path1, "");
Files.writeString(path2, "");
assertEquals(-1, CompareFileContents.filesCompareByByte(path1, path2));
}
@Test
public void whenFirstEmpty_thenPositionFirst() throws IOException {
Files.writeString(path1, "");
Files.writeString(path2, "testing1 line 1" + System.lineSeparator() + "line 2");
assertEquals(1, CompareFileContents.filesCompareByByte(path1, path2));
}
@Test
public void whenSecondEmpty_thenPositionFirst() throws IOException {
Files.writeString(path1, "testing1 line 1" + System.lineSeparator() + "line 2");
Files.writeString(path2, "");
assertEquals(1, CompareFileContents.filesCompareByByte(path1, path2));
}
@AfterAll
public static void shutDown() {
path1.toFile().deleteOnExit();
path2.toFile().deleteOnExit();
}
}

View File

@ -1,6 +1,6 @@
package java.com.baeldung.newfeatures;
package com.baeldung.newfeatures;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.text.NumberFormat;
import java.util.Locale;
@ -16,6 +16,6 @@ public class CompactNumbersUnitTest {
assertEquals("2.59K", likesShort.format(2592));
NumberFormat likesLong = NumberFormat.getCompactNumberInstance(new Locale("en", "US"), NumberFormat.Style.LONG);
likesLong.setMaximumFractionDigits(2);
assertEquals("2.59 thousand", likesShort.format(2592));
assertEquals("2.59 thousand", likesLong.format(2592));
}
}

View File

@ -1,6 +1,6 @@
package java.com.baeldung.newfeatures;
package com.baeldung.newfeatures;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;

View File

@ -1,6 +1,6 @@
package java.com.baeldung.newfeatures;
package com.baeldung.newfeatures;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals;

View File

@ -1,6 +1,6 @@
package java.com.baeldung.newfeatures;
package com.baeldung.newfeatures;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@ -13,6 +13,6 @@ public class TeeingCollectorUnitTest {
public void givenSetOfNumbers_thenCalculateAverage() {
double mean = Stream.of(1, 2, 3, 4, 5)
.collect(Collectors.teeing(Collectors.summingDouble(i -> i), Collectors.counting(), (sum, count) -> sum / count));
assertEquals(3.0, mean);
assertEquals(3.0, mean, 0);
}
}

View File

@ -0,0 +1,3 @@
### Relevant articles:
- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection)

View File

@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>
<artifactId>core-java-16</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-16</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>16</maven.compiler.source.version>
<maven.compiler.target.version>16</maven.compiler.target.version>
<assertj.version>3.6.1</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,38 @@
package com.baeldung.java_16_features.groupingby;
public class BlogPost {
private String title;
private String author;
private BlogPostType type;
private int likes;
record AuthPostTypesLikes(String author, BlogPostType type, int likes) {};
public BlogPost(String title, String author, BlogPostType type, int likes) {
this.title = title;
this.author = author;
this.type = type;
this.likes = likes;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public BlogPostType getType() {
return type;
}
public int getLikes() {
return likes;
}
@Override
public String toString() {
return "BlogPost{" + "title='" + title + '\'' + ", type=" + type + ", likes=" + likes + '}';
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.java_16_features.groupingby;
public enum BlogPostType {
NEWS, REVIEW, GUIDE
}

View File

@ -0,0 +1,41 @@
package com.baeldung.java_16_features.groupingby;
import java.util.Objects;
public class Tuple {
private final BlogPostType type;
private final String author;
public Tuple(BlogPostType type, String author) {
this.type = type;
this.author = author;
}
public BlogPostType getType() {
return type;
}
public String getAuthor() {
return author;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Tuple tuple = (Tuple) o;
return type == tuple.type && author.equals(tuple.author);
}
@Override
public int hashCode() {
return Objects.hash(type, author);
}
@Override
public String toString() {
return "Tuple{" + "type=" + type + ", author='" + author + '\'' + '}';
}
}

View File

@ -0,0 +1,254 @@
package com.baeldung.java_16_features.groupingby;
import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.averagingInt;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.groupingByConcurrent;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.maxBy;
import static java.util.stream.Collectors.summarizingInt;
import static java.util.stream.Collectors.summingInt;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.jupiter.api.Test;
public class JavaGroupingByCollectorUnitTest {
private static final List<BlogPost> posts = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5),
new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15));
@Test
public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() {
Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType));
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() {
Map<BlogPostType, String> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
assertEquals("Post titles: [News item 1, News item 2]", postsPerType.get(BlogPostType.NEWS));
assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE));
assertEquals("Post titles: [Tech review 1, Tech review 2]", postsPerType.get(BlogPostType.REVIEW));
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() {
Map<BlogPostType, Integer> likesPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
assertEquals(50, likesPerType.get(BlogPostType.NEWS)
.intValue());
assertEquals(20, likesPerType.get(BlogPostType.REVIEW)
.intValue());
assertEquals(20, likesPerType.get(BlogPostType.GUIDE)
.intValue());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() {
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() {
Map<BlogPostType, Set<BlogPost>> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, toSet()));
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() {
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts.parallelStream()
.collect(groupingByConcurrent(BlogPost::getType));
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() {
Map<BlogPostType, Double> averageLikesPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
assertEquals(25, averageLikesPerType.get(BlogPostType.NEWS)
.intValue());
assertEquals(20, averageLikesPerType.get(BlogPostType.GUIDE)
.intValue());
assertEquals(10, averageLikesPerType.get(BlogPostType.REVIEW)
.intValue());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() {
Map<BlogPostType, Long> numberOfPostsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, counting()));
assertEquals(2, numberOfPostsPerType.get(BlogPostType.NEWS)
.intValue());
assertEquals(1, numberOfPostsPerType.get(BlogPostType.GUIDE)
.intValue());
assertEquals(2, numberOfPostsPerType.get(BlogPostType.REVIEW)
.intValue());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() {
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts.stream()
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
assertTrue(maxLikesPerPostType.get(BlogPostType.NEWS)
.isPresent());
assertEquals(35, maxLikesPerPostType.get(BlogPostType.NEWS)
.get()
.getLikes());
assertTrue(maxLikesPerPostType.get(BlogPostType.GUIDE)
.isPresent());
assertEquals(20, maxLikesPerPostType.get(BlogPostType.GUIDE)
.get()
.getLikes());
assertTrue(maxLikesPerPostType.get(BlogPostType.REVIEW)
.isPresent());
assertEquals(15, maxLikesPerPostType.get(BlogPostType.REVIEW)
.get()
.getLikes());
}
@Test
public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() {
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts.stream()
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
assertEquals(1, map.get("Author 1")
.get(BlogPostType.NEWS)
.size());
assertEquals(1, map.get("Author 1")
.get(BlogPostType.GUIDE)
.size());
assertEquals(1, map.get("Author 1")
.get(BlogPostType.REVIEW)
.size());
assertEquals(1, map.get("Author 2")
.get(BlogPostType.NEWS)
.size());
assertEquals(1, map.get("Author 2")
.get(BlogPostType.REVIEW)
.size());
assertNull(map.get("Author 2")
.get(BlogPostType.GUIDE));
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() {
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS);
assertEquals(2, newsLikeStatistics.getCount());
assertEquals(50, newsLikeStatistics.getSum());
assertEquals(25.0, newsLikeStatistics.getAverage(), 0.001);
assertEquals(35, newsLikeStatistics.getMax());
assertEquals(15, newsLikeStatistics.getMin());
}
@Test
public void givenAListOfPosts_whenGroupedByComplexMapPairKeyType_thenGetAMapBetweenPairAndList() {
Map<Pair<BlogPostType, String>, List<BlogPost>> postsPerTypeAndAuthor = posts.stream()
.collect(groupingBy(post -> new ImmutablePair<>(post.getType(), post.getAuthor())));
List<BlogPost> result = postsPerTypeAndAuthor.get(new ImmutablePair<>(BlogPostType.GUIDE, "Author 1"));
assertThat(result.size()).isEqualTo(1);
BlogPost blogPost = result.get(0);
assertThat(blogPost.getTitle()).isEqualTo("Programming guide");
assertThat(blogPost.getType()).isEqualTo(BlogPostType.GUIDE);
assertThat(blogPost.getAuthor()).isEqualTo("Author 1");
}
@Test
public void givenAListOfPosts_whenGroupedByComplexMapKeyType_thenGetAMapBetweenTupleAndList() {
Map<Tuple, List<BlogPost>> postsPerTypeAndAuthor = posts.stream()
.collect(groupingBy(post -> new Tuple(post.getType(), post.getAuthor())));
List<BlogPost> result = postsPerTypeAndAuthor.get(new Tuple(BlogPostType.GUIDE, "Author 1"));
assertThat(result.size()).isEqualTo(1);
BlogPost blogPost = result.get(0);
assertThat(blogPost.getTitle()).isEqualTo("Programming guide");
assertThat(blogPost.getType()).isEqualTo(BlogPostType.GUIDE);
assertThat(blogPost.getAuthor()).isEqualTo("Author 1");
}
@Test
public void givenAListOfPosts_whenGroupedByRecord_thenGetAMapBetweenRecordAndList() {
Map<BlogPost.AuthPostTypesLikes, List<BlogPost>> postsPerTypeAndAuthor = posts.stream()
.collect(groupingBy(post -> new BlogPost.AuthPostTypesLikes(post.getAuthor(), post.getType(), post.getLikes())));
List<BlogPost> result = postsPerTypeAndAuthor.get(new BlogPost.AuthPostTypesLikes("Author 1", BlogPostType.GUIDE, 20));
assertThat(result.size()).isEqualTo(1);
BlogPost blogPost = result.get(0);
assertThat(blogPost.getTitle()).isEqualTo("Programming guide");
assertThat(blogPost.getType()).isEqualTo(BlogPostType.GUIDE);
assertThat(blogPost.getAuthor()).isEqualTo("Author 1");
assertThat(blogPost.getLikes()).isEqualTo(20);
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.streams;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class StreamToImmutableUnitTest {
@Test
public void whenUsingStreamToList_thenReturnImmutableList() {
List<String> immutableList = Stream.of("a", "b", "c", "d")
.toList();
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
immutableList.add("e");
});
}
}

View File

@ -7,4 +7,5 @@ This module contains articles about Java 8 core features
- [Run a Java Application from the Command Line](https://www.baeldung.com/java-run-jar-with-arguments)
- [Java 8 Stream skip() vs limit()](https://www.baeldung.com/java-stream-skip-vs-limit)
- [Guide to Java BiFunction Interface](https://www.baeldung.com/java-bifunction-interface)
- [Interface With Default Methods vs Abstract Class](https://www.baeldung.com/java-interface-default-method-vs-abstract-class)
- [[<-- Prev]](/core-java-modules/core-java-8)

View File

@ -0,0 +1,14 @@
package com.baeldung.interfaceVsAbstractClass;
public class ChidlCircleInterfaceImpl implements CircleInterface {
private String color;
@Override
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.interfaceVsAbstractClass;
public class ChildCircleClass extends CircleClass {
}

View File

@ -0,0 +1,23 @@
package com.baeldung.interfaceVsAbstractClass;
import java.util.Arrays;
import java.util.List;
public abstract class CircleClass {
private String color;
private List<String> allowedColors = Arrays.asList("RED", "GREEN", "BLUE");
public boolean isValid() {
return allowedColors.contains(getColor());
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.interfaceVsAbstractClass;
import java.util.Arrays;
import java.util.List;
public interface CircleInterface {
List<String> allowedColors = Arrays.asList("RED", "GREEN", "BLUE");
String getColor();
public default boolean isValid() {
return allowedColors.contains(getColor());
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.interfaceVsAbstractClass;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class InterfaceVsAbstractClassUnitTest {
@Test
public void givenAbstractClass_whenValidCircleUsed_thenPass() {
CircleClass redCircle = new ChildCircleClass();
redCircle.setColor("RED");
assertTrue(redCircle.isValid());
}
@Test
public void givenInterface_whenValidCircleWithoutStateUsed_thenPass() {
ChidlCircleInterfaceImpl redCircleWithoutState = new ChidlCircleInterfaceImpl();
redCircleWithoutState.setColor("RED");
assertTrue(redCircleWithoutState.isValid());
}
}

View File

@ -10,3 +10,4 @@ This module contains articles about Java 9 core features
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [Immutable ArrayList in Java](https://www.baeldung.com/java-immutable-list)
- [Easy Ways to Write a Java InputStream to an OutputStream](https://www.baeldung.com/java-inputstream-to-outputstream)
- [Private Methods in Java Interfaces](https://www.baeldung.com/java-interface-private-methods)

View File

@ -0,0 +1,10 @@
package com.baeldung.java9.interfaces;
public class CustomFoo implements Foo {
public static void main(String... args) {
Foo customFoo = new CustomFoo();
customFoo.bar(); // 'Hello world!'
Foo.buzz(); // 'Hello static world!'
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.java9.interfaces;
public interface Foo {
public default void bar() {
System.out.print("Hello");
baz();
}
public static void buzz() {
System.out.print("Hello");
staticBaz();
}
private void baz() {
System.out.print(" world!");
}
private static void staticBaz() {
System.out.print(" static world!");
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.java9.interfaces;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.assertj.core.api.Assertions.assertThat;
class CustomFooUnitTest {
private ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private PrintStream originalOut = System.out;
@BeforeEach
void setup() {
System.setOut(new PrintStream(outContent));
}
@AfterEach
void tearDown() {
System.setOut(originalOut);
}
@Test
void givenACustomFooObject_whenCallingDefaultMethodBar_thenExpectedStringIsWrittenToSystemOut() {
CustomFoo customFoo = new CustomFoo();
customFoo.bar();
assertThat(outContent.toString()).isEqualTo("Hello world!");
}
@Test
void givenAFooInterface_whenCallingStaticMethodBuzz_thenExpectedStringIsWrittenToSystemOut() {
Foo.buzz();
assertThat(outContent.toString()).isEqualTo("Hello static world!");
}
}

View File

@ -10,3 +10,5 @@
- [Overview of Java Built-in Annotations](https://www.baeldung.com/java-default-annotations)
- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation)
- [Efficient Word Frequency Calculator in Java](https://www.baeldung.com/java-word-frequency)
- [Why Missing Annotations Dont Cause ClassNotFoundException](https://www.baeldung.com/classnotfoundexception-missing-annotation)
- [Valid @SuppressWarnings Warning Names](https://www.baeldung.com/java-suppresswarnings-valid-names)

View File

@ -0,0 +1,46 @@
package com.baeldung.annotations;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings({"serial", "unchecked"})
public class ClassWithSuppressWarningsNames implements Serializable {
// private static final long serialVersionUID = -1166032307853492833L;
@SuppressWarnings("unused")
public static void suppressBoxingWarning() {
int value = 5;
int unusedVar = 10; // no warning here
List<Integer> list = new ArrayList<>();
list.add(Integer.valueOf(value));
}
@SuppressWarnings("deprecated")
void suppressDeprecatedWarning() {
ClassWithSuppressWarningsNames cls = new ClassWithSuppressWarningsNames();
cls.deprecatedMethod(); // no warning here
}
@SuppressWarnings("fallthrough")
String suppressFallthroughWarning() {
int day = 5;
switch (day) {
case 5:
return "This is day 5";
// break; // no warning here
case 10:
return "This is day 10";
// break;
default:
return "This default day";
}
}
@Deprecated
String deprecatedMethod() {
return "deprecated method";
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.missingannotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface A {
}

View File

@ -0,0 +1,10 @@
package com.baeldung.missingannotation;
@A
@C(D.class)
public class B {
public static void main(String[] args) {
System.out.println("It worked");
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.missingannotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface C {
Class<?> value();
}

View File

@ -0,0 +1,4 @@
package com.baeldung.missingannotation;
public class D {
}

View File

@ -6,3 +6,4 @@
- [ArrayList vs. LinkedList vs. HashMap in Java](https://www.baeldung.com/java-arraylist-vs-linkedlist-vs-hashmap)
- [Java Deque vs. Stack](https://www.baeldung.com/java-deque-vs-stack)
- [Collection.toArray(new T[0]) or .toArray(new T[size])](https://www.baeldung.com/java-collection-toarray-methods)

View File

@ -1,31 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>
<artifactId>core-java-collections-4</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-4</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
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>
<artifactId>core-java-collections-4</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-4</name>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<properties>
<assertj.version>3.19.0</assertj.version>
</properties>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<assertj.version>3.19.0</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,72 @@
package com.baeldung.collections.toarraycomparison;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(value = 3, jvmArgsAppend = { "-XX:+UseParallelGC", "-Xms4g", "-Xmx4g" })
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class ToArrayBenchmark {
@Param({ "10", "10000", "10000000" })
private int size;
@Param({ "array-list", "tree-set" })
private String type;
private Collection<String> collection;
@Setup
public void setup() {
switch (type) {
case "array-list":
collection = new ArrayList<String>();
break;
case "tree-set":
collection = new TreeSet<String>();
break;
default:
throw new UnsupportedOperationException();
}
for (int i = 0; i < size; i++) {
collection.add(String.valueOf(i));
}
}
@Benchmark
public String[] zero_sized() {
return collection.toArray(new String[0]);
}
@Benchmark
public String[] pre_sized() {
return collection.toArray(new String[collection.size()]);
}
public static void main(String[] args) {
try {
org.openjdk.jmh.Main.main(args);
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -7,7 +7,7 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>

View File

@ -31,7 +31,6 @@
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>

View File

@ -2,3 +2,4 @@
- [Binary Semaphore vs Reentrant Lock](https://www.baeldung.com/java-binary-semaphore-vs-reentrant-lock)
- [Bad Practices With Synchronization](https://www.baeldung.com/java-synchronization-bad-practices)
- [Start Two Threads at the Exact Same Time in Java](https://www.baeldung.com/java-start-two-threads-at-same-time)

View File

@ -0,0 +1,86 @@
package com.baeldung.threadsstartatsametime;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Phaser;
public class ThreadsStartAtSameTime {
public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
usingCountDownLatch();
Thread.sleep(30);
usingCyclicBarrier();
Thread.sleep(30);
usingPhaser();
}
private static void usingCountDownLatch() throws InterruptedException {
System.out.println("===============================================");
System.out.println(" >>> Using CountDownLatch <<<<");
System.out.println("===============================================");
CountDownLatch latch = new CountDownLatch(1);
WorkerWithCountDownLatch worker1 = new WorkerWithCountDownLatch("Worker with latch 1", latch);
WorkerWithCountDownLatch worker2 = new WorkerWithCountDownLatch("Worker with latch 2", latch);
worker1.start();
worker2.start();
Thread.sleep(10);//simulation of some actual work
System.out.println("-----------------------------------------------");
System.out.println(" Now release the latch:");
System.out.println("-----------------------------------------------");
latch.countDown();
}
private static void usingCyclicBarrier() throws BrokenBarrierException, InterruptedException {
System.out.println("\n===============================================");
System.out.println(" >>> Using CyclicBarrier <<<<");
System.out.println("===============================================");
CyclicBarrier barrier = new CyclicBarrier(3);
WorkerWithCyclicBarrier worker1 = new WorkerWithCyclicBarrier("Worker with barrier 1", barrier);
WorkerWithCyclicBarrier worker2 = new WorkerWithCyclicBarrier("Worker with barrier 2", barrier);
worker1.start();
worker2.start();
Thread.sleep(10);//simulation of some actual work
System.out.println("-----------------------------------------------");
System.out.println(" Now open the barrier:");
System.out.println("-----------------------------------------------");
barrier.await();
}
private static void usingPhaser() throws InterruptedException {
System.out.println("\n===============================================");
System.out.println(" >>> Using Phaser <<<");
System.out.println("===============================================");
Phaser phaser = new Phaser();
phaser.register();
WorkerWithPhaser worker1 = new WorkerWithPhaser("Worker with phaser 1", phaser);
WorkerWithPhaser worker2 = new WorkerWithPhaser("Worker with phaser 2", phaser);
worker1.start();
worker2.start();
Thread.sleep(10);//simulation of some actual work
System.out.println("-----------------------------------------------");
System.out.println(" Now open the phaser barrier:");
System.out.println("-----------------------------------------------");
phaser.arriveAndAwaitAdvance();
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.threadsstartatsametime;
import java.time.Instant;
import java.util.concurrent.CountDownLatch;
public class WorkerWithCountDownLatch extends Thread {
private CountDownLatch latch;
public WorkerWithCountDownLatch(String name, CountDownLatch latch) {
this.latch = latch;
setName(name);
}
@Override public void run() {
try {
System.out.printf("[ %s ] created, blocked by the latch\n", getName());
latch.await();
System.out.printf("[ %s ] starts at: %s\n", getName(), Instant.now());
// do actual work here...
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.threadsstartatsametime;
import java.time.Instant;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class WorkerWithCyclicBarrier extends Thread {
private CyclicBarrier barrier;
public WorkerWithCyclicBarrier(String name, CyclicBarrier barrier) {
this.barrier = barrier;
this.setName(name);
}
@Override public void run() {
try {
System.out.printf("[ %s ] created, blocked by the barrier\n", getName());
barrier.await();
System.out.printf("[ %s ] starts at: %s\n", getName(), Instant.now());
// do actual work here...
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.threadsstartatsametime;
import java.time.Instant;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Phaser;
public class WorkerWithPhaser extends Thread {
private Phaser phaser;
public WorkerWithPhaser(String name, Phaser phaser) {
this.phaser = phaser;
phaser.register();
setName(name);
}
@Override public void run() {
try {
System.out.printf("[ %s ] created, blocked by the phaser\n", getName());
phaser.arriveAndAwaitAdvance();
System.out.printf("[ %s ] starts at: %s\n", getName(), Instant.now());
// do actual work here...
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}

View File

@ -7,7 +7,7 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-advanced</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>

View File

@ -13,4 +13,5 @@ This module contains articles about basic Java concurrency
- [Why are Local Variables Thread-Safe in Java](https://www.baeldung.com/java-local-variables-thread-safe)
- [How to Stop Execution After a Certain Time in Java](https://www.baeldung.com/java-stop-execution-after-certain-time)
- [How to Handle InterruptedException in Java](https://www.baeldung.com/java-interrupted-exception)
- [How to Get the Number of Threads in a Java Process](https://www.baeldung.com/java-get-number-of-threads)
- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic)

View File

@ -7,7 +7,7 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-basic-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>

View File

@ -0,0 +1,14 @@
package com.baeldung.concurrent.threads.number;
import java.lang.management.ManagementFactory;
public class FindNumberOfThreads {
public static void main(String[] args) {
System.out.println("Number of threads " + Thread.activeCount());
System.out.println("Current Thread Group - "
+ Thread.currentThread().getThreadGroup().getName());
System.out.println("Total Number of threads "
+ ManagementFactory.getThreadMXBean().getThreadCount());
}
}

View File

@ -7,7 +7,7 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-basic</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>

View File

@ -6,7 +6,7 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-collections-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>

View File

@ -7,7 +7,7 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-collections</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>

View File

@ -49,7 +49,6 @@
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>

View File

@ -7,7 +7,7 @@
<version>${project.parent.version}</version>
<name>core-java-date-operations-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>

View File

@ -48,7 +48,6 @@
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>

View File

@ -7,7 +7,7 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-function</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
@ -40,4 +40,4 @@
<assertj.version>3.6.1</assertj.version>
</properties>
</project>
</project>

View File

@ -7,7 +7,7 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-functional</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>

View File

@ -7,7 +7,7 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-io-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>

View File

@ -7,7 +7,7 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-io-apis</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>

View File

@ -36,6 +36,16 @@
<build>
<finalName>core-java-io-conversions-2</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${source.version}</source>
<target>${target.version}</target>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
@ -45,6 +55,8 @@
</build>
<properties>
<source.version>11</source.version>
<target.version>11</target.version>
<json.version>20200518</json.version>
<opencsv.version>4.1</opencsv.version>
</properties>

View File

@ -21,11 +21,11 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Scanner;
import java.util.UUID;
@ -70,6 +70,16 @@ public class JavaInputStreamToXUnitTest {
assertThat(text, equalTo(originalString));
}
@Test
public void givenUsingJava9_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
final String text = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
assertThat(text, equalTo(originalString));
}
@Test
public final void givenUsingJava7_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
@ -155,15 +165,13 @@ public class JavaInputStreamToXUnitTest {
@Test
public final void whenConvertingToFile_thenCorrect() throws IOException {
final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
final byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer);
final Path path = Paths.get("src/test/resources/sample.txt");
final byte[] buffer = java.nio.file.Files.readAllBytes(path);
final File targetFile = new File("src/test/resources/targetFile.tmp");
final OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
IOUtils.closeQuietly(initialStream);
IOUtils.closeQuietly(outStream);
}

View File

@ -7,6 +7,7 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-io-conversions</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>

Some files were not shown because too many files have changed in this diff Show More