added files for BidiMapUnitTest
This commit is contained in:
commit
30f8705430
3
asciidoctor/README.md
Normal file
3
asciidoctor/README.md
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
### Relevant articles
|
||||||
|
|
||||||
|
- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor)
|
0
asciidoctor/log4j.properties
Normal file
0
asciidoctor/log4j.properties
Normal file
56
asciidoctor/pom.xml
Normal file
56
asciidoctor/pom.xml
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
<?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">
|
||||||
|
<parent>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<artifactId>asciidoctor</artifactId>
|
||||||
|
<name>asciidoctor</name>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.asciidoctor</groupId>
|
||||||
|
<artifactId>asciidoctor-maven-plugin</artifactId>
|
||||||
|
<version>1.5.5</version>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.asciidoctor</groupId>
|
||||||
|
<artifactId>asciidoctorj-pdf</artifactId>
|
||||||
|
<version>1.5.0-alpha.15</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>output-pdf</id>
|
||||||
|
<phase>generate-resources</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>process-asciidoc</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<configuration>
|
||||||
|
<sourceDirectory>src/docs/asciidoc</sourceDirectory>
|
||||||
|
<outputDirectory>target/docs/asciidoc</outputDirectory>
|
||||||
|
<backend>pdf</backend>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.asciidoctor</groupId>
|
||||||
|
<artifactId>asciidoctorj</artifactId>
|
||||||
|
<version>1.5.4</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.asciidoctor</groupId>
|
||||||
|
<artifactId>asciidoctorj-pdf</artifactId>
|
||||||
|
<version>1.5.0-alpha.11</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</project>
|
15
camel-api/README.md
Normal file
15
camel-api/README.md
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
Example for the Article on Camel API with SpringBoot
|
||||||
|
|
||||||
|
to start up, run:
|
||||||
|
mvn spring-boot:run
|
||||||
|
|
||||||
|
them, do a POST http request to:
|
||||||
|
http://localhost:8080/camel/api/bean
|
||||||
|
|
||||||
|
with the HEADER: Content-Type: application/json,
|
||||||
|
|
||||||
|
and a BODY Payload like {"id": 1,"name": "World"}
|
||||||
|
|
||||||
|
and we will get a return code of 201 and the response: Hello, World - if the transform() method from Application class is uncommented and the process() method is commented
|
||||||
|
|
||||||
|
or return code of 201 and the response: {"id": 10,"name": "Hello, World"} - if the transform() method from Application class is commented and the process() method is uncommented
|
80
camel-api/pom.xml
Normal file
80
camel-api/pom.xml
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
<?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>
|
||||||
|
|
||||||
|
<groupId>com.example</groupId>
|
||||||
|
<artifactId>spring-boot-camel</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
|
||||||
|
<name>Spring-Boot - Camel API</name>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
|
<camel.version>2.19.1</camel.version>
|
||||||
|
<spring-boot-starter.version>1.5.4.RELEASE</spring-boot-starter.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.camel</groupId>
|
||||||
|
<artifactId>camel-servlet-starter</artifactId>
|
||||||
|
<version>${camel.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.camel</groupId>
|
||||||
|
<artifactId>camel-jackson-starter</artifactId>
|
||||||
|
<version>${camel.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.camel</groupId>
|
||||||
|
<artifactId>camel-swagger-java-starter</artifactId>
|
||||||
|
<version>${camel.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.camel</groupId>
|
||||||
|
<artifactId>camel-spring-boot-starter</artifactId>
|
||||||
|
<version>${camel.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
<version>${spring-boot-starter.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<defaultGoal>spring-boot:run</defaultGoal>
|
||||||
|
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<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>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
<version>${spring-boot-starter.version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>repackage</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
104
camel-api/src/main/java/com/baeldung/camel/Application.java
Normal file
104
camel-api/src/main/java/com/baeldung/camel/Application.java
Normal file
@ -0,0 +1,104 @@
|
|||||||
|
package com.baeldung.camel;
|
||||||
|
|
||||||
|
import javax.ws.rs.core.MediaType;
|
||||||
|
|
||||||
|
import org.apache.camel.CamelContext;
|
||||||
|
import org.apache.camel.Exchange;
|
||||||
|
import org.apache.camel.Processor;
|
||||||
|
import org.apache.camel.builder.RouteBuilder;
|
||||||
|
import org.apache.camel.component.servlet.CamelHttpTransportServlet;
|
||||||
|
import org.apache.camel.impl.DefaultCamelContext;
|
||||||
|
import org.apache.camel.model.rest.RestBindingMode;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.web.servlet.ServletRegistrationBean;
|
||||||
|
import org.springframework.boot.web.support.SpringBootServletInitializer;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
@ComponentScan(basePackages="com.baeldung.camel")
|
||||||
|
public class Application extends SpringBootServletInitializer {
|
||||||
|
|
||||||
|
@Value("${server.port}")
|
||||||
|
String serverPort;
|
||||||
|
|
||||||
|
@Value("${baeldung.api.path}")
|
||||||
|
String contextPath;
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(Application.class, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
ServletRegistrationBean servletRegistrationBean() {
|
||||||
|
ServletRegistrationBean servlet = new ServletRegistrationBean(new CamelHttpTransportServlet(), contextPath+"/*");
|
||||||
|
servlet.setName("CamelServlet");
|
||||||
|
return servlet;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Component
|
||||||
|
class RestApi extends RouteBuilder {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void configure() {
|
||||||
|
|
||||||
|
CamelContext context = new DefaultCamelContext();
|
||||||
|
|
||||||
|
|
||||||
|
// http://localhost:8080/camel/api-doc
|
||||||
|
restConfiguration().contextPath(contextPath) //
|
||||||
|
.port(serverPort)
|
||||||
|
.enableCORS(true)
|
||||||
|
.apiContextPath("/api-doc")
|
||||||
|
.apiProperty("api.title", "Test REST API")
|
||||||
|
.apiProperty("api.version", "v1")
|
||||||
|
.apiProperty("cors", "true") // cross-site
|
||||||
|
.apiContextRouteId("doc-api")
|
||||||
|
.component("servlet")
|
||||||
|
.bindingMode(RestBindingMode.json)
|
||||||
|
.dataFormatProperty("prettyPrint", "true");
|
||||||
|
/**
|
||||||
|
The Rest DSL supports automatic binding json/xml contents to/from POJOs using Camels Data Format.
|
||||||
|
By default the binding mode is off, meaning there is no automatic binding happening for incoming and outgoing messages.
|
||||||
|
You may want to use binding if you develop POJOs that maps to your REST services request and response types.
|
||||||
|
This allows you, as a developer, to work with the POJOs in Java code.
|
||||||
|
*/
|
||||||
|
|
||||||
|
rest("/api/").description("Teste REST Service")
|
||||||
|
.id("api-route")
|
||||||
|
.post("/bean")
|
||||||
|
.produces(MediaType.APPLICATION_JSON)
|
||||||
|
.consumes(MediaType.APPLICATION_JSON)
|
||||||
|
// .get("/hello/{place}")
|
||||||
|
.bindingMode(RestBindingMode.auto)
|
||||||
|
.type(MyBean.class)
|
||||||
|
.enableCORS(true)
|
||||||
|
// .outType(OutBean.class)
|
||||||
|
|
||||||
|
.to("direct:remoteService");
|
||||||
|
|
||||||
|
|
||||||
|
from("direct:remoteService")
|
||||||
|
.routeId("direct-route")
|
||||||
|
.tracing()
|
||||||
|
.log(">>> ${body.id}")
|
||||||
|
.log(">>> ${body.name}")
|
||||||
|
// .transform().simple("blue ${in.body.name}")
|
||||||
|
.process(new Processor() {
|
||||||
|
@Override
|
||||||
|
public void process(Exchange exchange) throws Exception {
|
||||||
|
MyBean bodyIn = (MyBean) exchange.getIn().getBody();
|
||||||
|
|
||||||
|
ExampleServices.example(bodyIn);
|
||||||
|
|
||||||
|
exchange.getIn().setBody(bodyIn);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(201));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.camel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* a Mock class to show how some other layer
|
||||||
|
* (a persistence layer, for instance)
|
||||||
|
* could be used insida a Camel
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class ExampleServices {
|
||||||
|
|
||||||
|
public static void example(MyBean bodyIn) {
|
||||||
|
bodyIn.setName( "Hello, " + bodyIn.getName() );
|
||||||
|
bodyIn.setId(bodyIn.getId()*10);
|
||||||
|
}
|
||||||
|
}
|
18
camel-api/src/main/java/com/baeldung/camel/MyBean.java
Normal file
18
camel-api/src/main/java/com/baeldung/camel/MyBean.java
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.camel;
|
||||||
|
|
||||||
|
public class MyBean {
|
||||||
|
private Integer id;
|
||||||
|
private String name;
|
||||||
|
public Integer getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
public void setId(Integer id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
}
|
15
camel-api/src/main/resources/application.properties
Normal file
15
camel-api/src/main/resources/application.properties
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
logging.config=classpath:logback.xml
|
||||||
|
|
||||||
|
# the options from org.apache.camel.spring.boot.CamelConfigurationProperties can be configured here
|
||||||
|
camel.springboot.name=MyCamel
|
||||||
|
|
||||||
|
# lets listen on all ports to ensure we can be invoked from the pod IP
|
||||||
|
server.address=0.0.0.0
|
||||||
|
management.address=0.0.0.0
|
||||||
|
|
||||||
|
# lets use a different management port in case you need to listen to HTTP requests on 8080
|
||||||
|
management.port=8081
|
||||||
|
|
||||||
|
# disable all management enpoints except health
|
||||||
|
endpoints.enabled = true
|
||||||
|
endpoints.health.enabled = true
|
27
camel-api/src/main/resources/application.yml
Normal file
27
camel-api/src/main/resources/application.yml
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
server:
|
||||||
|
port: 8080
|
||||||
|
|
||||||
|
# for example purposes of Camel version 2.18 and below
|
||||||
|
baeldung:
|
||||||
|
api:
|
||||||
|
path: '/camel'
|
||||||
|
|
||||||
|
camel:
|
||||||
|
springboot:
|
||||||
|
# The Camel context name
|
||||||
|
name: ServicesRest
|
||||||
|
|
||||||
|
# Binding health checks to a different port
|
||||||
|
management:
|
||||||
|
port: 8081
|
||||||
|
|
||||||
|
# disable all management enpoints except health
|
||||||
|
endpoints:
|
||||||
|
enabled: false
|
||||||
|
health:
|
||||||
|
enabled: true
|
||||||
|
|
||||||
|
# The application configuration properties
|
||||||
|
quickstart:
|
||||||
|
generateOrderPeriod: 10s
|
||||||
|
processOrderPeriod: 30s
|
17
camel-api/src/main/resources/logback.xml
Normal file
17
camel-api/src/main/resources/logback.xml
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE xml>
|
||||||
|
<configuration>
|
||||||
|
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<!-- encoders are assigned the type
|
||||||
|
ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="info">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
|
||||||
|
</configuration>
|
@ -327,6 +327,22 @@
|
|||||||
</executions>
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
|
<artifactId>exec-maven-plugin</artifactId>
|
||||||
|
<version>1.6.0</version>
|
||||||
|
<configuration>
|
||||||
|
<executable>java</executable>
|
||||||
|
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
|
||||||
|
<arguments>
|
||||||
|
<argument>-Xmx300m</argument>
|
||||||
|
<argument>-XX:+UseParallelGC</argument>
|
||||||
|
<argument>-classpath</argument>
|
||||||
|
<classpath/>
|
||||||
|
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||||
|
</arguments>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
|
|
||||||
</build>
|
</build>
|
||||||
|
@ -6,7 +6,7 @@ public class NumbersConsumer implements Runnable {
|
|||||||
private final BlockingQueue<Integer> queue;
|
private final BlockingQueue<Integer> queue;
|
||||||
private final int poisonPill;
|
private final int poisonPill;
|
||||||
|
|
||||||
public NumbersConsumer(BlockingQueue<Integer> queue, int poisonPill) {
|
NumbersConsumer(BlockingQueue<Integer> queue, int poisonPill) {
|
||||||
this.queue = queue;
|
this.queue = queue;
|
||||||
this.poisonPill = poisonPill;
|
this.poisonPill = poisonPill;
|
||||||
}
|
}
|
||||||
|
@ -9,7 +9,7 @@ public class NumbersProducer implements Runnable {
|
|||||||
private final int poisonPill;
|
private final int poisonPill;
|
||||||
private final int poisonPillPerProducer;
|
private final int poisonPillPerProducer;
|
||||||
|
|
||||||
public NumbersProducer(BlockingQueue<Integer> numbersQueue, int poisonPill, int poisonPillPerProducer) {
|
NumbersProducer(BlockingQueue<Integer> numbersQueue, int poisonPill, int poisonPillPerProducer) {
|
||||||
this.numbersQueue = numbersQueue;
|
this.numbersQueue = numbersQueue;
|
||||||
this.poisonPill = poisonPill;
|
this.poisonPill = poisonPill;
|
||||||
this.poisonPillPerProducer = poisonPillPerProducer;
|
this.poisonPillPerProducer = poisonPillPerProducer;
|
||||||
|
@ -7,7 +7,7 @@ public class BrokenWorker implements Runnable {
|
|||||||
private final List<String> outputScraper;
|
private final List<String> outputScraper;
|
||||||
private final CountDownLatch countDownLatch;
|
private final CountDownLatch countDownLatch;
|
||||||
|
|
||||||
public BrokenWorker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
BrokenWorker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
||||||
this.outputScraper = outputScraper;
|
this.outputScraper = outputScraper;
|
||||||
this.countDownLatch = countDownLatch;
|
this.countDownLatch = countDownLatch;
|
||||||
}
|
}
|
||||||
|
@ -10,7 +10,7 @@ public class WaitingWorker implements Runnable {
|
|||||||
private final CountDownLatch callingThreadBlocker;
|
private final CountDownLatch callingThreadBlocker;
|
||||||
private final CountDownLatch completedThreadCounter;
|
private final CountDownLatch completedThreadCounter;
|
||||||
|
|
||||||
public WaitingWorker(final List<String> outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) {
|
WaitingWorker(final List<String> outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) {
|
||||||
|
|
||||||
this.outputScraper = outputScraper;
|
this.outputScraper = outputScraper;
|
||||||
this.readyThreadCounter = readyThreadCounter;
|
this.readyThreadCounter = readyThreadCounter;
|
||||||
|
@ -7,7 +7,7 @@ public class Worker implements Runnable {
|
|||||||
private final List<String> outputScraper;
|
private final List<String> outputScraper;
|
||||||
private final CountDownLatch countDownLatch;
|
private final CountDownLatch countDownLatch;
|
||||||
|
|
||||||
public Worker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
Worker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
||||||
this.outputScraper = outputScraper;
|
this.outputScraper = outputScraper;
|
||||||
this.countDownLatch = countDownLatch;
|
this.countDownLatch = countDownLatch;
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,81 @@
|
|||||||
|
package com.baeldung.concurrent.cyclicbarrier;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Random;
|
||||||
|
import java.util.concurrent.BrokenBarrierException;
|
||||||
|
import java.util.concurrent.CyclicBarrier;
|
||||||
|
|
||||||
|
public class CyclicBarrierDemo {
|
||||||
|
|
||||||
|
private CyclicBarrier cyclicBarrier;
|
||||||
|
private List<List<Integer>> partialResults = Collections.synchronizedList(new ArrayList<>());
|
||||||
|
private Random random = new Random();
|
||||||
|
private int NUM_PARTIAL_RESULTS;
|
||||||
|
private int NUM_WORKERS;
|
||||||
|
|
||||||
|
|
||||||
|
private void runSimulation(int numWorkers, int numberOfPartialResults) {
|
||||||
|
NUM_PARTIAL_RESULTS = numberOfPartialResults;
|
||||||
|
NUM_WORKERS = numWorkers;
|
||||||
|
|
||||||
|
cyclicBarrier = new CyclicBarrier(NUM_WORKERS, new AggregatorThread());
|
||||||
|
System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute "
|
||||||
|
+ NUM_PARTIAL_RESULTS + " partial results each");
|
||||||
|
for (int i = 0; i < NUM_WORKERS; i++) {
|
||||||
|
Thread worker = new Thread(new NumberCruncherThread());
|
||||||
|
worker.setName("Thread " + i);
|
||||||
|
worker.start();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class NumberCruncherThread implements Runnable {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
String thisThreadName = Thread.currentThread().getName();
|
||||||
|
List<Integer> partialResult = new ArrayList<>();
|
||||||
|
for (int i = 0; i < NUM_PARTIAL_RESULTS; i++) {
|
||||||
|
Integer num = random.nextInt(10);
|
||||||
|
System.out.println(thisThreadName
|
||||||
|
+ ": Crunching some numbers! Final result - " + num);
|
||||||
|
partialResult.add(num);
|
||||||
|
}
|
||||||
|
partialResults.add(partialResult);
|
||||||
|
try {
|
||||||
|
System.out.println(thisThreadName + " waiting for others to reach barrier.");
|
||||||
|
cyclicBarrier.await();
|
||||||
|
} catch (InterruptedException | BrokenBarrierException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class AggregatorThread implements Runnable {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
String thisThreadName = Thread.currentThread().getName();
|
||||||
|
System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS
|
||||||
|
+ " workers, having " + NUM_PARTIAL_RESULTS + " results each.");
|
||||||
|
int sum = 0;
|
||||||
|
for (List<Integer> threadResult : partialResults) {
|
||||||
|
System.out.print("Adding ");
|
||||||
|
for (Integer partialResult : threadResult) {
|
||||||
|
System.out.print(partialResult+" ");
|
||||||
|
sum += partialResult;
|
||||||
|
}
|
||||||
|
System.out.println();
|
||||||
|
}
|
||||||
|
System.out.println(Thread.currentThread().getName() + ": Final result = " + sum);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
CyclicBarrierDemo play = new CyclicBarrierDemo();
|
||||||
|
play.runSimulation(5, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -9,7 +9,7 @@ public class DelayObject implements Delayed {
|
|||||||
private String data;
|
private String data;
|
||||||
private long startTime;
|
private long startTime;
|
||||||
|
|
||||||
public DelayObject(String data, long delayInMilliseconds) {
|
DelayObject(String data, long delayInMilliseconds) {
|
||||||
this.data = data;
|
this.data = data;
|
||||||
this.startTime = System.currentTimeMillis() + delayInMilliseconds;
|
this.startTime = System.currentTimeMillis() + delayInMilliseconds;
|
||||||
}
|
}
|
||||||
|
@ -7,9 +7,9 @@ import java.util.concurrent.atomic.AtomicInteger;
|
|||||||
public class DelayQueueConsumer implements Runnable {
|
public class DelayQueueConsumer implements Runnable {
|
||||||
private BlockingQueue<DelayObject> queue;
|
private BlockingQueue<DelayObject> queue;
|
||||||
private final Integer numberOfElementsToTake;
|
private final Integer numberOfElementsToTake;
|
||||||
public final AtomicInteger numberOfConsumedElements = new AtomicInteger();
|
final AtomicInteger numberOfConsumedElements = new AtomicInteger();
|
||||||
|
|
||||||
public DelayQueueConsumer(BlockingQueue<DelayObject> queue, Integer numberOfElementsToTake) {
|
DelayQueueConsumer(BlockingQueue<DelayObject> queue, Integer numberOfElementsToTake) {
|
||||||
this.queue = queue;
|
this.queue = queue;
|
||||||
this.numberOfElementsToTake = numberOfElementsToTake;
|
this.numberOfElementsToTake = numberOfElementsToTake;
|
||||||
}
|
}
|
||||||
|
@ -9,7 +9,7 @@ public class DelayQueueProducer implements Runnable {
|
|||||||
private final Integer numberOfElementsToProduce;
|
private final Integer numberOfElementsToProduce;
|
||||||
private final Integer delayOfEachProducedMessageMilliseconds;
|
private final Integer delayOfEachProducedMessageMilliseconds;
|
||||||
|
|
||||||
public DelayQueueProducer(BlockingQueue<DelayObject> queue,
|
DelayQueueProducer(BlockingQueue<DelayObject> queue,
|
||||||
Integer numberOfElementsToProduce,
|
Integer numberOfElementsToProduce,
|
||||||
Integer delayOfEachProducedMessageMilliseconds) {
|
Integer delayOfEachProducedMessageMilliseconds) {
|
||||||
this.queue = queue;
|
this.queue = queue;
|
||||||
|
@ -5,7 +5,7 @@ public class Philosopher implements Runnable {
|
|||||||
private final Object leftFork;
|
private final Object leftFork;
|
||||||
private final Object rightFork;
|
private final Object rightFork;
|
||||||
|
|
||||||
public Philosopher(Object left, Object right) {
|
Philosopher(Object left, Object right) {
|
||||||
this.leftFork = left;
|
this.leftFork = left;
|
||||||
this.rightFork = right;
|
this.rightFork = right;
|
||||||
}
|
}
|
||||||
@ -30,7 +30,6 @@ public class Philosopher implements Runnable {
|
|||||||
}
|
}
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
Thread.currentThread().interrupt();
|
Thread.currentThread().interrupt();
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -7,7 +7,7 @@ public class FactorialSquareCalculator extends RecursiveTask<Integer> {
|
|||||||
|
|
||||||
final private Integer n;
|
final private Integer n;
|
||||||
|
|
||||||
public FactorialSquareCalculator(Integer n) {
|
FactorialSquareCalculator(Integer n) {
|
||||||
this.n = n;
|
this.n = n;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -3,15 +3,15 @@ package com.baeldung.concurrent.future;
|
|||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Future;
|
import java.util.concurrent.Future;
|
||||||
|
|
||||||
public class SquareCalculator {
|
class SquareCalculator {
|
||||||
|
|
||||||
private final ExecutorService executor;
|
private final ExecutorService executor;
|
||||||
|
|
||||||
public SquareCalculator(ExecutorService executor) {
|
SquareCalculator(ExecutorService executor) {
|
||||||
this.executor = executor;
|
this.executor = executor;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Future<Integer> calculate(Integer input) {
|
Future<Integer> calculate(Integer input) {
|
||||||
return executor.submit(() -> {
|
return executor.submit(() -> {
|
||||||
Thread.sleep(1000);
|
Thread.sleep(1000);
|
||||||
return input * input;
|
return input * input;
|
||||||
|
@ -13,23 +13,23 @@ import static java.lang.Thread.sleep;
|
|||||||
|
|
||||||
public class ReentrantLockWithCondition {
|
public class ReentrantLockWithCondition {
|
||||||
|
|
||||||
static Logger logger = LoggerFactory.getLogger(ReentrantLockWithCondition.class);
|
private static Logger LOG = LoggerFactory.getLogger(ReentrantLockWithCondition.class);
|
||||||
|
|
||||||
Stack<String> stack = new Stack<>();
|
private Stack<String> stack = new Stack<>();
|
||||||
int CAPACITY = 5;
|
private static final int CAPACITY = 5;
|
||||||
|
|
||||||
ReentrantLock lock = new ReentrantLock();
|
private ReentrantLock lock = new ReentrantLock();
|
||||||
Condition stackEmptyCondition = lock.newCondition();
|
private Condition stackEmptyCondition = lock.newCondition();
|
||||||
Condition stackFullCondition = lock.newCondition();
|
private Condition stackFullCondition = lock.newCondition();
|
||||||
|
|
||||||
public void pushToStack(String item) throws InterruptedException {
|
private void pushToStack(String item) throws InterruptedException {
|
||||||
try {
|
try {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
if (stack.size() == CAPACITY) {
|
if (stack.size() == CAPACITY) {
|
||||||
logger.info(Thread.currentThread().getName() + " wait on stack full");
|
LOG.info(Thread.currentThread().getName() + " wait on stack full");
|
||||||
stackFullCondition.await();
|
stackFullCondition.await();
|
||||||
}
|
}
|
||||||
logger.info("Pushing the item " + item);
|
LOG.info("Pushing the item " + item);
|
||||||
stack.push(item);
|
stack.push(item);
|
||||||
stackEmptyCondition.signalAll();
|
stackEmptyCondition.signalAll();
|
||||||
} finally {
|
} finally {
|
||||||
@ -38,11 +38,11 @@ public class ReentrantLockWithCondition {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String popFromStack() throws InterruptedException {
|
private String popFromStack() throws InterruptedException {
|
||||||
try {
|
try {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
if (stack.size() == 0) {
|
if (stack.size() == 0) {
|
||||||
logger.info(Thread.currentThread().getName() + " wait on stack empty");
|
LOG.info(Thread.currentThread().getName() + " wait on stack empty");
|
||||||
stackEmptyCondition.await();
|
stackEmptyCondition.await();
|
||||||
}
|
}
|
||||||
return stack.pop();
|
return stack.pop();
|
||||||
@ -70,7 +70,7 @@ public class ReentrantLockWithCondition {
|
|||||||
service.execute(() -> {
|
service.execute(() -> {
|
||||||
for (int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
try {
|
try {
|
||||||
logger.info("Item popped " + object.popFromStack());
|
LOG.info("Item popped " + object.popFromStack());
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
@ -12,48 +12,48 @@ import static java.lang.Thread.sleep;
|
|||||||
|
|
||||||
public class SharedObjectWithLock {
|
public class SharedObjectWithLock {
|
||||||
|
|
||||||
Logger logger = LoggerFactory.getLogger(SharedObjectWithLock.class);
|
private static final Logger LOG = LoggerFactory.getLogger(SharedObjectWithLock.class);
|
||||||
|
|
||||||
ReentrantLock lock = new ReentrantLock(true);
|
private ReentrantLock lock = new ReentrantLock(true);
|
||||||
|
|
||||||
int counter = 0;
|
private int counter = 0;
|
||||||
|
|
||||||
public void perform() {
|
void perform() {
|
||||||
|
|
||||||
lock.lock();
|
lock.lock();
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
||||||
try {
|
try {
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " processing");
|
||||||
counter++;
|
counter++;
|
||||||
} catch (Exception exception) {
|
} catch (Exception exception) {
|
||||||
logger.error(" Interrupted Exception ", exception);
|
LOG.error(" Interrupted Exception ", exception);
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void performTryLock() {
|
private void performTryLock() {
|
||||||
|
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock");
|
||||||
try {
|
try {
|
||||||
boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS);
|
boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS);
|
||||||
if (isLockAcquired) {
|
if (isLockAcquired) {
|
||||||
try {
|
try {
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
||||||
|
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " processing");
|
||||||
sleep(1000);
|
sleep(1000);
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (InterruptedException exception) {
|
} catch (InterruptedException exception) {
|
||||||
logger.error(" Interrupted Exception ", exception);
|
LOG.error(" Interrupted Exception ", exception);
|
||||||
}
|
}
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock");
|
||||||
}
|
}
|
||||||
|
|
||||||
public ReentrantLock getLock() {
|
public ReentrantLock getLock() {
|
||||||
@ -78,12 +78,8 @@ public class SharedObjectWithLock {
|
|||||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||||
|
|
||||||
service.execute(() -> {
|
service.execute(object::perform);
|
||||||
object.perform();
|
service.execute(object::performTryLock);
|
||||||
});
|
|
||||||
service.execute(() -> {
|
|
||||||
object.performTryLock();
|
|
||||||
});
|
|
||||||
|
|
||||||
service.shutdown();
|
service.shutdown();
|
||||||
|
|
||||||
|
@ -12,8 +12,8 @@ import java.util.concurrent.locks.StampedLock;
|
|||||||
import static java.lang.Thread.sleep;
|
import static java.lang.Thread.sleep;
|
||||||
|
|
||||||
public class StampedLockDemo {
|
public class StampedLockDemo {
|
||||||
Map<String, String> map = new HashMap<>();
|
private Map<String, String> map = new HashMap<>();
|
||||||
Logger logger = LoggerFactory.getLogger(StampedLockDemo.class);
|
private Logger logger = LoggerFactory.getLogger(StampedLockDemo.class);
|
||||||
|
|
||||||
private final StampedLock lock = new StampedLock();
|
private final StampedLock lock = new StampedLock();
|
||||||
|
|
||||||
@ -44,7 +44,7 @@ public class StampedLockDemo {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String readWithOptimisticLock(String key) throws InterruptedException {
|
private String readWithOptimisticLock(String key) throws InterruptedException {
|
||||||
long stamp = lock.tryOptimisticRead();
|
long stamp = lock.tryOptimisticRead();
|
||||||
String value = map.get(key);
|
String value = map.get(key);
|
||||||
|
|
||||||
|
@ -15,8 +15,8 @@ import static java.lang.Thread.sleep;
|
|||||||
|
|
||||||
public class SynchronizedHashMapWithRWLock {
|
public class SynchronizedHashMapWithRWLock {
|
||||||
|
|
||||||
static Map<String, String> syncHashMap = new HashMap<>();
|
private static Map<String, String> syncHashMap = new HashMap<>();
|
||||||
Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class);
|
private Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class);
|
||||||
|
|
||||||
private final ReadWriteLock lock = new ReentrantReadWriteLock();
|
private final ReadWriteLock lock = new ReentrantReadWriteLock();
|
||||||
private final Lock readLock = lock.readLock();
|
private final Lock readLock = lock.readLock();
|
||||||
@ -84,7 +84,7 @@ public class SynchronizedHashMapWithRWLock {
|
|||||||
|
|
||||||
SynchronizedHashMapWithRWLock object;
|
SynchronizedHashMapWithRWLock object;
|
||||||
|
|
||||||
public Reader(SynchronizedHashMapWithRWLock object) {
|
Reader(SynchronizedHashMapWithRWLock object) {
|
||||||
this.object = object;
|
this.object = object;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -0,0 +1,31 @@
|
|||||||
|
package com.baeldung.concurrent.semaphores;
|
||||||
|
|
||||||
|
import java.util.concurrent.Semaphore;
|
||||||
|
|
||||||
|
class CounterUsingMutex {
|
||||||
|
|
||||||
|
private final Semaphore mutex;
|
||||||
|
private int count;
|
||||||
|
|
||||||
|
CounterUsingMutex() {
|
||||||
|
mutex = new Semaphore(1);
|
||||||
|
count = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void increase() throws InterruptedException {
|
||||||
|
mutex.acquire();
|
||||||
|
this.count = this.count + 1;
|
||||||
|
Thread.sleep(1000);
|
||||||
|
mutex.release();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
int getCount() {
|
||||||
|
return this.count;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean hasQueuedThreads() {
|
||||||
|
return mutex.hasQueuedThreads();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.concurrent.semaphores;
|
||||||
|
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.concurrent.TimedSemaphore;
|
||||||
|
|
||||||
|
class DelayQueueUsingTimedSemaphore {
|
||||||
|
|
||||||
|
private final TimedSemaphore semaphore;
|
||||||
|
|
||||||
|
DelayQueueUsingTimedSemaphore(long period, int slotLimit) {
|
||||||
|
semaphore = new TimedSemaphore(period, TimeUnit.SECONDS, slotLimit);
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean tryAdd() {
|
||||||
|
return semaphore.tryAcquire();
|
||||||
|
}
|
||||||
|
|
||||||
|
int availableSlots() {
|
||||||
|
return semaphore.getAvailablePermits();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.concurrent.semaphores;
|
||||||
|
|
||||||
|
import java.util.concurrent.Semaphore;
|
||||||
|
|
||||||
|
class LoginQueueUsingSemaphore {
|
||||||
|
|
||||||
|
private final Semaphore semaphore;
|
||||||
|
|
||||||
|
LoginQueueUsingSemaphore(int slotLimit) {
|
||||||
|
semaphore = new Semaphore(slotLimit);
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean tryLogin() {
|
||||||
|
return semaphore.tryAcquire();
|
||||||
|
}
|
||||||
|
|
||||||
|
void logout() {
|
||||||
|
semaphore.release();
|
||||||
|
}
|
||||||
|
|
||||||
|
int availableSlots() {
|
||||||
|
return semaphore.availablePermits();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -2,20 +2,20 @@ package com.baeldung.concurrent.skiplist;
|
|||||||
|
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
|
|
||||||
public class Event {
|
class Event {
|
||||||
private final ZonedDateTime eventTime;
|
private final ZonedDateTime eventTime;
|
||||||
private final String content;
|
private final String content;
|
||||||
|
|
||||||
public Event(ZonedDateTime eventTime, String content) {
|
Event(ZonedDateTime eventTime, String content) {
|
||||||
this.eventTime = eventTime;
|
this.eventTime = eventTime;
|
||||||
this.content = content;
|
this.content = content;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ZonedDateTime getEventTime() {
|
ZonedDateTime getEventTime() {
|
||||||
return eventTime;
|
return eventTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getContent() {
|
String getContent() {
|
||||||
return content;
|
return content;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,21 +5,21 @@ import java.util.Comparator;
|
|||||||
import java.util.concurrent.ConcurrentNavigableMap;
|
import java.util.concurrent.ConcurrentNavigableMap;
|
||||||
import java.util.concurrent.ConcurrentSkipListMap;
|
import java.util.concurrent.ConcurrentSkipListMap;
|
||||||
|
|
||||||
public class EventWindowSort {
|
class EventWindowSort {
|
||||||
private final ConcurrentSkipListMap<ZonedDateTime, String> events
|
private final ConcurrentSkipListMap<ZonedDateTime, String> events
|
||||||
= new ConcurrentSkipListMap<>(Comparator.comparingLong(value -> value.toInstant().toEpochMilli()));
|
= new ConcurrentSkipListMap<>(Comparator.comparingLong(value -> value.toInstant().toEpochMilli()));
|
||||||
|
|
||||||
public void acceptEvent(Event event) {
|
void acceptEvent(Event event) {
|
||||||
events.put(event.getEventTime(), event.getContent());
|
events.put(event.getEventTime(), event.getContent());
|
||||||
}
|
}
|
||||||
|
|
||||||
public ConcurrentNavigableMap<ZonedDateTime, String> getEventsFromLastMinute() {
|
ConcurrentNavigableMap<ZonedDateTime, String> getEventsFromLastMinute() {
|
||||||
return events.tailMap(ZonedDateTime
|
return events.tailMap(ZonedDateTime
|
||||||
.now()
|
.now()
|
||||||
.minusMinutes(1));
|
.minusMinutes(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
public ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
|
ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
|
||||||
return events.headMap(ZonedDateTime
|
return events.headMap(ZonedDateTime
|
||||||
.now()
|
.now()
|
||||||
.minusMinutes(1));
|
.minusMinutes(1));
|
||||||
|
@ -13,10 +13,10 @@ public class WaitSleepExample {
|
|||||||
private static final Object LOCK = new Object();
|
private static final Object LOCK = new Object();
|
||||||
|
|
||||||
public static void main(String... args) throws InterruptedException {
|
public static void main(String... args) throws InterruptedException {
|
||||||
sleepWaitInSyncronizedBlocks();
|
sleepWaitInSynchronizedBlocks();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void sleepWaitInSyncronizedBlocks() throws InterruptedException {
|
private static void sleepWaitInSynchronizedBlocks() throws InterruptedException {
|
||||||
Thread.sleep(1000); // called on the thread
|
Thread.sleep(1000); // called on the thread
|
||||||
LOG.debug("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second");
|
LOG.debug("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second");
|
||||||
|
|
||||||
|
@ -5,13 +5,13 @@ public class BaeldungSynchronizedBlocks {
|
|||||||
private int count = 0;
|
private int count = 0;
|
||||||
private static int staticCount = 0;
|
private static int staticCount = 0;
|
||||||
|
|
||||||
public void performSynchronisedTask() {
|
void performSynchronisedTask() {
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
setCount(getCount() + 1);
|
setCount(getCount() + 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void performStaticSyncTask() {
|
static void performStaticSyncTask() {
|
||||||
synchronized (BaeldungSynchronizedBlocks.class) {
|
synchronized (BaeldungSynchronizedBlocks.class) {
|
||||||
setStaticCount(getStaticCount() + 1);
|
setStaticCount(getStaticCount() + 1);
|
||||||
}
|
}
|
||||||
@ -25,11 +25,11 @@ public class BaeldungSynchronizedBlocks {
|
|||||||
this.count = count;
|
this.count = count;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static int getStaticCount() {
|
static int getStaticCount() {
|
||||||
return staticCount;
|
return staticCount;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void setStaticCount(int staticCount) {
|
private static void setStaticCount(int staticCount) {
|
||||||
BaeldungSynchronizedBlocks.staticCount = staticCount;
|
BaeldungSynchronizedBlocks.staticCount = staticCount;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,17 +5,17 @@ public class BaeldungSynchronizedMethods {
|
|||||||
private int sum = 0;
|
private int sum = 0;
|
||||||
private int syncSum = 0;
|
private int syncSum = 0;
|
||||||
|
|
||||||
public static int staticSum = 0;
|
static int staticSum = 0;
|
||||||
|
|
||||||
public void calculate() {
|
void calculate() {
|
||||||
setSum(getSum() + 1);
|
setSum(getSum() + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void synchronisedCalculate() {
|
synchronized void synchronisedCalculate() {
|
||||||
setSyncSum(getSyncSum() + 1);
|
setSyncSum(getSyncSum() + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static synchronized void syncStaticCalculate() {
|
static synchronized void syncStaticCalculate() {
|
||||||
staticSum = staticSum + 1;
|
staticSum = staticSum + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -27,11 +27,11 @@ public class BaeldungSynchronizedMethods {
|
|||||||
this.sum = sum;
|
this.sum = sum;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getSyncSum() {
|
int getSyncSum() {
|
||||||
return syncSum;
|
return syncSum;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setSyncSum(int syncSum) {
|
private void setSyncSum(int syncSum) {
|
||||||
this.syncSum = syncSum;
|
this.syncSum = syncSum;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,40 +6,40 @@ import java.time.LocalDateTime;
|
|||||||
import java.time.temporal.ChronoUnit;
|
import java.time.temporal.ChronoUnit;
|
||||||
import java.time.temporal.TemporalAdjusters;
|
import java.time.temporal.TemporalAdjusters;
|
||||||
|
|
||||||
public class UseLocalDate {
|
class UseLocalDate {
|
||||||
|
|
||||||
public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) {
|
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) {
|
LocalDate getLocalDateUsingParseMethod(String representation) {
|
||||||
return LocalDate.parse(representation);
|
return LocalDate.parse(representation);
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getLocalDateFromClock() {
|
LocalDate getLocalDateFromClock() {
|
||||||
LocalDate localDate = LocalDate.now();
|
LocalDate localDate = LocalDate.now();
|
||||||
return localDate;
|
return localDate;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getNextDay(LocalDate localDate) {
|
LocalDate getNextDay(LocalDate localDate) {
|
||||||
return localDate.plusDays(1);
|
return localDate.plusDays(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getPreviousDay(LocalDate localDate) {
|
LocalDate getPreviousDay(LocalDate localDate) {
|
||||||
return localDate.minus(1, ChronoUnit.DAYS);
|
return localDate.minus(1, ChronoUnit.DAYS);
|
||||||
}
|
}
|
||||||
|
|
||||||
public DayOfWeek getDayOfWeek(LocalDate localDate) {
|
DayOfWeek getDayOfWeek(LocalDate localDate) {
|
||||||
DayOfWeek day = localDate.getDayOfWeek();
|
DayOfWeek day = localDate.getDayOfWeek();
|
||||||
return day;
|
return day;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getFirstDayOfMonth() {
|
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) {
|
LocalDateTime getStartOfDay(LocalDate localDate) {
|
||||||
LocalDateTime startofDay = localDate.atStartOfDay();
|
LocalDateTime startofDay = localDate.atStartOfDay();
|
||||||
return startofDay;
|
return startofDay;
|
||||||
}
|
}
|
||||||
|
@ -5,31 +5,27 @@ import java.time.temporal.ChronoUnit;
|
|||||||
|
|
||||||
public class UseLocalTime {
|
public class UseLocalTime {
|
||||||
|
|
||||||
public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
|
LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
|
||||||
LocalTime localTime = LocalTime.of(hour, min, seconds);
|
return LocalTime.of(hour, min, seconds);
|
||||||
return localTime;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
|
LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
|
||||||
LocalTime localTime = LocalTime.parse(timeRepresentation);
|
return LocalTime.parse(timeRepresentation);
|
||||||
return localTime;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime getLocalTimeFromClock() {
|
private LocalTime getLocalTimeFromClock() {
|
||||||
LocalTime localTime = LocalTime.now();
|
return LocalTime.now();
|
||||||
return localTime;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime addAnHour(LocalTime localTime) {
|
LocalTime addAnHour(LocalTime localTime) {
|
||||||
LocalTime newTime = localTime.plus(1, ChronoUnit.HOURS);
|
return localTime.plus(1, ChronoUnit.HOURS);
|
||||||
return newTime;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getHourFromLocalTime(LocalTime localTime) {
|
int getHourFromLocalTime(LocalTime localTime) {
|
||||||
return localTime.getHour();
|
return localTime.getHour();
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) {
|
LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) {
|
||||||
return localTime.withMinute(minute);
|
return localTime.withMinute(minute);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -3,13 +3,13 @@ package com.baeldung.datetime;
|
|||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.Period;
|
import java.time.Period;
|
||||||
|
|
||||||
public class UsePeriod {
|
class UsePeriod {
|
||||||
|
|
||||||
public LocalDate modifyDates(LocalDate localDate, Period period) {
|
LocalDate modifyDates(LocalDate localDate, Period period) {
|
||||||
return localDate.plus(period);
|
return localDate.plus(period);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) {
|
Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) {
|
||||||
return Period.between(localDate1, localDate2);
|
return Period.between(localDate1, localDate2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,12 +8,10 @@ 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());
|
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
|
||||||
return localDateTime;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDateTime convertDateToLocalDate(Calendar calendar) {
|
public LocalDateTime convertDateToLocalDate(Calendar calendar) {
|
||||||
LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
|
return LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
|
||||||
return localDateTime;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -4,10 +4,9 @@ import java.time.LocalDateTime;
|
|||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
|
|
||||||
public class UseZonedDateTime {
|
class UseZonedDateTime {
|
||||||
|
|
||||||
public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
|
ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
|
||||||
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
|
return ZonedDateTime.of(localDateTime, zoneId);
|
||||||
return zonedDateTime;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -13,8 +13,7 @@ public class DirectoryMonitoringExample {
|
|||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class);
|
private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class);
|
||||||
|
|
||||||
|
private static final int POLL_INTERVAL = 500;
|
||||||
public static final int POLL_INTERVAL = 500;
|
|
||||||
|
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
FileAlterationObserver observer = new FileAlterationObserver(System.getProperty("user.home"));
|
FileAlterationObserver observer = new FileAlterationObserver(System.getProperty("user.home"));
|
||||||
|
@ -6,12 +6,12 @@ public class Computer {
|
|||||||
private String color;
|
private String color;
|
||||||
private Integer healty;
|
private Integer healty;
|
||||||
|
|
||||||
public Computer(final int age, final String color) {
|
Computer(final int age, final String color) {
|
||||||
this.age = age;
|
this.age = age;
|
||||||
this.color = color;
|
this.color = color;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Computer(final Integer age, final String color, final Integer healty) {
|
Computer(final Integer age, final String color, final Integer healty) {
|
||||||
this.age = age;
|
this.age = age;
|
||||||
this.color = color;
|
this.color = color;
|
||||||
this.healty = healty;
|
this.healty = healty;
|
||||||
@ -28,7 +28,7 @@ public class Computer {
|
|||||||
this.age = age;
|
this.age = age;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getColor() {
|
String getColor() {
|
||||||
return color;
|
return color;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -36,11 +36,11 @@ public class Computer {
|
|||||||
this.color = color;
|
this.color = color;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Integer getHealty() {
|
Integer getHealty() {
|
||||||
return healty;
|
return healty;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setHealty(final Integer healty) {
|
void setHealty(final Integer healty) {
|
||||||
this.healty = healty;
|
this.healty = healty;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -72,10 +72,7 @@ public class Computer {
|
|||||||
|
|
||||||
final Computer computer = (Computer) o;
|
final Computer computer = (Computer) o;
|
||||||
|
|
||||||
if (age != null ? !age.equals(computer.age) : computer.age != null) {
|
return (age != null ? age.equals(computer.age) : computer.age == null) && (color != null ? color.equals(computer.color) : computer.color == null);
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return color != null ? color.equals(computer.color) : computer.color == null;
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -7,8 +7,8 @@ import java.util.List;
|
|||||||
|
|
||||||
public class ComputerUtils {
|
public class ComputerUtils {
|
||||||
|
|
||||||
public static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
|
static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
|
||||||
public static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
|
static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
|
||||||
|
|
||||||
public static List<Computer> filter(final List<Computer> inventory, final ComputerPredicate p) {
|
public static List<Computer> filter(final List<Computer> inventory, final ComputerPredicate p) {
|
||||||
|
|
||||||
@ -18,7 +18,7 @@ public class ComputerUtils {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void repair(final Computer computer) {
|
static void repair(final Computer computer) {
|
||||||
if (computer.getHealty() < 50) {
|
if (computer.getHealty() < 50) {
|
||||||
computer.setHealty(100);
|
computer.setHealty(100);
|
||||||
}
|
}
|
||||||
|
@ -13,7 +13,7 @@ public class MacbookPro extends Computer {
|
|||||||
super(age, color);
|
super(age, color);
|
||||||
}
|
}
|
||||||
|
|
||||||
public MacbookPro(Integer age, String color, Integer healty) {
|
MacbookPro(Integer age, String color, Integer healty) {
|
||||||
super(age, color, healty);
|
super(age, color, healty);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -15,7 +15,7 @@ public class TimingDynamicInvocationHandler implements InvocationHandler {
|
|||||||
|
|
||||||
private Object target;
|
private Object target;
|
||||||
|
|
||||||
public TimingDynamicInvocationHandler(Object target) {
|
TimingDynamicInvocationHandler(Object target) {
|
||||||
this.target = target;
|
this.target = target;
|
||||||
|
|
||||||
for(Method method: target.getClass().getDeclaredMethods()) {
|
for(Method method: target.getClass().getDeclaredMethods()) {
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
package com.baeldung.equalshashcode.entities;
|
package com.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
import java.awt.Color;
|
import java.awt.*;
|
||||||
|
|
||||||
public class Square extends Rectangle {
|
public class Square extends Rectangle {
|
||||||
|
|
||||||
Color color;
|
private Color color;
|
||||||
|
|
||||||
public Square(double width, Color color) {
|
public Square(double width, Color color) {
|
||||||
super(width, width);
|
super(width, width);
|
||||||
|
@ -8,7 +8,7 @@ import javax.naming.InitialContext;
|
|||||||
import javax.naming.NamingException;
|
import javax.naming.NamingException;
|
||||||
|
|
||||||
public class LookupFSJNDI {
|
public class LookupFSJNDI {
|
||||||
InitialContext ctx = null;
|
private InitialContext ctx = null;
|
||||||
|
|
||||||
public LookupFSJNDI() throws NamingException {
|
public LookupFSJNDI() throws NamingException {
|
||||||
super();
|
super();
|
||||||
|
@ -1,58 +1,71 @@
|
|||||||
package com.baeldung.map.iteration;
|
package com.baeldung.map.iteration;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.HashMap;
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
public class MapIteration {
|
public class MapIteration {
|
||||||
|
|
||||||
public List<String> iterateUsingEntrySet(Map<String, Integer> map) {
|
public static void main(String[] args) {
|
||||||
List<String> mapKeyValueList = new ArrayList<>();
|
MapIteration mapIteration = new MapIteration();
|
||||||
|
Map<String, Integer> map = new HashMap<>();
|
||||||
|
|
||||||
|
map.put("One", 1);
|
||||||
|
map.put("Three", 3);
|
||||||
|
map.put("Two", 2);
|
||||||
|
|
||||||
|
System.out.println("Iterating Keys of Map Using KeySet");
|
||||||
|
mapIteration.iterateKeys(map);
|
||||||
|
|
||||||
|
System.out.println("Iterating Map Using Entry Set");
|
||||||
|
mapIteration.iterateUsingEntrySet(map);
|
||||||
|
|
||||||
|
System.out.println("Iterating Using Iterator and Map Entry");
|
||||||
|
mapIteration.iterateUsingIteratorAndEntry(map);
|
||||||
|
|
||||||
|
System.out.println("Iterating Using KeySet and For Each");
|
||||||
|
mapIteration.iterateUsingKeySetAndForeach(map);
|
||||||
|
|
||||||
|
System.out.println("Iterating Map Using Lambda Expression");
|
||||||
|
mapIteration.iterateUsingLambda(map);
|
||||||
|
|
||||||
|
System.out.println("Iterating Using Stream API");
|
||||||
|
mapIteration.iterateUsingStreamAPI(map);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void iterateUsingEntrySet(Map<String, Integer> map) {
|
||||||
for (Map.Entry<String, Integer> entry : map.entrySet()) {
|
for (Map.Entry<String, Integer> entry : map.entrySet()) {
|
||||||
mapKeyValueList.add(entry.getKey() + ":" + entry.getValue());
|
System.out.println(entry.getKey() + ":" + entry.getValue());
|
||||||
}
|
}
|
||||||
return mapKeyValueList;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<String> iterateUsingLambda(Map<String, Integer> map) {
|
public void iterateUsingLambda(Map<String, Integer> map) {
|
||||||
List<String> mapKeyValueList = new ArrayList<>();
|
map.forEach((k, v) -> System.out.println((k + ":" + v)));
|
||||||
map.forEach((k, v) -> mapKeyValueList.add(k + ":" + v));
|
|
||||||
return mapKeyValueList;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<String> iterateUsingIteratorAndEntry(Map<String, Integer> map) {
|
public void iterateUsingIteratorAndEntry(Map<String, Integer> map) {
|
||||||
ArrayList<String> mapKeyValueList = new ArrayList<>();
|
|
||||||
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
|
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
|
||||||
|
|
||||||
while (iterator.hasNext()) {
|
while (iterator.hasNext()) {
|
||||||
Map.Entry<String, Integer> pair = iterator.next();
|
Map.Entry<String, Integer> pair = iterator.next();
|
||||||
mapKeyValueList.add(pair.getKey() + ":" + pair.getValue());
|
System.out.println(pair.getKey() + ":" + pair.getValue());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return mapKeyValueList;
|
public void iterateUsingKeySetAndForeach(Map<String, Integer> map) {
|
||||||
}
|
|
||||||
|
|
||||||
public List<String> iterateUsingKeySetAndForeach(Map<String, Integer> map) {
|
|
||||||
List<String> mapKeyValueList = new ArrayList<>();
|
|
||||||
for (String key : map.keySet()) {
|
for (String key : map.keySet()) {
|
||||||
mapKeyValueList.add(key + ":" + map.get(key));
|
System.out.println(key + ":" + map.get(key));
|
||||||
}
|
}
|
||||||
return mapKeyValueList;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<String> iterateUsingStreamAPI(Map<String, Integer> map) {
|
public void iterateUsingStreamAPI(Map<String, Integer> map) {
|
||||||
ArrayList<String> mapKeyValueList = new ArrayList<>();
|
map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
|
||||||
map.entrySet().stream().forEach(e -> mapKeyValueList.add(e.getKey() + ":" + e.getValue()));
|
|
||||||
return mapKeyValueList;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public ArrayList<String> iterateKeys(Map<String, Integer> map) {
|
public void iterateKeys(Map<String, Integer> map) {
|
||||||
ArrayList<String> mapKeyList = new ArrayList<>();
|
|
||||||
for (String key : map.keySet()) {
|
for (String key : map.keySet()) {
|
||||||
mapKeyList.add(key);
|
System.out.println(key);
|
||||||
}
|
}
|
||||||
return mapKeyList;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.maths;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
|
||||||
|
public class BigDecimalImpl {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
BigDecimal serviceTax = new BigDecimal("56.0084578639");
|
||||||
|
serviceTax = serviceTax.setScale(2, RoundingMode.CEILING);
|
||||||
|
|
||||||
|
BigDecimal entertainmentTax = new BigDecimal("23.00689");
|
||||||
|
entertainmentTax = entertainmentTax.setScale(2, RoundingMode.FLOOR);
|
||||||
|
|
||||||
|
BigDecimal totalTax = serviceTax.add(entertainmentTax);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.maths;
|
||||||
|
|
||||||
|
import java.math.BigInteger;
|
||||||
|
|
||||||
|
public class BigIntegerImpl {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476");
|
||||||
|
BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476");
|
||||||
|
|
||||||
|
BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,19 @@
|
|||||||
|
package com.baeldung.outofmemoryerror;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
|
public class OutOfMemoryGCLimitExceed {
|
||||||
|
public static void addRandomDataToMap() {
|
||||||
|
Map<Integer, String> dataMap = new HashMap<>();
|
||||||
|
Random r = new Random();
|
||||||
|
while (true) {
|
||||||
|
dataMap.put(r.nextInt(), String.valueOf(r.nextInt()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
OutOfMemoryGCLimitExceed.addRandomDataToMap();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.typeerasure;
|
||||||
|
|
||||||
|
public class ArrayContentPrintUtil {
|
||||||
|
|
||||||
|
public static <E> void printArray(E[] array) {
|
||||||
|
for (E element : array) {
|
||||||
|
System.out.printf("%s ", element);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <E extends Comparable<E>> void printArray(E[] array) {
|
||||||
|
for (E element : array) {
|
||||||
|
System.out.printf("%s ", element);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,37 @@
|
|||||||
|
package com.baeldung.typeerasure;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
public class BoundStack<E extends Comparable<E>> {
|
||||||
|
|
||||||
|
private E[] stackContent;
|
||||||
|
private int total;
|
||||||
|
|
||||||
|
public BoundStack(int capacity) {
|
||||||
|
this.stackContent = (E[]) new Object[capacity];
|
||||||
|
}
|
||||||
|
|
||||||
|
public void push(E data) {
|
||||||
|
if (total == stackContent.length) {
|
||||||
|
resize(2 * stackContent.length);
|
||||||
|
}
|
||||||
|
stackContent[total++] = data;
|
||||||
|
}
|
||||||
|
|
||||||
|
public E pop() {
|
||||||
|
if (!isEmpty()) {
|
||||||
|
E datum = stackContent[total];
|
||||||
|
stackContent[total--] = null;
|
||||||
|
return datum;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void resize(int capacity) {
|
||||||
|
Arrays.copyOf(stackContent, capacity);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isEmpty() {
|
||||||
|
return total == 0;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.typeerasure;
|
||||||
|
|
||||||
|
public class IntegerStack extends Stack<Integer> {
|
||||||
|
|
||||||
|
public IntegerStack(int capacity) {
|
||||||
|
super(capacity);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void push(Integer value) {
|
||||||
|
System.out.println("Pushing into my integerStack");
|
||||||
|
super.push(value);
|
||||||
|
}
|
||||||
|
}
|
39
core-java/src/main/java/com/baeldung/typeerasure/Stack.java
Normal file
39
core-java/src/main/java/com/baeldung/typeerasure/Stack.java
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
package com.baeldung.typeerasure;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
public class Stack<E> {
|
||||||
|
|
||||||
|
private E[] stackContent;
|
||||||
|
private int total;
|
||||||
|
|
||||||
|
public Stack(int capacity) {
|
||||||
|
this.stackContent = (E[]) new Object[capacity];
|
||||||
|
}
|
||||||
|
|
||||||
|
public void push(E data) {
|
||||||
|
System.out.println("In base stack push#");
|
||||||
|
if (total == stackContent.length) {
|
||||||
|
resize(2 * stackContent.length);
|
||||||
|
}
|
||||||
|
stackContent[total++] = data;
|
||||||
|
}
|
||||||
|
|
||||||
|
public E pop() {
|
||||||
|
if (!isEmpty()) {
|
||||||
|
E datum = stackContent[total];
|
||||||
|
stackContent[total--] = null;
|
||||||
|
return datum;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void resize(int capacity) {
|
||||||
|
Arrays.copyOf(stackContent, capacity);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isEmpty() {
|
||||||
|
return total == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,114 @@
|
|||||||
|
package com.baeldung.concurrent.semaphores;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
public class SemaphoresManualTest {
|
||||||
|
|
||||||
|
// ========= login queue ======
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLoginQueue_whenReachLimit_thenBlocked() {
|
||||||
|
final int slots = 10;
|
||||||
|
final ExecutorService executorService = Executors.newFixedThreadPool(slots);
|
||||||
|
final LoginQueueUsingSemaphore loginQueue = new LoginQueueUsingSemaphore(slots);
|
||||||
|
IntStream.range(0, slots)
|
||||||
|
.forEach(user -> executorService.execute(loginQueue::tryLogin));
|
||||||
|
executorService.shutdown();
|
||||||
|
|
||||||
|
assertEquals(0, loginQueue.availableSlots());
|
||||||
|
assertFalse(loginQueue.tryLogin());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLoginQueue_whenLogout_thenSlotsAvailable() {
|
||||||
|
final int slots = 10;
|
||||||
|
final ExecutorService executorService = Executors.newFixedThreadPool(slots);
|
||||||
|
final LoginQueueUsingSemaphore loginQueue = new LoginQueueUsingSemaphore(slots);
|
||||||
|
IntStream.range(0, slots)
|
||||||
|
.forEach(user -> executorService.execute(loginQueue::tryLogin));
|
||||||
|
executorService.shutdown();
|
||||||
|
|
||||||
|
assertEquals(0, loginQueue.availableSlots());
|
||||||
|
loginQueue.logout();
|
||||||
|
assertTrue(loginQueue.availableSlots() > 0);
|
||||||
|
assertTrue(loginQueue.tryLogin());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========= delay queue =======
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDelayQueue_whenReachLimit_thenBlocked() {
|
||||||
|
final int slots = 50;
|
||||||
|
final ExecutorService executorService = Executors.newFixedThreadPool(slots);
|
||||||
|
final DelayQueueUsingTimedSemaphore delayQueue = new DelayQueueUsingTimedSemaphore(1, slots);
|
||||||
|
IntStream.range(0, slots)
|
||||||
|
.forEach(user -> executorService.execute(delayQueue::tryAdd));
|
||||||
|
executorService.shutdown();
|
||||||
|
|
||||||
|
assertEquals(0, delayQueue.availableSlots());
|
||||||
|
assertFalse(delayQueue.tryAdd());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDelayQueue_whenTimePass_thenSlotsAvailable() throws InterruptedException {
|
||||||
|
final int slots = 50;
|
||||||
|
final ExecutorService executorService = Executors.newFixedThreadPool(slots);
|
||||||
|
final DelayQueueUsingTimedSemaphore delayQueue = new DelayQueueUsingTimedSemaphore(1, slots);
|
||||||
|
IntStream.range(0, slots)
|
||||||
|
.forEach(user -> executorService.execute(delayQueue::tryAdd));
|
||||||
|
executorService.shutdown();
|
||||||
|
|
||||||
|
assertEquals(0, delayQueue.availableSlots());
|
||||||
|
Thread.sleep(1000);
|
||||||
|
assertTrue(delayQueue.availableSlots() > 0);
|
||||||
|
assertTrue(delayQueue.tryAdd());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== mutex ========
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMutexAndMultipleThreads_thenBlocked() throws InterruptedException {
|
||||||
|
final int count = 5;
|
||||||
|
final ExecutorService executorService = Executors.newFixedThreadPool(count);
|
||||||
|
final CounterUsingMutex counter = new CounterUsingMutex();
|
||||||
|
IntStream.range(0, count)
|
||||||
|
.forEach(user -> executorService.execute(() -> {
|
||||||
|
try {
|
||||||
|
counter.increase();
|
||||||
|
} catch (final InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
executorService.shutdown();
|
||||||
|
|
||||||
|
assertTrue(counter.hasQueuedThreads());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMutexAndMultipleThreads_ThenDelay_thenCorrectCount() throws InterruptedException {
|
||||||
|
final int count = 5;
|
||||||
|
final ExecutorService executorService = Executors.newFixedThreadPool(count);
|
||||||
|
final CounterUsingMutex counter = new CounterUsingMutex();
|
||||||
|
IntStream.range(0, count)
|
||||||
|
.forEach(user -> executorService.execute(() -> {
|
||||||
|
try {
|
||||||
|
counter.increase();
|
||||||
|
} catch (final InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
executorService.shutdown();
|
||||||
|
assertTrue(counter.hasQueuedThreads());
|
||||||
|
Thread.sleep(5000);
|
||||||
|
assertFalse(counter.hasQueuedThreads());
|
||||||
|
assertEquals(count, counter.getCount());
|
||||||
|
}
|
||||||
|
}
|
@ -1,69 +0,0 @@
|
|||||||
package com.baeldung.map.iteration;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import org.junit.BeforeClass;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class MapIterationTest {
|
|
||||||
|
|
||||||
public static Map<String, Integer> testMap = new HashMap<String, Integer>();
|
|
||||||
public static String testString1 = "One:1";
|
|
||||||
public static String testString2 = "Two:2";
|
|
||||||
public static String testString3 = "Three:3";
|
|
||||||
|
|
||||||
@BeforeClass
|
|
||||||
public static void createTestData() {
|
|
||||||
testMap.put("One", 1);
|
|
||||||
testMap.put("Three", 3);
|
|
||||||
testMap.put("Two", 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenMap_whenIterateUsingEntrySetReturnsAllEntries_thenCorrect() {
|
|
||||||
MapIteration mapIteration = new MapIteration();
|
|
||||||
List<String> list = mapIteration.iterateUsingEntrySet(testMap);
|
|
||||||
assertTrue((list.contains(testString1)) && (list.contains(testString2)) && (list.contains(testString3)));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenMap_whenIterateUsingLambdaReturnsAllEntries_thenCorrect() {
|
|
||||||
MapIteration mapIteration = new MapIteration();
|
|
||||||
List<String> list = mapIteration.iterateUsingLambda(testMap);
|
|
||||||
assertTrue((list.contains(testString1)) && (list.contains(testString2)) && (list.contains(testString3)));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenMap_whenIterateUsingIteratorAndEntryReturnsAllEntries_thenCorrect() {
|
|
||||||
MapIteration mapIteration = new MapIteration();
|
|
||||||
List<String> list = mapIteration.iterateUsingIteratorAndEntry(testMap);
|
|
||||||
assertTrue((list.contains(testString1)) && (list.contains(testString2)) && (list.contains(testString3)));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenMap_whenIterateUsingKeySetAndForeachReturnsAllEntries_thenCorrect() {
|
|
||||||
MapIteration mapIteration = new MapIteration();
|
|
||||||
List<String> list = mapIteration.iterateUsingKeySetAndForeach(testMap);
|
|
||||||
assertTrue((list.contains(testString1)) && (list.contains(testString2)) && (list.contains(testString3)));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenMap_whenIterateUsingStreamAPIReturnsAllEntries_thenCorrect() {
|
|
||||||
MapIteration mapIteration = new MapIteration();
|
|
||||||
List<String> list = mapIteration.iterateUsingStreamAPI(testMap);
|
|
||||||
assertTrue((list.contains(testString1)) && (list.contains(testString2)) && (list.contains(testString3)));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenMap_whenIterateUsingKeysReturnsAllKeys_thenCorrect() {
|
|
||||||
MapIteration mapIteration = new MapIteration();
|
|
||||||
ArrayList<String> list = mapIteration.iterateKeys(testMap);
|
|
||||||
assertTrue((list.contains("One")) && (list.contains("Two")) && (list.contains("Three")));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -0,0 +1,24 @@
|
|||||||
|
package com.baeldung.maths;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class BigDecimalImplTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBigDecimalNumbers_whenAddedTogether_thenGetExpectedResult() {
|
||||||
|
BigDecimal serviceTax = new BigDecimal("56.0084578639");
|
||||||
|
serviceTax = serviceTax.setScale(2, RoundingMode.CEILING);
|
||||||
|
|
||||||
|
BigDecimal entertainmentTax = new BigDecimal("23.00689");
|
||||||
|
entertainmentTax = entertainmentTax.setScale(2, RoundingMode.FLOOR);
|
||||||
|
|
||||||
|
BigDecimal totalTax = serviceTax.add(entertainmentTax);
|
||||||
|
BigDecimal result = BigDecimal.valueOf(79.01);
|
||||||
|
|
||||||
|
Assert.assertEquals(result, totalTax);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
package com.baeldung.maths;
|
||||||
|
|
||||||
|
import java.math.BigInteger;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class BigIntegerImplTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBigIntegerNumbers_whenAddedTogether_thenGetExpectedResult() {
|
||||||
|
BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476");
|
||||||
|
BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476");
|
||||||
|
|
||||||
|
BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda);
|
||||||
|
BigInteger result = new BigInteger("14110718640342675608722521633212952");
|
||||||
|
|
||||||
|
Assert.assertEquals(result, totalStars);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
package com.baeldung.typeerasure;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class TypeErasureUnitTest {
|
||||||
|
|
||||||
|
@Test(expected = ClassCastException.class)
|
||||||
|
public void givenIntegerStack_whenStringPushedAndAssignPoppedValueToInteger_shouldFail() {
|
||||||
|
IntegerStack integerStack = new IntegerStack(5);
|
||||||
|
Stack stack = integerStack;
|
||||||
|
stack.push("Hello");
|
||||||
|
Integer data = integerStack.pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnyArray_whenInvokedPrintArray_shouldSucceed() {
|
||||||
|
Integer[] scores = new Integer[] { 100, 200, 10, 99, 20 };
|
||||||
|
ArrayContentPrintUtil.printArray(scores);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
39
guest/memory-leaks/pom.xml
Normal file
39
guest/memory-leaks/pom.xml
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>memory-leaks</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>4.12</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources/</directory>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/*.java</exclude>
|
||||||
|
</excludes>
|
||||||
|
</resource>
|
||||||
|
<resource>
|
||||||
|
<directory>src/test/resources/</directory>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.5</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
11
guest/memory-leaks/src/test/java/com/baeldung/Key.java
Normal file
11
guest/memory-leaks/src/test/java/com/baeldung/Key.java
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
package com.baeldung;
|
||||||
|
|
||||||
|
public class Key {
|
||||||
|
|
||||||
|
public static String key;
|
||||||
|
|
||||||
|
public Key(String key) {
|
||||||
|
Key.key = key;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,98 @@
|
|||||||
|
//package com.baeldung;
|
||||||
|
//
|
||||||
|
//import java.io.BufferedReader;
|
||||||
|
//import java.io.File;
|
||||||
|
//import java.io.IOException;
|
||||||
|
//import java.io.InputStream;
|
||||||
|
//import java.io.InputStreamReader;
|
||||||
|
//import java.net.URISyntaxException;
|
||||||
|
//import java.net.URL;
|
||||||
|
//import java.net.URLConnection;
|
||||||
|
//import java.nio.charset.StandardCharsets;
|
||||||
|
//import java.nio.file.Files;
|
||||||
|
//import java.nio.file.Paths;
|
||||||
|
//import java.nio.file.StandardOpenOption;
|
||||||
|
//import java.util.ArrayList;
|
||||||
|
//import java.util.Map;
|
||||||
|
//import java.util.Random;
|
||||||
|
//import java.util.Scanner;
|
||||||
|
//
|
||||||
|
//import org.junit.FixMethodOrder;
|
||||||
|
//import org.junit.Test;
|
||||||
|
//import org.junit.runner.RunWith;
|
||||||
|
//import org.junit.runners.JUnit4;
|
||||||
|
//import org.junit.runners.MethodSorters;
|
||||||
|
//
|
||||||
|
//@FixMethodOrder(MethodSorters.NAME_ASCENDING)
|
||||||
|
//@RunWith(JUnit4.class)
|
||||||
|
//public class MemoryLeaksTest {
|
||||||
|
// private Random random = new Random();
|
||||||
|
// public static final ArrayList<Double> list = new ArrayList<Double>(1000000);
|
||||||
|
//
|
||||||
|
// @Test
|
||||||
|
// public void givenStaticField_whenLotsOfOperations_thenMemoryLeak() throws InterruptedException {
|
||||||
|
// for (int i = 0; i < 1000000; i++) {
|
||||||
|
// list.add(random.nextDouble());
|
||||||
|
// }
|
||||||
|
// System.gc();
|
||||||
|
// Thread.sleep(10000); //to allow GC do its job
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
//
|
||||||
|
// @Test
|
||||||
|
// public void givenNormalField_whenLotsOfOperations_thenGCWorksFine() throws InterruptedException {
|
||||||
|
// addElementsToTheList();
|
||||||
|
// System.gc();
|
||||||
|
// Thread.sleep(10000); //to allow GC do its job
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// private void addElementsToTheList(){
|
||||||
|
// ArrayList<Double> list = new ArrayList<Double>(1000000);
|
||||||
|
// for (int i = 0; i < 1000000; i++) {
|
||||||
|
// list.add(random.nextDouble());
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// @SuppressWarnings({ "resource" })
|
||||||
|
// @Test(expected = OutOfMemoryError.class)
|
||||||
|
// public void givenLengthString_whenIntern_thenOutOfMemory() throws IOException, InterruptedException {
|
||||||
|
// Thread.sleep(15000);
|
||||||
|
// String str = new Scanner(new File("src/test/resources/large.txt"), "UTF-8").useDelimiter("\\A")
|
||||||
|
// .next();
|
||||||
|
// System.gc();
|
||||||
|
// str.intern();
|
||||||
|
// Thread.sleep(10000);
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// @Test(expected = OutOfMemoryError.class)
|
||||||
|
// public void givenURL_whenUnclosedStream_thenOutOfMemory() throws IOException, URISyntaxException {
|
||||||
|
// String str = "";
|
||||||
|
// URLConnection conn = new URL("http:norvig.com/big.txt").openConnection();
|
||||||
|
// BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
|
||||||
|
// while (br.readLine() != null) {
|
||||||
|
// str += br.readLine();
|
||||||
|
// }
|
||||||
|
// Files.write(Paths.get("src/main/resources/"), str.getBytes(), StandardOpenOption.CREATE);
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// @SuppressWarnings("unused")
|
||||||
|
// @Test(expected = OutOfMemoryError.class)
|
||||||
|
// public void givenConnection_whenUnclosed_thenOutOfMemory() throws IOException, URISyntaxException {
|
||||||
|
// URL url = new URL("ftp:speedtest.tele2.net");
|
||||||
|
// URLConnection urlc = url.openConnection();
|
||||||
|
// InputStream is = urlc.getInputStream();
|
||||||
|
// String str = "";
|
||||||
|
// while (true) {
|
||||||
|
// str += is.toString()
|
||||||
|
// .intern();
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// @Test(expected = OutOfMemoryError.class)
|
||||||
|
// public void givenMap_whenNoEqualsNoHashCodeMethods_thenOutOfMemory() throws IOException, URISyntaxException {
|
||||||
|
// Map<Object, Object> map = System.getProperties();
|
||||||
|
// while (true) {
|
||||||
|
// map.put(new Key("key"), "value");
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//}
|
5391
guest/memory-leaks/src/test/resources/large.txt
Normal file
5391
guest/memory-leaks/src/test/resources/large.txt
Normal file
File diff suppressed because it is too large
Load Diff
43
jee7/pom.xml
43
jee7/pom.xml
@ -31,6 +31,7 @@
|
|||||||
<arquillian-glassfish.version>1.0.0.Final</arquillian-glassfish.version>
|
<arquillian-glassfish.version>1.0.0.Final</arquillian-glassfish.version>
|
||||||
|
|
||||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||||
|
<org.springframework.security.version>4.2.3.RELEASE</org.springframework.security.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<prerequisites>
|
<prerequisites>
|
||||||
@ -136,6 +137,34 @@
|
|||||||
<artifactId>standard</artifactId>
|
<artifactId>standard</artifactId>
|
||||||
<version>1.1.2</version>
|
<version>1.1.2</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.mvc</groupId>
|
||||||
|
<artifactId>javax.mvc-api</artifactId>
|
||||||
|
<version>20160715</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.glassfish.ozark</groupId>
|
||||||
|
<artifactId>ozark</artifactId>
|
||||||
|
<version>20160715</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.security</groupId>
|
||||||
|
<artifactId>spring-security-web</artifactId>
|
||||||
|
<version>${org.springframework.security.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.security</groupId>
|
||||||
|
<artifactId>spring-security-config</artifactId>
|
||||||
|
<version>${org.springframework.security.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.security</groupId>
|
||||||
|
<artifactId>spring-security-taglibs</artifactId>
|
||||||
|
<version>${org.springframework.security.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -378,4 +407,18 @@
|
|||||||
</properties>
|
</properties>
|
||||||
</profile>
|
</profile>
|
||||||
</profiles>
|
</profiles>
|
||||||
|
|
||||||
|
<repositories>
|
||||||
|
<repository>
|
||||||
|
<id>bintray-mvc-spec-maven</id>
|
||||||
|
<name>bintray</name>
|
||||||
|
<url>http://dl.bintray.com/mvc-spec/maven</url>
|
||||||
|
<releases>
|
||||||
|
<enabled>true</enabled>
|
||||||
|
</releases>
|
||||||
|
<snapshots>
|
||||||
|
<enabled>false</enabled>
|
||||||
|
</snapshots>
|
||||||
|
</repository>
|
||||||
|
</repositories>
|
||||||
</project>
|
</project>
|
||||||
|
13
jee7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java
Executable file
13
jee7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java
Executable file
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.springSecurity;
|
||||||
|
|
||||||
|
import javax.ws.rs.ApplicationPath;
|
||||||
|
import javax.ws.rs.core.Application;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Application class required by JAX-RS. If you don't want to have any
|
||||||
|
* prefix in the URL, you can set the application path to "/".
|
||||||
|
*/
|
||||||
|
@ApplicationPath("/")
|
||||||
|
public class ApplicationConfig extends Application {
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.springSecurity;
|
||||||
|
|
||||||
|
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
|
||||||
|
|
||||||
|
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
|
||||||
|
|
||||||
|
public SecurityWebApplicationInitializer() {
|
||||||
|
super(SpringSecurityConfig.class);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,46 @@
|
|||||||
|
package com.baeldung.springSecurity;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableWebSecurity
|
||||||
|
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||||
|
@Override
|
||||||
|
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||||
|
auth
|
||||||
|
.inMemoryAuthentication()
|
||||||
|
.withUser("user1")
|
||||||
|
.password("user1Pass")
|
||||||
|
.roles("USER")
|
||||||
|
.and()
|
||||||
|
.withUser("admin")
|
||||||
|
.password("adminPass")
|
||||||
|
.roles("ADMIN");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
|
http
|
||||||
|
.csrf()
|
||||||
|
.disable()
|
||||||
|
.authorizeRequests()
|
||||||
|
.antMatchers("/auth/login*")
|
||||||
|
.anonymous()
|
||||||
|
.antMatchers("/home/admin*")
|
||||||
|
.hasRole("ADMIN")
|
||||||
|
.anyRequest()
|
||||||
|
.authenticated()
|
||||||
|
.and()
|
||||||
|
.formLogin()
|
||||||
|
.loginPage("/auth/login")
|
||||||
|
.defaultSuccessUrl("/home", true)
|
||||||
|
.failureUrl("/auth/login?error=true")
|
||||||
|
.and()
|
||||||
|
.logout()
|
||||||
|
.logoutSuccessUrl("/auth/login");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,28 @@
|
|||||||
|
package com.baeldung.springSecurity.controller;
|
||||||
|
|
||||||
|
import javax.mvc.annotation.Controller;
|
||||||
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.Path;
|
||||||
|
|
||||||
|
@Path("/home")
|
||||||
|
@Controller
|
||||||
|
public class HomeController {
|
||||||
|
|
||||||
|
@GET
|
||||||
|
public String home() {
|
||||||
|
return "home.jsp";
|
||||||
|
}
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Path("/user")
|
||||||
|
public String admin() {
|
||||||
|
return "user.jsp";
|
||||||
|
}
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Path("/admin")
|
||||||
|
public String user() {
|
||||||
|
return "admin.jsp";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.springSecurity.controller;
|
||||||
|
|
||||||
|
import javax.mvc.annotation.Controller;
|
||||||
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.Path;
|
||||||
|
|
||||||
|
@Path("/auth/login")
|
||||||
|
@Controller
|
||||||
|
public class LoginController {
|
||||||
|
|
||||||
|
@GET
|
||||||
|
public String login() {
|
||||||
|
return "login.jsp";
|
||||||
|
}
|
||||||
|
}
|
12
jee7/src/main/webapp/WEB-INF/views/admin.jsp
Normal file
12
jee7/src/main/webapp/WEB-INF/views/admin.jsp
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
|
||||||
|
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
|
||||||
|
<html>
|
||||||
|
<head></head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<h1>Welcome to the ADMIN page</h1>
|
||||||
|
|
||||||
|
<a href="<c:url value="/logout" />">Logout</a>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
26
jee7/src/main/webapp/WEB-INF/views/home.jsp
Normal file
26
jee7/src/main/webapp/WEB-INF/views/home.jsp
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
|
||||||
|
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
|
||||||
|
<html>
|
||||||
|
<head></head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<h1>This is the body of the sample view</h1>
|
||||||
|
|
||||||
|
<security:authorize access="hasRole('USER')">
|
||||||
|
This text is only visible to a user
|
||||||
|
<br/> <br/>
|
||||||
|
<a href="<c:url value="/home/user" />">Restricted Admin Page</a>
|
||||||
|
<br/> <br/>
|
||||||
|
</security:authorize>
|
||||||
|
|
||||||
|
<security:authorize access="hasRole('ADMIN')">
|
||||||
|
This text is only visible to an admin
|
||||||
|
<br/>
|
||||||
|
<a href="<c:url value="/home/admin" />">Admin Page</a>
|
||||||
|
<br/>
|
||||||
|
</security:authorize>
|
||||||
|
|
||||||
|
<a href="<c:url value="/logout" />">Logout</a>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
26
jee7/src/main/webapp/WEB-INF/views/login.jsp
Normal file
26
jee7/src/main/webapp/WEB-INF/views/login.jsp
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
<html>
|
||||||
|
<head></head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<h1>Login</h1>
|
||||||
|
|
||||||
|
<form name='f' action="/auth/login" method='POST'>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<td>User:</td>
|
||||||
|
<td><input type='text' name='username' value=''></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>Password:</td>
|
||||||
|
<td><input type='password' name='password'/></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td><input name="submit" type="submit" value="submit"/></td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
</form>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
12
jee7/src/main/webapp/WEB-INF/views/user.jsp
Normal file
12
jee7/src/main/webapp/WEB-INF/views/user.jsp
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
|
||||||
|
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
|
||||||
|
<html>
|
||||||
|
<head></head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<h1>Welcome to the Restricted Admin page</h1>
|
||||||
|
|
||||||
|
<a href="<c:url value="/logout" />">Logout</a>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
@ -1,8 +0,0 @@
|
|||||||
## Relevant articles:
|
|
||||||
|
|
||||||
- [Introduction to the Kotlin Language](http://www.baeldung.com/kotlin)
|
|
||||||
- [A guide to the “when{}” block in Kotlin](http://www.baeldung.com/kotlin-when)
|
|
||||||
- [Comprehensive Guide to Null Safety in Kotlin](http://www.baeldung.com/kotlin-null-safety)
|
|
||||||
- [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability)
|
|
||||||
- [Difference Between “==” and “===” in Kotlin](http://www.baeldung.com/kotlin-equality-operators)
|
|
||||||
- [Generics in Kotlin](http://www.baeldung.com/kotlin-generics)
|
|
@ -1,121 +0,0 @@
|
|||||||
<?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>kotlin-mockito</artifactId>
|
|
||||||
<version>1.0-SNAPSHOT</version>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>parent-modules</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.jetbrains.kotlin</groupId>
|
|
||||||
<artifactId>kotlin-stdlib</artifactId>
|
|
||||||
<version>${kotlin.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.mockito</groupId>
|
|
||||||
<artifactId>mockito-core</artifactId>
|
|
||||||
<version>${mockito.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>junit</groupId>
|
|
||||||
<artifactId>junit</artifactId>
|
|
||||||
<version>${junit.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.nhaarman</groupId>
|
|
||||||
<artifactId>mockito-kotlin</artifactId>
|
|
||||||
<version>${mockito-kotlin.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
|
|
||||||
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
|
|
||||||
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<artifactId>kotlin-maven-plugin</artifactId>
|
|
||||||
<groupId>org.jetbrains.kotlin</groupId>
|
|
||||||
<version>${kotlin.version}</version>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<id>compile</id>
|
|
||||||
<goals>
|
|
||||||
<goal>compile</goal>
|
|
||||||
</goals>
|
|
||||||
<configuration>
|
|
||||||
<sourceDirs>
|
|
||||||
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
|
|
||||||
<sourceDir>${project.basedir}/src/main/java</sourceDir>
|
|
||||||
</sourceDirs>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
|
||||||
<execution>
|
|
||||||
<id>test-compile</id>
|
|
||||||
<goals>
|
|
||||||
<goal>test-compile</goal>
|
|
||||||
</goals>
|
|
||||||
<configuration>
|
|
||||||
<sourceDirs>
|
|
||||||
<sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
|
|
||||||
<sourceDir>${project.basedir}/src/test/java</sourceDir>
|
|
||||||
</sourceDirs>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
|
||||||
<version>${maven-compiler.version}</version>
|
|
||||||
<executions>
|
|
||||||
<!-- Replacing default-compile as it is treated specially
|
|
||||||
by maven -->
|
|
||||||
<execution>
|
|
||||||
<id>default-compile</id>
|
|
||||||
<phase>none</phase>
|
|
||||||
</execution>
|
|
||||||
<!-- Replacing default-testCompile as it is treated specially
|
|
||||||
by maven -->
|
|
||||||
<execution>
|
|
||||||
<id>default-testCompile</id>
|
|
||||||
<phase>none</phase>
|
|
||||||
</execution>
|
|
||||||
<execution>
|
|
||||||
<id>java-compile</id>
|
|
||||||
<phase>compile</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>compile</goal>
|
|
||||||
</goals>
|
|
||||||
</execution>
|
|
||||||
<execution>
|
|
||||||
<id>java-test-compile</id>
|
|
||||||
<phase>test-compile</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>testCompile</goal>
|
|
||||||
</goals>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<mockito.version>2.8.9</mockito.version>
|
|
||||||
<junit.version>4.12</junit.version>
|
|
||||||
<kotlin.version>1.1.2-4</kotlin.version>
|
|
||||||
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
|
|
||||||
<maven-compiler.version>3.5.1</maven-compiler.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
|
@ -1,24 +0,0 @@
|
|||||||
package com.baeldung.java;
|
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.FileReader;
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
public class ArrayExample {
|
|
||||||
|
|
||||||
public int sumValues(int[] nums) {
|
|
||||||
int res = 0;
|
|
||||||
|
|
||||||
for (int x:nums) {
|
|
||||||
res += x;
|
|
||||||
}
|
|
||||||
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void writeList() throws IOException {
|
|
||||||
File file = new File("E://file.txt");
|
|
||||||
FileReader fr = new FileReader(file);
|
|
||||||
fr.close();
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,24 +0,0 @@
|
|||||||
package com.baeldung.java;
|
|
||||||
|
|
||||||
public class Customer {
|
|
||||||
|
|
||||||
private String firstName;
|
|
||||||
private String lastName;
|
|
||||||
|
|
||||||
public String getFirstName() {
|
|
||||||
return firstName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setFirstName(String firstName) {
|
|
||||||
this.firstName = firstName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getLastName() {
|
|
||||||
return lastName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setLastName(String lastName) {
|
|
||||||
this.lastName = lastName;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,7 +0,0 @@
|
|||||||
package com.baeldung.java;
|
|
||||||
|
|
||||||
public class StringUtils {
|
|
||||||
public static String toUpperCase(String name) {
|
|
||||||
return name.toUpperCase();
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,17 +0,0 @@
|
|||||||
package com.baeldung.kotlin;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
public class JavaCallToKotlinUnitTest {
|
|
||||||
@Test
|
|
||||||
public void givenKotlinClass_whenCallFromJava_shouldProduceResults() {
|
|
||||||
//when
|
|
||||||
int res = new MathematicsOperations().addTwoNumbers(2, 4);
|
|
||||||
|
|
||||||
//then
|
|
||||||
assertEquals(6, res);
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
@ -3,7 +3,6 @@
|
|||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>kotlin</artifactId>
|
<artifactId>kotlin</artifactId>
|
||||||
<version>1.0-SNAPSHOT</version>
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
|
||||||
@ -13,6 +12,13 @@
|
|||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
|
<repositories>
|
||||||
|
<repository>
|
||||||
|
<id>central</id>
|
||||||
|
<url>http://jcenter.bintray.com</url>
|
||||||
|
</repository>
|
||||||
|
</repositories>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.jetbrains.kotlin</groupId>
|
<groupId>org.jetbrains.kotlin</groupId>
|
||||||
@ -31,9 +37,19 @@
|
|||||||
<version>${kotlin-reflect.version}</version>
|
<version>${kotlin-reflect.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jetbrains.kotlinx</groupId>
|
||||||
|
<artifactId>kotlinx-coroutines-core</artifactId>
|
||||||
|
<version>${kotlinx.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.nhaarman</groupId>
|
||||||
|
<artifactId>mockito-kotlin</artifactId>
|
||||||
|
<version>${mockito-kotlin.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
@ -104,10 +120,12 @@
|
|||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<kotlin-maven-plugin.version>1.1.1</kotlin-maven-plugin.version>
|
<kotlin-maven-plugin.version>1.1.2</kotlin-maven-plugin.version>
|
||||||
<kotlin-test-junit.version>1.1.1</kotlin-test-junit.version>
|
<kotlin-test-junit.version>1.1.2</kotlin-test-junit.version>
|
||||||
<kotlin-stdlib.version>1.1.1</kotlin-stdlib.version>
|
<kotlin-stdlib.version>1.1.2</kotlin-stdlib.version>
|
||||||
<kotlin-reflect.version>1.1.1</kotlin-reflect.version>
|
<kotlin-reflect.version>1.1.2</kotlin-reflect.version>
|
||||||
|
<kotlinx.version>0.15</kotlinx.version>
|
||||||
|
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
179
kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt
Normal file
179
kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt
Normal file
@ -0,0 +1,179 @@
|
|||||||
|
package com.baeldung.kotlin
|
||||||
|
|
||||||
|
import kotlinx.coroutines.experimental.*
|
||||||
|
import org.junit.Test
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
|
import kotlin.coroutines.experimental.buildSequence
|
||||||
|
import kotlin.system.measureTimeMillis
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
|
|
||||||
|
class CoroutinesTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenBuildSequence_whenTakeNElements_thenShouldReturnItInALazyWay() {
|
||||||
|
//given
|
||||||
|
val fibonacciSeq = buildSequence {
|
||||||
|
var a = 0
|
||||||
|
var b = 1
|
||||||
|
|
||||||
|
yield(1)
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
yield(a + b)
|
||||||
|
|
||||||
|
val tmp = a + b
|
||||||
|
a = b
|
||||||
|
b = tmp
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//when
|
||||||
|
val res = fibonacciSeq.take(5).toList()
|
||||||
|
|
||||||
|
//then
|
||||||
|
assertEquals(res, listOf(1, 1, 2, 3, 5))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenLazySeq_whenTakeNElements_thenShouldReturnAllElements() {
|
||||||
|
//given
|
||||||
|
val lazySeq = buildSequence {
|
||||||
|
print("START ")
|
||||||
|
for (i in 1..5) {
|
||||||
|
yield(i)
|
||||||
|
print("STEP ")
|
||||||
|
}
|
||||||
|
print("END")
|
||||||
|
}
|
||||||
|
//when
|
||||||
|
val res = lazySeq.take(10).toList()
|
||||||
|
|
||||||
|
//then
|
||||||
|
assertEquals(res, listOf(1, 2, 3, 4, 5))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenAsyncCoroutine_whenStartIt_thenShouldExecuteItInTheAsyncWay() {
|
||||||
|
//given
|
||||||
|
val res = mutableListOf<String>()
|
||||||
|
|
||||||
|
//when
|
||||||
|
runBlocking<Unit> {
|
||||||
|
val promise = launch(CommonPool) { expensiveComputation(res) }
|
||||||
|
res.add("Hello,")
|
||||||
|
promise.join()
|
||||||
|
}
|
||||||
|
|
||||||
|
//then
|
||||||
|
assertEquals(res, listOf("Hello,", "word!"))
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
suspend fun expensiveComputation(res: MutableList<String>) {
|
||||||
|
delay(1000L)
|
||||||
|
res.add("word!")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenHugeAmountOfCoroutines_whenStartIt_thenShouldExecuteItWithoutOutOfMemory() {
|
||||||
|
runBlocking<Unit> {
|
||||||
|
//given
|
||||||
|
val counter = AtomicInteger(0)
|
||||||
|
val numberOfCoroutines = 100_000
|
||||||
|
|
||||||
|
//when
|
||||||
|
val jobs = List(numberOfCoroutines) {
|
||||||
|
launch(CommonPool) {
|
||||||
|
delay(1L)
|
||||||
|
counter.incrementAndGet()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
jobs.forEach { it.join() }
|
||||||
|
|
||||||
|
//then
|
||||||
|
assertEquals(counter.get(), numberOfCoroutines)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenCancellableJob_whenRequestForCancel_thenShouldQuit() {
|
||||||
|
runBlocking<Unit> {
|
||||||
|
//given
|
||||||
|
val job = launch(CommonPool) {
|
||||||
|
while (isActive) {
|
||||||
|
println("is working")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
delay(1300L)
|
||||||
|
|
||||||
|
//when
|
||||||
|
job.cancel()
|
||||||
|
|
||||||
|
//then cancel successfully
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = CancellationException::class)
|
||||||
|
fun givenAsyncAction_whenDeclareTimeout_thenShouldFinishWhenTimedOut() {
|
||||||
|
runBlocking<Unit> {
|
||||||
|
withTimeout(1300L) {
|
||||||
|
repeat(1000) { i ->
|
||||||
|
println("Some expensive computation $i ...")
|
||||||
|
delay(500L)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenHaveTwoExpensiveAction_whenExecuteThemAsync_thenTheyShouldRunConcurrently() {
|
||||||
|
runBlocking<Unit> {
|
||||||
|
val delay = 1000L
|
||||||
|
val time = measureTimeMillis {
|
||||||
|
//given
|
||||||
|
val one = async(CommonPool) { someExpensiveComputation(delay) }
|
||||||
|
val two = async(CommonPool) { someExpensiveComputation(delay) }
|
||||||
|
|
||||||
|
//when
|
||||||
|
runBlocking {
|
||||||
|
one.await()
|
||||||
|
two.await()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//then
|
||||||
|
assertTrue(time < delay * 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenTwoExpensiveAction_whenExecuteThemLazy_thenTheyShouldNotConcurrently() {
|
||||||
|
runBlocking<Unit> {
|
||||||
|
val delay = 1000L
|
||||||
|
val time = measureTimeMillis {
|
||||||
|
//given
|
||||||
|
val one = async(CommonPool, CoroutineStart.LAZY) { someExpensiveComputation(delay) }
|
||||||
|
val two = async(CommonPool, CoroutineStart.LAZY) { someExpensiveComputation(delay) }
|
||||||
|
|
||||||
|
//when
|
||||||
|
runBlocking {
|
||||||
|
one.await()
|
||||||
|
two.await()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//then
|
||||||
|
assertTrue(time > delay * 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun someExpensiveComputation(delayInMilliseconds: Long) {
|
||||||
|
delay(delayInMilliseconds)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
@ -17,6 +17,7 @@
|
|||||||
- [Introduction to HikariCP](http://www.baeldung.com/hikaricp)
|
- [Introduction to HikariCP](http://www.baeldung.com/hikaricp)
|
||||||
- [Serenity BDD with Spring and JBehave](http://www.baeldung.com/serenity-spring-jbehave)
|
- [Serenity BDD with Spring and JBehave](http://www.baeldung.com/serenity-spring-jbehave)
|
||||||
- [Locality-Sensitive Hashing in Java Using Java-LSH](http://www.baeldung.com/locality-sensitive-hashing)
|
- [Locality-Sensitive Hashing in Java Using Java-LSH](http://www.baeldung.com/locality-sensitive-hashing)
|
||||||
|
- [Apache Commons Collections OrderedMap](http://www.baeldung.com/apache-commons-ordered-map)
|
||||||
|
|
||||||
|
|
||||||
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.
|
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.
|
||||||
|
@ -70,32 +70,6 @@
|
|||||||
</execution>
|
</execution>
|
||||||
</executions>
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
|
||||||
<groupId>org.asciidoctor</groupId>
|
|
||||||
<artifactId>asciidoctor-maven-plugin</artifactId>
|
|
||||||
<version>1.5.5</version>
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.asciidoctor</groupId>
|
|
||||||
<artifactId>asciidoctorj-pdf</artifactId>
|
|
||||||
<version>1.5.0-alpha.15</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<id>output-pdf</id>
|
|
||||||
<phase>generate-resources</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>process-asciidoc</goal>
|
|
||||||
</goals>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
<configuration>
|
|
||||||
<sourceDirectory>src/docs/asciidoc</sourceDirectory>
|
|
||||||
<outputDirectory>target/docs/asciidoc</outputDirectory>
|
|
||||||
<backend>pdf</backend>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
@ -116,6 +90,11 @@
|
|||||||
<artifactId>commons-lang3</artifactId>
|
<artifactId>commons-lang3</artifactId>
|
||||||
<version>${commons-lang.version}</version>
|
<version>${commons-lang.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-text</artifactId>
|
||||||
|
<version>${commons-text.version}</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-collections4</artifactId>
|
<artifactId>commons-collections4</artifactId>
|
||||||
@ -216,12 +195,6 @@
|
|||||||
<artifactId>serenity-core</artifactId>
|
<artifactId>serenity-core</artifactId>
|
||||||
<version>${serenity.version}</version>
|
<version>${serenity.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
<exclusions>
|
|
||||||
<exclusion>
|
|
||||||
<groupId>org.asciidoctor</groupId>
|
|
||||||
<artifactId>asciidoctor-java-integration</artifactId>
|
|
||||||
</exclusion>
|
|
||||||
</exclusions>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>net.serenity-bdd</groupId>
|
<groupId>net.serenity-bdd</groupId>
|
||||||
@ -365,16 +338,6 @@
|
|||||||
<artifactId>netty-all</artifactId>
|
<artifactId>netty-all</artifactId>
|
||||||
<version>${netty.version}</version>
|
<version>${netty.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>org.asciidoctor</groupId>
|
|
||||||
<artifactId>asciidoctorj</artifactId>
|
|
||||||
<version>1.5.4</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.asciidoctor</groupId>
|
|
||||||
<artifactId>asciidoctorj-pdf</artifactId>
|
|
||||||
<version>1.5.0-alpha.11</version>
|
|
||||||
</dependency>
|
|
||||||
<!-- OpenNLP -->
|
<!-- OpenNLP -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.opennlp</groupId>
|
<groupId>org.apache.opennlp</groupId>
|
||||||
@ -392,11 +355,23 @@
|
|||||||
<artifactId>java-lsh</artifactId>
|
<artifactId>java-lsh</artifactId>
|
||||||
<version>${java-lsh.version}</version>
|
<version>${java-lsh.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>au.com.dius</groupId>
|
||||||
|
<artifactId>pact-jvm-consumer-junit_2.11</artifactId>
|
||||||
|
<version>${pact.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.codehaus.groovy</groupId>
|
||||||
|
<artifactId>groovy-all</artifactId>
|
||||||
|
<version>2.4.10</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
<properties>
|
<properties>
|
||||||
<multiverse.version>0.7.0</multiverse.version>
|
<multiverse.version>0.7.0</multiverse.version>
|
||||||
<cglib.version>3.2.4</cglib.version>
|
<cglib.version>3.2.4</cglib.version>
|
||||||
<commons-lang.version>3.5</commons-lang.version>
|
<commons-lang.version>3.5</commons-lang.version>
|
||||||
|
<commons-text.version>1.1</commons-text.version>
|
||||||
<commons-beanutils.version>1.9.3</commons-beanutils.version>
|
<commons-beanutils.version>1.9.3</commons-beanutils.version>
|
||||||
<jasypt.version>1.9.2</jasypt.version>
|
<jasypt.version>1.9.2</jasypt.version>
|
||||||
<javatuples.version>1.2</javatuples.version>
|
<javatuples.version>1.2</javatuples.version>
|
||||||
@ -421,6 +396,7 @@
|
|||||||
<commons.collections.version>4.1</commons.collections.version>
|
<commons.collections.version>4.1</commons.collections.version>
|
||||||
<junit.version>4.12</junit.version>
|
<junit.version>4.12</junit.version>
|
||||||
<java-lsh.version>0.10</java-lsh.version>
|
<java-lsh.version>0.10</java-lsh.version>
|
||||||
|
<pact.version>3.5.0</pact.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -0,0 +1,35 @@
|
|||||||
|
package com.baeldung.commons.beanutils;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class CourseEntity {
|
||||||
|
private String name;
|
||||||
|
private List<String> codes;
|
||||||
|
private Map<String, Student> students = new HashMap<String, Student>();
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> getCodes() {
|
||||||
|
return codes;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCodes(List<String> codes) {
|
||||||
|
this.codes = codes;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStudent(String id, Student student) {
|
||||||
|
students.put(id, student);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Student getStudent(String enrolledId) {
|
||||||
|
return students.get(enrolledId);
|
||||||
|
}
|
||||||
|
}
|
@ -3,6 +3,7 @@ package com.baeldung.commons.beanutils;
|
|||||||
import java.lang.reflect.InvocationTargetException;
|
import java.lang.reflect.InvocationTargetException;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.apache.commons.beanutils.BeanUtils;
|
||||||
import org.apache.commons.beanutils.PropertyUtils;
|
import org.apache.commons.beanutils.PropertyUtils;
|
||||||
|
|
||||||
public class CourseService {
|
public class CourseService {
|
||||||
@ -31,4 +32,9 @@ public class CourseService {
|
|||||||
return (String) PropertyUtils.getNestedProperty(
|
return (String) PropertyUtils.getNestedProperty(
|
||||||
course, "enrolledStudent(" + enrollId + ")." + nestedPropertyName);
|
course, "enrolledStudent(" + enrollId + ")." + nestedPropertyName);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static void copyProperties(Course course, CourseEntity courseEntity)
|
||||||
|
throws IllegalAccessException, InvocationTargetException {
|
||||||
|
BeanUtils.copyProperties(course, courseEntity);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,47 @@
|
|||||||
|
package com.baeldung.commons.collectionutil;
|
||||||
|
|
||||||
|
public class Address {
|
||||||
|
|
||||||
|
private String locality;
|
||||||
|
private String city;
|
||||||
|
private String zip;
|
||||||
|
|
||||||
|
public String getLocality() {
|
||||||
|
return locality;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLocality(String locality) {
|
||||||
|
this.locality = locality;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCity() {
|
||||||
|
return city;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCity(String city) {
|
||||||
|
this.city = city;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getZip() {
|
||||||
|
return zip;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setZip(String zip) {
|
||||||
|
this.zip = zip;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
StringBuilder builder = new StringBuilder();
|
||||||
|
builder.append("Address [locality=").append(locality).append(", city=").append(city).append(", zip=").append(zip).append("]");
|
||||||
|
return builder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Address(String locality, String city, String zip) {
|
||||||
|
super();
|
||||||
|
this.locality = locality;
|
||||||
|
this.city = city;
|
||||||
|
this.zip = zip;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,118 @@
|
|||||||
|
package com.baeldung.commons.collectionutil;
|
||||||
|
|
||||||
|
public class Customer implements Comparable<Customer> {
|
||||||
|
|
||||||
|
private Integer id;
|
||||||
|
private String name;
|
||||||
|
private Long phone;
|
||||||
|
private String locality;
|
||||||
|
private String city;
|
||||||
|
private String zip;
|
||||||
|
|
||||||
|
public Integer getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(Integer id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getPhone() {
|
||||||
|
return phone;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPhone(Long phone) {
|
||||||
|
this.phone = phone;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLocality() {
|
||||||
|
return locality;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLocality(String locality) {
|
||||||
|
this.locality = locality;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCity() {
|
||||||
|
return city;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCity(String city) {
|
||||||
|
this.city = city;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getZip() {
|
||||||
|
return zip;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setZip(String zip) {
|
||||||
|
this.zip = zip;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Customer(Integer id, String name, Long phone, String locality, String city, String zip) {
|
||||||
|
super();
|
||||||
|
this.id = id;
|
||||||
|
this.name = name;
|
||||||
|
this.phone = phone;
|
||||||
|
this.locality = locality;
|
||||||
|
this.city = city;
|
||||||
|
this.zip = zip;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Customer(Integer id, String name, Long phone) {
|
||||||
|
super();
|
||||||
|
this.id = id;
|
||||||
|
this.name = name;
|
||||||
|
this.phone = phone;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Customer(String name) {
|
||||||
|
super();
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
final int prime = 31;
|
||||||
|
int result = 1;
|
||||||
|
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (this == obj)
|
||||||
|
return true;
|
||||||
|
if (obj == null)
|
||||||
|
return false;
|
||||||
|
if (getClass() != obj.getClass())
|
||||||
|
return false;
|
||||||
|
Customer other = (Customer) obj;
|
||||||
|
if (name == null) {
|
||||||
|
if (other.name != null)
|
||||||
|
return false;
|
||||||
|
} else if (!name.equals(other.name))
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int compareTo(Customer o) {
|
||||||
|
return this.name.compareTo(o.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
StringBuilder builder = new StringBuilder();
|
||||||
|
builder.append("Customer [id=").append(id).append(", name=").append(name).append(", phone=").append(phone).append("]");
|
||||||
|
return builder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -35,4 +35,19 @@ public class CourseServiceTest {
|
|||||||
Assert.assertEquals(studentName, accessedStudentName);
|
Assert.assertEquals(studentName, accessedStudentName);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCopyProperties_whenCopyCourseToCourseEntity_thenCopyPropertyWithSameName()
|
||||||
|
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
||||||
|
Course course = new Course();
|
||||||
|
course.setName("Computer Science");
|
||||||
|
course.setCodes(Arrays.asList("CS"));
|
||||||
|
course.setEnrolledStudent("ST-1", new Student());
|
||||||
|
|
||||||
|
CourseEntity courseEntity = new CourseEntity();
|
||||||
|
|
||||||
|
CourseService.copyProperties(course, courseEntity);
|
||||||
|
Assert.assertEquals(course.getName(), courseEntity.getName());
|
||||||
|
Assert.assertEquals(course.getCodes(), courseEntity.getCodes());
|
||||||
|
Assert.assertNull(courseEntity.getStudent("ST-1"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,49 @@
|
|||||||
|
package com.baeldung.commons.collections;
|
||||||
|
|
||||||
|
import org.apache.commons.collections4.BidiMap;
|
||||||
|
import org.apache.commons.collections4.bidimap.DualHashBidiMap;
|
||||||
|
import org.apache.commons.collections4.bidimap.DualLinkedHashBidiMap;
|
||||||
|
import org.apache.commons.collections4.bidimap.DualTreeBidiMap;
|
||||||
|
import org.apache.commons.collections4.bidimap.TreeBidiMap;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Created by smatt on 03/07/2017.
|
||||||
|
*/
|
||||||
|
public class BidiMapUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenKeyValue_whenPut_thenAddEntryToMap() {
|
||||||
|
BidiMap<String, String> map = new DualHashBidiMap<>();
|
||||||
|
map.put("key1", "value1");
|
||||||
|
map.put("key2", "value2");
|
||||||
|
assertEquals(map.size(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenInverseBidiMap_thenInverseKeyValue() {
|
||||||
|
BidiMap<String, String> map = new DualHashBidiMap<>();
|
||||||
|
map.put("key1", "value1");
|
||||||
|
map.put("key2", "value2");
|
||||||
|
BidiMap<String, String> rMap = map.inverseBidiMap();
|
||||||
|
assertTrue(rMap.containsKey("value1") && rMap.containsKey("value2"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValue_whenRemoveValue_thenRemoveMatchingMapEntry() {
|
||||||
|
BidiMap<String, String> map = new DualHashBidiMap<>();
|
||||||
|
map.put("key1", "value1");
|
||||||
|
map.put("key2", "value2");
|
||||||
|
map.removeValue("value2");
|
||||||
|
assertFalse(map.containsKey("key2"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValue_whenGetKey_thenMappedKey() {
|
||||||
|
BidiMap<String, String> map = new DualHashBidiMap<>();
|
||||||
|
map.put("key1", "value1");
|
||||||
|
assertEquals(map.getKey("value1"), "key1");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,113 @@
|
|||||||
|
package com.baeldung.commons.collections;
|
||||||
|
|
||||||
|
|
||||||
|
import com.baeldung.commons.collectionutil.Address;
|
||||||
|
import com.baeldung.commons.collectionutil.Customer;
|
||||||
|
import org.apache.commons.collections4.Closure;
|
||||||
|
import org.apache.commons.collections4.CollectionUtils;
|
||||||
|
import org.apache.commons.collections4.Predicate;
|
||||||
|
import org.apache.commons.collections4.Transformer;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
public class CollectionUtilsGuideTest {
|
||||||
|
|
||||||
|
|
||||||
|
Customer customer1 = new Customer(1, "Daniel", 123456l, "locality1", "city1", "1234");
|
||||||
|
Customer customer4 = new Customer(4, "Bob", 456789l, "locality4", "city4", "4567");
|
||||||
|
List<Customer> list1, list2, list3, linkedList1;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() {
|
||||||
|
Customer customer2 = new Customer(2, "Fredrik", 234567l, "locality2", "city2", "2345");
|
||||||
|
Customer customer3 = new Customer(3, "Kyle", 345678l, "locality3", "city3", "3456");
|
||||||
|
Customer customer5 = new Customer(5, "Cat", 567890l, "locality5", "city5", "5678");
|
||||||
|
Customer customer6 = new Customer(6, "John", 678901l, "locality6", "city6", "6789");
|
||||||
|
|
||||||
|
list1 = Arrays.asList(customer1, customer2, customer3);
|
||||||
|
list2 = Arrays.asList(customer4, customer5, customer6);
|
||||||
|
list3 = Arrays.asList(customer1, customer2);
|
||||||
|
|
||||||
|
linkedList1 = new LinkedList<>(list1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenList_whenAddIgnoreNull_thenNoNullAdded() {
|
||||||
|
CollectionUtils.addIgnoreNull(list1, null);
|
||||||
|
assertFalse(list1.contains(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoSortedLists_whenCollated_thenSorted() {
|
||||||
|
List<Customer> sortedList = CollectionUtils.collate(list1, list2);
|
||||||
|
|
||||||
|
assertEquals(6, sortedList.size());
|
||||||
|
assertTrue(sortedList.get(0).getName().equals("Bob"));
|
||||||
|
assertTrue(sortedList.get(2).getName().equals("Daniel"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenListOfCustomers_whenTransformed_thenListOfAddress() {
|
||||||
|
Collection<Address> addressCol = CollectionUtils.collect(list1, customer -> {
|
||||||
|
return new Address(customer.getLocality(), customer.getCity(), customer.getZip());
|
||||||
|
});
|
||||||
|
|
||||||
|
List<Address> addressList = new ArrayList<>(addressCol);
|
||||||
|
assertTrue(addressList.size() == 3);
|
||||||
|
assertTrue(addressList.get(0).getLocality().equals("locality1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCustomerList_whenFiltered_thenCorrectSize() {
|
||||||
|
|
||||||
|
boolean isModified = CollectionUtils.filter(linkedList1, customer -> Arrays.asList("Daniel","Kyle").contains(customer.getName()));
|
||||||
|
|
||||||
|
//filterInverse does the opposite. It removes the element from the list if the Predicate returns true
|
||||||
|
//select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection
|
||||||
|
|
||||||
|
assertTrue(isModified && linkedList1.size() == 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNonEmptyList_whenCheckedIsNotEmpty_thenTrue() {
|
||||||
|
List<Customer> emptyList = new ArrayList<>();
|
||||||
|
List<Customer> nullList = null;
|
||||||
|
|
||||||
|
//Very handy at times where we want to check if a collection is not null and not empty too.
|
||||||
|
//isNotEmpty does the opposite. Handy because using ! operator on isEmpty makes it missable while reading
|
||||||
|
assertTrue(CollectionUtils.isNotEmpty(list1));
|
||||||
|
assertTrue(CollectionUtils.isEmpty(nullList));
|
||||||
|
assertTrue(CollectionUtils.isEmpty(emptyList));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCustomerListAndASubcollection_whenChecked_thenTrue() {
|
||||||
|
assertTrue(CollectionUtils.isSubCollection(list3, list1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenIntersected_thenCheckSize() {
|
||||||
|
Collection<Customer> intersection = CollectionUtils.intersection(list1, list3);
|
||||||
|
assertTrue(intersection.size() == 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenSubtracted_thenCheckElementNotPresentInA() {
|
||||||
|
Collection<Customer> result = CollectionUtils.subtract(list1, list3);
|
||||||
|
assertFalse(result.contains(customer1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenUnioned_thenCheckElementPresentInResult() {
|
||||||
|
Collection<Customer> union = CollectionUtils.union(list1, list2);
|
||||||
|
assertTrue(union.contains(customer1));
|
||||||
|
assertTrue(union.contains(customer4));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,5 +1,10 @@
|
|||||||
package com.baeldung.commons.collections.orderedmap;
|
package com.baeldung.commons.collections.orderedmap;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
import org.apache.commons.collections4.OrderedMap;
|
import org.apache.commons.collections4.OrderedMap;
|
||||||
import org.apache.commons.collections4.OrderedMapIterator;
|
import org.apache.commons.collections4.OrderedMapIterator;
|
||||||
import org.apache.commons.collections4.map.LinkedMap;
|
import org.apache.commons.collections4.map.LinkedMap;
|
||||||
@ -7,11 +12,6 @@ import org.apache.commons.collections4.map.ListOrderedMap;
|
|||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
public class OrderedMapUnitTest {
|
public class OrderedMapUnitTest {
|
||||||
|
|
||||||
private String[] names = {"Emily", "Mathew", "Rose", "John", "Anna"};
|
private String[] names = {"Emily", "Mathew", "Rose", "John", "Anna"};
|
||||||
@ -45,11 +45,12 @@ public class OrderedMapUnitTest {
|
|||||||
// as defined in the constant arrays of names and ages:
|
// as defined in the constant arrays of names and ages:
|
||||||
|
|
||||||
OrderedMapIterator<String, Integer> runnersIterator = this.runnersLinkedMap.mapIterator();
|
OrderedMapIterator<String, Integer> runnersIterator = this.runnersLinkedMap.mapIterator();
|
||||||
for (int i = 0; runnersIterator.hasNext(); i++) {
|
int i = 0;
|
||||||
|
while (runnersIterator.hasNext()) {
|
||||||
runnersIterator.next();
|
runnersIterator.next();
|
||||||
|
|
||||||
assertEquals(runnersIterator.getKey(), this.names[i]);
|
assertEquals(runnersIterator.getKey(), this.names[i]);
|
||||||
assertEquals(runnersIterator.getValue(), this.ages[i]);
|
assertEquals(runnersIterator.getValue(), this.ages[i]);
|
||||||
|
i++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -59,11 +60,12 @@ public class OrderedMapUnitTest {
|
|||||||
// as defined in the constant arrays of names and ages:
|
// as defined in the constant arrays of names and ages:
|
||||||
|
|
||||||
OrderedMapIterator<String, Integer> runnersIterator = this.runnersListOrderedMap.mapIterator();
|
OrderedMapIterator<String, Integer> runnersIterator = this.runnersListOrderedMap.mapIterator();
|
||||||
for (int i = 0; runnersIterator.hasNext(); i++) {
|
int i = 0;
|
||||||
|
while (runnersIterator.hasNext()) {
|
||||||
runnersIterator.next();
|
runnersIterator.next();
|
||||||
|
|
||||||
assertEquals(runnersIterator.getKey(), this.names[i]);
|
assertEquals(runnersIterator.getKey(), this.names[i]);
|
||||||
assertEquals(runnersIterator.getValue(), this.ages[i]);
|
assertEquals(runnersIterator.getValue(), this.ages[i]);
|
||||||
|
i++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -73,9 +75,11 @@ public class OrderedMapUnitTest {
|
|||||||
// as defined in the constant arrays of names and ages
|
// as defined in the constant arrays of names and ages
|
||||||
|
|
||||||
String name = this.runnersLinkedMap.firstKey();
|
String name = this.runnersLinkedMap.firstKey();
|
||||||
for (int i = 0; name != null; i++) {
|
int i = 0;
|
||||||
|
while (name != null) {
|
||||||
assertEquals(name, this.names[i]);
|
assertEquals(name, this.names[i]);
|
||||||
name = this.runnersLinkedMap.nextKey(name);
|
name = this.runnersLinkedMap.nextKey(name);
|
||||||
|
i++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -85,9 +89,11 @@ public class OrderedMapUnitTest {
|
|||||||
// as defined in the constant arrays of names and ages
|
// as defined in the constant arrays of names and ages
|
||||||
|
|
||||||
String name = this.runnersListOrderedMap.firstKey();
|
String name = this.runnersListOrderedMap.firstKey();
|
||||||
for (int i = 0; name != null; i++) {
|
int i = 0;
|
||||||
|
while (name != null) {
|
||||||
assertEquals(name, this.names[i]);
|
assertEquals(name, this.names[i]);
|
||||||
name = this.runnersListOrderedMap.nextKey(name);
|
name = this.runnersListOrderedMap.nextKey(name);
|
||||||
|
i++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -97,9 +103,11 @@ public class OrderedMapUnitTest {
|
|||||||
// as defined in the constant arrays of names and ages
|
// as defined in the constant arrays of names and ages
|
||||||
|
|
||||||
String name = this.runnersLinkedMap.lastKey();
|
String name = this.runnersLinkedMap.lastKey();
|
||||||
for (int i = RUNNERS_COUNT - 1; name != null; i--) {
|
int i = RUNNERS_COUNT - 1;
|
||||||
|
while (name != null) {
|
||||||
assertEquals(name, this.names[i]);
|
assertEquals(name, this.names[i]);
|
||||||
name = this.runnersLinkedMap.previousKey(name);
|
name = this.runnersLinkedMap.previousKey(name);
|
||||||
|
i--;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -109,9 +117,11 @@ public class OrderedMapUnitTest {
|
|||||||
// as defined in the constant arrays of names and ages
|
// as defined in the constant arrays of names and ages
|
||||||
|
|
||||||
String name = this.runnersListOrderedMap.lastKey();
|
String name = this.runnersListOrderedMap.lastKey();
|
||||||
for (int i = RUNNERS_COUNT - 1; name != null; i--) {
|
int i = RUNNERS_COUNT - 1;
|
||||||
|
while (name != null) {
|
||||||
assertEquals(name, this.names[i]);
|
assertEquals(name, this.names[i]);
|
||||||
name = this.runnersListOrderedMap.previousKey(name);
|
name = this.runnersListOrderedMap.previousKey(name);
|
||||||
|
i--;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user