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>
|
||||
</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>
|
||||
|
||||
</build>
|
||||
|
@ -6,7 +6,7 @@ public class NumbersConsumer implements Runnable {
|
||||
private final BlockingQueue<Integer> queue;
|
||||
private final int poisonPill;
|
||||
|
||||
public NumbersConsumer(BlockingQueue<Integer> queue, int poisonPill) {
|
||||
NumbersConsumer(BlockingQueue<Integer> queue, int poisonPill) {
|
||||
this.queue = queue;
|
||||
this.poisonPill = poisonPill;
|
||||
}
|
||||
|
@ -9,7 +9,7 @@ public class NumbersProducer implements Runnable {
|
||||
private final int poisonPill;
|
||||
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.poisonPill = poisonPill;
|
||||
this.poisonPillPerProducer = poisonPillPerProducer;
|
||||
|
@ -7,7 +7,7 @@ public class BrokenWorker implements Runnable {
|
||||
private final List<String> outputScraper;
|
||||
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.countDownLatch = countDownLatch;
|
||||
}
|
||||
|
@ -10,7 +10,7 @@ public class WaitingWorker implements Runnable {
|
||||
private final CountDownLatch callingThreadBlocker;
|
||||
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.readyThreadCounter = readyThreadCounter;
|
||||
|
@ -7,7 +7,7 @@ public class Worker implements Runnable {
|
||||
private final List<String> outputScraper;
|
||||
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.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 long startTime;
|
||||
|
||||
public DelayObject(String data, long delayInMilliseconds) {
|
||||
DelayObject(String data, long delayInMilliseconds) {
|
||||
this.data = data;
|
||||
this.startTime = System.currentTimeMillis() + delayInMilliseconds;
|
||||
}
|
||||
|
@ -7,9 +7,9 @@ import java.util.concurrent.atomic.AtomicInteger;
|
||||
public class DelayQueueConsumer implements Runnable {
|
||||
private BlockingQueue<DelayObject> queue;
|
||||
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.numberOfElementsToTake = numberOfElementsToTake;
|
||||
}
|
||||
|
@ -9,9 +9,9 @@ public class DelayQueueProducer implements Runnable {
|
||||
private final Integer numberOfElementsToProduce;
|
||||
private final Integer delayOfEachProducedMessageMilliseconds;
|
||||
|
||||
public DelayQueueProducer(BlockingQueue<DelayObject> queue,
|
||||
Integer numberOfElementsToProduce,
|
||||
Integer delayOfEachProducedMessageMilliseconds) {
|
||||
DelayQueueProducer(BlockingQueue<DelayObject> queue,
|
||||
Integer numberOfElementsToProduce,
|
||||
Integer delayOfEachProducedMessageMilliseconds) {
|
||||
this.queue = queue;
|
||||
this.numberOfElementsToProduce = numberOfElementsToProduce;
|
||||
this.delayOfEachProducedMessageMilliseconds = delayOfEachProducedMessageMilliseconds;
|
||||
|
@ -5,7 +5,7 @@ public class Philosopher implements Runnable {
|
||||
private final Object leftFork;
|
||||
private final Object rightFork;
|
||||
|
||||
public Philosopher(Object left, Object right) {
|
||||
Philosopher(Object left, Object right) {
|
||||
this.leftFork = left;
|
||||
this.rightFork = right;
|
||||
}
|
||||
@ -30,7 +30,6 @@ public class Philosopher implements Runnable {
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
@ -7,7 +7,7 @@ public class FactorialSquareCalculator extends RecursiveTask<Integer> {
|
||||
|
||||
final private Integer n;
|
||||
|
||||
public FactorialSquareCalculator(Integer n) {
|
||||
FactorialSquareCalculator(Integer n) {
|
||||
this.n = n;
|
||||
}
|
||||
|
||||
|
@ -3,15 +3,15 @@ package com.baeldung.concurrent.future;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
public class SquareCalculator {
|
||||
class SquareCalculator {
|
||||
|
||||
private final ExecutorService executor;
|
||||
|
||||
public SquareCalculator(ExecutorService executor) {
|
||||
SquareCalculator(ExecutorService executor) {
|
||||
this.executor = executor;
|
||||
}
|
||||
|
||||
public Future<Integer> calculate(Integer input) {
|
||||
Future<Integer> calculate(Integer input) {
|
||||
return executor.submit(() -> {
|
||||
Thread.sleep(1000);
|
||||
return input * input;
|
||||
|
@ -13,71 +13,71 @@ import static java.lang.Thread.sleep;
|
||||
|
||||
public class ReentrantLockWithCondition {
|
||||
|
||||
static Logger logger = LoggerFactory.getLogger(ReentrantLockWithCondition.class);
|
||||
private static Logger LOG = LoggerFactory.getLogger(ReentrantLockWithCondition.class);
|
||||
|
||||
Stack<String> stack = new Stack<>();
|
||||
int CAPACITY = 5;
|
||||
private Stack<String> stack = new Stack<>();
|
||||
private static final int CAPACITY = 5;
|
||||
|
||||
ReentrantLock lock = new ReentrantLock();
|
||||
Condition stackEmptyCondition = lock.newCondition();
|
||||
Condition stackFullCondition = lock.newCondition();
|
||||
private ReentrantLock lock = new ReentrantLock();
|
||||
private Condition stackEmptyCondition = lock.newCondition();
|
||||
private Condition stackFullCondition = lock.newCondition();
|
||||
|
||||
public void pushToStack(String item) throws InterruptedException {
|
||||
try {
|
||||
lock.lock();
|
||||
if (stack.size() == CAPACITY) {
|
||||
logger.info(Thread.currentThread().getName() + " wait on stack full");
|
||||
stackFullCondition.await();
|
||||
}
|
||||
logger.info("Pushing the item " + item);
|
||||
stack.push(item);
|
||||
stackEmptyCondition.signalAll();
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
private void pushToStack(String item) throws InterruptedException {
|
||||
try {
|
||||
lock.lock();
|
||||
if (stack.size() == CAPACITY) {
|
||||
LOG.info(Thread.currentThread().getName() + " wait on stack full");
|
||||
stackFullCondition.await();
|
||||
}
|
||||
LOG.info("Pushing the item " + item);
|
||||
stack.push(item);
|
||||
stackEmptyCondition.signalAll();
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public String popFromStack() throws InterruptedException {
|
||||
try {
|
||||
lock.lock();
|
||||
if (stack.size() == 0) {
|
||||
logger.info(Thread.currentThread().getName() + " wait on stack empty");
|
||||
stackEmptyCondition.await();
|
||||
}
|
||||
return stack.pop();
|
||||
} finally {
|
||||
stackFullCondition.signalAll();
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
private String popFromStack() throws InterruptedException {
|
||||
try {
|
||||
lock.lock();
|
||||
if (stack.size() == 0) {
|
||||
LOG.info(Thread.currentThread().getName() + " wait on stack empty");
|
||||
stackEmptyCondition.await();
|
||||
}
|
||||
return stack.pop();
|
||||
} finally {
|
||||
stackFullCondition.signalAll();
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
final int threadCount = 2;
|
||||
ReentrantLockWithCondition object = new ReentrantLockWithCondition();
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
service.execute(() -> {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
try {
|
||||
object.pushToStack("Item " + i);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
final int threadCount = 2;
|
||||
ReentrantLockWithCondition object = new ReentrantLockWithCondition();
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
service.execute(() -> {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
try {
|
||||
object.pushToStack("Item " + i);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
});
|
||||
|
||||
service.execute(() -> {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
try {
|
||||
logger.info("Item popped " + object.popFromStack());
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
service.execute(() -> {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
try {
|
||||
LOG.info("Item popped " + object.popFromStack());
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
});
|
||||
|
||||
service.shutdown();
|
||||
}
|
||||
service.shutdown();
|
||||
}
|
||||
}
|
||||
|
@ -12,81 +12,77 @@ import static java.lang.Thread.sleep;
|
||||
|
||||
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();
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
||||
try {
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
|
||||
counter++;
|
||||
} catch (Exception exception) {
|
||||
logger.error(" Interrupted Exception ", exception);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
||||
}
|
||||
}
|
||||
lock.lock();
|
||||
LOG.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
||||
try {
|
||||
LOG.info("Thread - " + Thread.currentThread().getName() + " processing");
|
||||
counter++;
|
||||
} catch (Exception exception) {
|
||||
LOG.error(" Interrupted Exception ", exception);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
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");
|
||||
try {
|
||||
boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS);
|
||||
if (isLockAcquired) {
|
||||
try {
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
||||
LOG.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock");
|
||||
try {
|
||||
boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS);
|
||||
if (isLockAcquired) {
|
||||
try {
|
||||
LOG.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
||||
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
|
||||
sleep(1000);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
||||
LOG.info("Thread - " + Thread.currentThread().getName() + " processing");
|
||||
sleep(1000);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
LOG.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
||||
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException exception) {
|
||||
logger.error(" Interrupted Exception ", exception);
|
||||
}
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock");
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException exception) {
|
||||
LOG.error(" Interrupted Exception ", exception);
|
||||
}
|
||||
LOG.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock");
|
||||
}
|
||||
|
||||
public ReentrantLock getLock() {
|
||||
return lock;
|
||||
}
|
||||
public ReentrantLock getLock() {
|
||||
return lock;
|
||||
}
|
||||
|
||||
boolean isLocked() {
|
||||
return lock.isLocked();
|
||||
}
|
||||
boolean isLocked() {
|
||||
return lock.isLocked();
|
||||
}
|
||||
|
||||
boolean hasQueuedThreads() {
|
||||
return lock.hasQueuedThreads();
|
||||
}
|
||||
boolean hasQueuedThreads() {
|
||||
return lock.hasQueuedThreads();
|
||||
}
|
||||
|
||||
int getCounter() {
|
||||
return counter;
|
||||
}
|
||||
int getCounter() {
|
||||
return counter;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
public static void main(String[] args) {
|
||||
|
||||
final int threadCount = 2;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
final int threadCount = 2;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
|
||||
service.execute(() -> {
|
||||
object.perform();
|
||||
});
|
||||
service.execute(() -> {
|
||||
object.performTryLock();
|
||||
});
|
||||
service.execute(object::perform);
|
||||
service.execute(object::performTryLock);
|
||||
|
||||
service.shutdown();
|
||||
service.shutdown();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -12,93 +12,93 @@ import java.util.concurrent.locks.StampedLock;
|
||||
import static java.lang.Thread.sleep;
|
||||
|
||||
public class StampedLockDemo {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
Logger logger = LoggerFactory.getLogger(StampedLockDemo.class);
|
||||
private Map<String, String> map = new HashMap<>();
|
||||
private Logger logger = LoggerFactory.getLogger(StampedLockDemo.class);
|
||||
|
||||
private final StampedLock lock = new StampedLock();
|
||||
private final StampedLock lock = new StampedLock();
|
||||
|
||||
public void put(String key, String value) throws InterruptedException {
|
||||
long stamp = lock.writeLock();
|
||||
public void put(String key, String value) throws InterruptedException {
|
||||
long stamp = lock.writeLock();
|
||||
|
||||
try {
|
||||
logger.info(Thread.currentThread().getName() + " acquired the write lock with stamp " + stamp);
|
||||
map.put(key, value);
|
||||
} finally {
|
||||
lock.unlockWrite(stamp);
|
||||
logger.info(Thread.currentThread().getName() + " unlocked the write lock with stamp " + stamp);
|
||||
}
|
||||
}
|
||||
try {
|
||||
logger.info(Thread.currentThread().getName() + " acquired the write lock with stamp " + stamp);
|
||||
map.put(key, value);
|
||||
} finally {
|
||||
lock.unlockWrite(stamp);
|
||||
logger.info(Thread.currentThread().getName() + " unlocked the write lock with stamp " + stamp);
|
||||
}
|
||||
}
|
||||
|
||||
public String get(String key) throws InterruptedException {
|
||||
long stamp = lock.readLock();
|
||||
logger.info(Thread.currentThread().getName() + " acquired the read lock with stamp " + stamp);
|
||||
try {
|
||||
sleep(5000);
|
||||
return map.get(key);
|
||||
public String get(String key) throws InterruptedException {
|
||||
long stamp = lock.readLock();
|
||||
logger.info(Thread.currentThread().getName() + " acquired the read lock with stamp " + stamp);
|
||||
try {
|
||||
sleep(5000);
|
||||
return map.get(key);
|
||||
|
||||
} finally {
|
||||
lock.unlockRead(stamp);
|
||||
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
|
||||
} finally {
|
||||
lock.unlockRead(stamp);
|
||||
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public String readWithOptimisticLock(String key) throws InterruptedException {
|
||||
long stamp = lock.tryOptimisticRead();
|
||||
String value = map.get(key);
|
||||
private String readWithOptimisticLock(String key) throws InterruptedException {
|
||||
long stamp = lock.tryOptimisticRead();
|
||||
String value = map.get(key);
|
||||
|
||||
if (!lock.validate(stamp)) {
|
||||
stamp = lock.readLock();
|
||||
try {
|
||||
sleep(5000);
|
||||
return map.get(key);
|
||||
if (!lock.validate(stamp)) {
|
||||
stamp = lock.readLock();
|
||||
try {
|
||||
sleep(5000);
|
||||
return map.get(key);
|
||||
|
||||
} finally {
|
||||
lock.unlock(stamp);
|
||||
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
|
||||
} finally {
|
||||
lock.unlock(stamp);
|
||||
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
|
||||
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
final int threadCount = 4;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
StampedLockDemo object = new StampedLockDemo();
|
||||
public static void main(String[] args) {
|
||||
final int threadCount = 4;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
StampedLockDemo object = new StampedLockDemo();
|
||||
|
||||
Runnable writeTask = () -> {
|
||||
Runnable writeTask = () -> {
|
||||
|
||||
try {
|
||||
object.put("key1", "value1");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
};
|
||||
Runnable readTask = () -> {
|
||||
try {
|
||||
object.put("key1", "value1");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
};
|
||||
Runnable readTask = () -> {
|
||||
|
||||
try {
|
||||
object.get("key1");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
};
|
||||
Runnable readOptimisticTask = () -> {
|
||||
try {
|
||||
object.get("key1");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
};
|
||||
Runnable readOptimisticTask = () -> {
|
||||
|
||||
try {
|
||||
object.readWithOptimisticLock("key1");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
};
|
||||
service.submit(writeTask);
|
||||
service.submit(writeTask);
|
||||
service.submit(readTask);
|
||||
service.submit(readOptimisticTask);
|
||||
try {
|
||||
object.readWithOptimisticLock("key1");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
};
|
||||
service.submit(writeTask);
|
||||
service.submit(writeTask);
|
||||
service.submit(readTask);
|
||||
service.submit(readOptimisticTask);
|
||||
|
||||
service.shutdown();
|
||||
service.shutdown();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -15,106 +15,106 @@ import static java.lang.Thread.sleep;
|
||||
|
||||
public class SynchronizedHashMapWithRWLock {
|
||||
|
||||
static Map<String, String> syncHashMap = new HashMap<>();
|
||||
Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class);
|
||||
private static Map<String, String> syncHashMap = new HashMap<>();
|
||||
private Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class);
|
||||
|
||||
private final ReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
private final Lock readLock = lock.readLock();
|
||||
private final Lock writeLock = lock.writeLock();
|
||||
private final ReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
private final Lock readLock = lock.readLock();
|
||||
private final Lock writeLock = lock.writeLock();
|
||||
|
||||
public void put(String key, String value) throws InterruptedException {
|
||||
public void put(String key, String value) throws InterruptedException {
|
||||
|
||||
try {
|
||||
writeLock.lock();
|
||||
logger.info(Thread.currentThread().getName() + " writing");
|
||||
syncHashMap.put(key, value);
|
||||
sleep(1000);
|
||||
} finally {
|
||||
writeLock.unlock();
|
||||
}
|
||||
try {
|
||||
writeLock.lock();
|
||||
logger.info(Thread.currentThread().getName() + " writing");
|
||||
syncHashMap.put(key, value);
|
||||
sleep(1000);
|
||||
} finally {
|
||||
writeLock.unlock();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public String get(String key) {
|
||||
try {
|
||||
readLock.lock();
|
||||
logger.info(Thread.currentThread().getName() + " reading");
|
||||
return syncHashMap.get(key);
|
||||
} finally {
|
||||
readLock.unlock();
|
||||
}
|
||||
}
|
||||
public String get(String key) {
|
||||
try {
|
||||
readLock.lock();
|
||||
logger.info(Thread.currentThread().getName() + " reading");
|
||||
return syncHashMap.get(key);
|
||||
} finally {
|
||||
readLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public String remove(String key) {
|
||||
try {
|
||||
writeLock.lock();
|
||||
return syncHashMap.remove(key);
|
||||
} finally {
|
||||
writeLock.unlock();
|
||||
}
|
||||
}
|
||||
public String remove(String key) {
|
||||
try {
|
||||
writeLock.lock();
|
||||
return syncHashMap.remove(key);
|
||||
} finally {
|
||||
writeLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean containsKey(String key) {
|
||||
try {
|
||||
readLock.lock();
|
||||
return syncHashMap.containsKey(key);
|
||||
} finally {
|
||||
readLock.unlock();
|
||||
}
|
||||
}
|
||||
public boolean containsKey(String key) {
|
||||
try {
|
||||
readLock.lock();
|
||||
return syncHashMap.containsKey(key);
|
||||
} finally {
|
||||
readLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
boolean isReadLockAvailable() {
|
||||
return readLock.tryLock();
|
||||
}
|
||||
boolean isReadLockAvailable() {
|
||||
return readLock.tryLock();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
|
||||
final int threadCount = 3;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
|
||||
final int threadCount = 3;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
|
||||
|
||||
service.execute(new Thread(new Writer(object), "Writer"));
|
||||
service.execute(new Thread(new Reader(object), "Reader1"));
|
||||
service.execute(new Thread(new Reader(object), "Reader2"));
|
||||
service.execute(new Thread(new Writer(object), "Writer"));
|
||||
service.execute(new Thread(new Reader(object), "Reader1"));
|
||||
service.execute(new Thread(new Reader(object), "Reader2"));
|
||||
|
||||
service.shutdown();
|
||||
}
|
||||
service.shutdown();
|
||||
}
|
||||
|
||||
private static class Reader implements Runnable {
|
||||
private static class Reader implements Runnable {
|
||||
|
||||
SynchronizedHashMapWithRWLock object;
|
||||
SynchronizedHashMapWithRWLock object;
|
||||
|
||||
public Reader(SynchronizedHashMapWithRWLock object) {
|
||||
this.object = object;
|
||||
}
|
||||
Reader(SynchronizedHashMapWithRWLock object) {
|
||||
this.object = object;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
object.get("key" + i);
|
||||
}
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
object.get("key" + i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class Writer implements Runnable {
|
||||
private static class Writer implements Runnable {
|
||||
|
||||
SynchronizedHashMapWithRWLock object;
|
||||
SynchronizedHashMapWithRWLock object;
|
||||
|
||||
public Writer(SynchronizedHashMapWithRWLock object) {
|
||||
this.object = object;
|
||||
}
|
||||
public Writer(SynchronizedHashMapWithRWLock object) {
|
||||
this.object = object;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
try {
|
||||
object.put("key" + i, "value" + i);
|
||||
sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
try {
|
||||
object.put("key" + i, "value" + i);
|
||||
sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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;
|
||||
|
||||
public class Event {
|
||||
class Event {
|
||||
private final ZonedDateTime eventTime;
|
||||
private final String content;
|
||||
|
||||
public Event(ZonedDateTime eventTime, String content) {
|
||||
Event(ZonedDateTime eventTime, String content) {
|
||||
this.eventTime = eventTime;
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public ZonedDateTime getEventTime() {
|
||||
ZonedDateTime getEventTime() {
|
||||
return eventTime;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
String getContent() {
|
||||
return content;
|
||||
}
|
||||
}
|
||||
|
@ -5,24 +5,24 @@ import java.util.Comparator;
|
||||
import java.util.concurrent.ConcurrentNavigableMap;
|
||||
import java.util.concurrent.ConcurrentSkipListMap;
|
||||
|
||||
public class EventWindowSort {
|
||||
class EventWindowSort {
|
||||
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());
|
||||
}
|
||||
|
||||
public ConcurrentNavigableMap<ZonedDateTime, String> getEventsFromLastMinute() {
|
||||
ConcurrentNavigableMap<ZonedDateTime, String> getEventsFromLastMinute() {
|
||||
return events.tailMap(ZonedDateTime
|
||||
.now()
|
||||
.minusMinutes(1));
|
||||
.now()
|
||||
.minusMinutes(1));
|
||||
}
|
||||
|
||||
public ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
|
||||
ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
|
||||
return events.headMap(ZonedDateTime
|
||||
.now()
|
||||
.minusMinutes(1));
|
||||
.now()
|
||||
.minusMinutes(1));
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -13,10 +13,10 @@ public class WaitSleepExample {
|
||||
private static final Object LOCK = new Object();
|
||||
|
||||
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
|
||||
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 static int staticCount = 0;
|
||||
|
||||
public void performSynchronisedTask() {
|
||||
void performSynchronisedTask() {
|
||||
synchronized (this) {
|
||||
setCount(getCount() + 1);
|
||||
}
|
||||
}
|
||||
|
||||
public static void performStaticSyncTask() {
|
||||
static void performStaticSyncTask() {
|
||||
synchronized (BaeldungSynchronizedBlocks.class) {
|
||||
setStaticCount(getStaticCount() + 1);
|
||||
}
|
||||
@ -25,11 +25,11 @@ public class BaeldungSynchronizedBlocks {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
public static int getStaticCount() {
|
||||
static int getStaticCount() {
|
||||
return staticCount;
|
||||
}
|
||||
|
||||
public static void setStaticCount(int staticCount) {
|
||||
private static void setStaticCount(int staticCount) {
|
||||
BaeldungSynchronizedBlocks.staticCount = staticCount;
|
||||
}
|
||||
}
|
||||
|
@ -5,17 +5,17 @@ public class BaeldungSynchronizedMethods {
|
||||
private int sum = 0;
|
||||
private int syncSum = 0;
|
||||
|
||||
public static int staticSum = 0;
|
||||
static int staticSum = 0;
|
||||
|
||||
public void calculate() {
|
||||
void calculate() {
|
||||
setSum(getSum() + 1);
|
||||
}
|
||||
|
||||
public synchronized void synchronisedCalculate() {
|
||||
synchronized void synchronisedCalculate() {
|
||||
setSyncSum(getSyncSum() + 1);
|
||||
}
|
||||
|
||||
public static synchronized void syncStaticCalculate() {
|
||||
static synchronized void syncStaticCalculate() {
|
||||
staticSum = staticSum + 1;
|
||||
}
|
||||
|
||||
@ -27,11 +27,11 @@ public class BaeldungSynchronizedMethods {
|
||||
this.sum = sum;
|
||||
}
|
||||
|
||||
public int getSyncSum() {
|
||||
int getSyncSum() {
|
||||
return syncSum;
|
||||
}
|
||||
|
||||
public void setSyncSum(int syncSum) {
|
||||
private void setSyncSum(int syncSum) {
|
||||
this.syncSum = syncSum;
|
||||
}
|
||||
}
|
||||
|
@ -6,40 +6,40 @@ import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
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);
|
||||
}
|
||||
|
||||
public LocalDate getLocalDateUsingParseMethod(String representation) {
|
||||
LocalDate getLocalDateUsingParseMethod(String representation) {
|
||||
return LocalDate.parse(representation);
|
||||
}
|
||||
|
||||
public LocalDate getLocalDateFromClock() {
|
||||
LocalDate getLocalDateFromClock() {
|
||||
LocalDate localDate = LocalDate.now();
|
||||
return localDate;
|
||||
}
|
||||
|
||||
public LocalDate getNextDay(LocalDate localDate) {
|
||||
LocalDate getNextDay(LocalDate localDate) {
|
||||
return localDate.plusDays(1);
|
||||
}
|
||||
|
||||
public LocalDate getPreviousDay(LocalDate localDate) {
|
||||
LocalDate getPreviousDay(LocalDate localDate) {
|
||||
return localDate.minus(1, ChronoUnit.DAYS);
|
||||
}
|
||||
|
||||
public DayOfWeek getDayOfWeek(LocalDate localDate) {
|
||||
DayOfWeek getDayOfWeek(LocalDate localDate) {
|
||||
DayOfWeek day = localDate.getDayOfWeek();
|
||||
return day;
|
||||
}
|
||||
|
||||
public LocalDate getFirstDayOfMonth() {
|
||||
LocalDate getFirstDayOfMonth() {
|
||||
LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
|
||||
return firstDayOfMonth;
|
||||
}
|
||||
|
||||
public LocalDateTime getStartOfDay(LocalDate localDate) {
|
||||
LocalDateTime getStartOfDay(LocalDate localDate) {
|
||||
LocalDateTime startofDay = localDate.atStartOfDay();
|
||||
return startofDay;
|
||||
}
|
||||
|
@ -5,31 +5,27 @@ import java.time.temporal.ChronoUnit;
|
||||
|
||||
public class UseLocalTime {
|
||||
|
||||
public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
|
||||
LocalTime localTime = LocalTime.of(hour, min, seconds);
|
||||
return localTime;
|
||||
LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
|
||||
return LocalTime.of(hour, min, seconds);
|
||||
}
|
||||
|
||||
public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
|
||||
LocalTime localTime = LocalTime.parse(timeRepresentation);
|
||||
return localTime;
|
||||
LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
|
||||
return LocalTime.parse(timeRepresentation);
|
||||
}
|
||||
|
||||
public LocalTime getLocalTimeFromClock() {
|
||||
LocalTime localTime = LocalTime.now();
|
||||
return localTime;
|
||||
private LocalTime getLocalTimeFromClock() {
|
||||
return LocalTime.now();
|
||||
}
|
||||
|
||||
public LocalTime addAnHour(LocalTime localTime) {
|
||||
LocalTime newTime = localTime.plus(1, ChronoUnit.HOURS);
|
||||
return newTime;
|
||||
LocalTime addAnHour(LocalTime localTime) {
|
||||
return localTime.plus(1, ChronoUnit.HOURS);
|
||||
}
|
||||
|
||||
public int getHourFromLocalTime(LocalTime localTime) {
|
||||
int getHourFromLocalTime(LocalTime localTime) {
|
||||
return localTime.getHour();
|
||||
}
|
||||
|
||||
public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) {
|
||||
LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) {
|
||||
return localTime.withMinute(minute);
|
||||
}
|
||||
}
|
||||
|
@ -3,13 +3,13 @@ package com.baeldung.datetime;
|
||||
import java.time.LocalDate;
|
||||
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);
|
||||
}
|
||||
|
||||
public Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) {
|
||||
Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) {
|
||||
return Period.between(localDate1, localDate2);
|
||||
}
|
||||
}
|
||||
|
@ -8,12 +8,10 @@ import java.util.Date;
|
||||
public class UseToInstant {
|
||||
|
||||
public LocalDateTime convertDateToLocalDate(Date date) {
|
||||
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
|
||||
return localDateTime;
|
||||
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
public LocalDateTime convertDateToLocalDate(Calendar calendar) {
|
||||
LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
|
||||
return localDateTime;
|
||||
return LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
@ -4,10 +4,9 @@ import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
public class UseZonedDateTime {
|
||||
class UseZonedDateTime {
|
||||
|
||||
public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
|
||||
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
|
||||
return zonedDateTime;
|
||||
ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
|
||||
return ZonedDateTime.of(localDateTime, zoneId);
|
||||
}
|
||||
}
|
||||
|
@ -13,8 +13,7 @@ public class DirectoryMonitoringExample {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class);
|
||||
|
||||
|
||||
public static final int POLL_INTERVAL = 500;
|
||||
private static final int POLL_INTERVAL = 500;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
FileAlterationObserver observer = new FileAlterationObserver(System.getProperty("user.home"));
|
||||
|
@ -6,12 +6,12 @@ public class Computer {
|
||||
private String color;
|
||||
private Integer healty;
|
||||
|
||||
public Computer(final int age, final String color) {
|
||||
Computer(final int age, final String color) {
|
||||
this.age = age;
|
||||
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.color = color;
|
||||
this.healty = healty;
|
||||
@ -28,7 +28,7 @@ public class Computer {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getColor() {
|
||||
String getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
@ -36,11 +36,11 @@ public class Computer {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
public Integer getHealty() {
|
||||
Integer getHealty() {
|
||||
return healty;
|
||||
}
|
||||
|
||||
public void setHealty(final Integer healty) {
|
||||
void setHealty(final Integer healty) {
|
||||
this.healty = healty;
|
||||
}
|
||||
|
||||
@ -72,10 +72,7 @@ public class Computer {
|
||||
|
||||
final Computer computer = (Computer) o;
|
||||
|
||||
if (age != null ? !age.equals(computer.age) : computer.age != null) {
|
||||
return false;
|
||||
}
|
||||
return color != null ? color.equals(computer.color) : computer.color == null;
|
||||
return (age != null ? age.equals(computer.age) : computer.age == null) && (color != null ? color.equals(computer.color) : computer.color == null);
|
||||
|
||||
}
|
||||
|
||||
|
@ -7,8 +7,8 @@ import java.util.List;
|
||||
|
||||
public class ComputerUtils {
|
||||
|
||||
public static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
|
||||
public static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
|
||||
static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
|
||||
static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
|
||||
|
||||
public static List<Computer> filter(final List<Computer> inventory, final ComputerPredicate p) {
|
||||
|
||||
@ -18,7 +18,7 @@ public class ComputerUtils {
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void repair(final Computer computer) {
|
||||
static void repair(final Computer computer) {
|
||||
if (computer.getHealty() < 50) {
|
||||
computer.setHealty(100);
|
||||
}
|
||||
|
@ -13,7 +13,7 @@ public class MacbookPro extends Computer {
|
||||
super(age, color);
|
||||
}
|
||||
|
||||
public MacbookPro(Integer age, String color, Integer healty) {
|
||||
MacbookPro(Integer age, String color, Integer healty) {
|
||||
super(age, color, healty);
|
||||
}
|
||||
|
||||
|
@ -15,7 +15,7 @@ public class TimingDynamicInvocationHandler implements InvocationHandler {
|
||||
|
||||
private Object target;
|
||||
|
||||
public TimingDynamicInvocationHandler(Object target) {
|
||||
TimingDynamicInvocationHandler(Object target) {
|
||||
this.target = target;
|
||||
|
||||
for(Method method: target.getClass().getDeclaredMethods()) {
|
||||
|
@ -1,10 +1,10 @@
|
||||
package com.baeldung.equalshashcode.entities;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.*;
|
||||
|
||||
public class Square extends Rectangle {
|
||||
|
||||
Color color;
|
||||
private Color color;
|
||||
|
||||
public Square(double width, Color color) {
|
||||
super(width, width);
|
||||
|
@ -8,7 +8,7 @@ import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
|
||||
public class LookupFSJNDI {
|
||||
InitialContext ctx = null;
|
||||
private InitialContext ctx = null;
|
||||
|
||||
public LookupFSJNDI() throws NamingException {
|
||||
super();
|
||||
|
@ -1,58 +1,71 @@
|
||||
package com.baeldung.map.iteration;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class MapIteration {
|
||||
|
||||
public List<String> iterateUsingEntrySet(Map<String, Integer> map) {
|
||||
List<String> mapKeyValueList = new ArrayList<>();
|
||||
public static void main(String[] args) {
|
||||
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()) {
|
||||
mapKeyValueList.add(entry.getKey() + ":" + entry.getValue());
|
||||
System.out.println(entry.getKey() + ":" + entry.getValue());
|
||||
}
|
||||
return mapKeyValueList;
|
||||
}
|
||||
|
||||
public List<String> iterateUsingLambda(Map<String, Integer> map) {
|
||||
List<String> mapKeyValueList = new ArrayList<>();
|
||||
map.forEach((k, v) -> mapKeyValueList.add(k + ":" + v));
|
||||
return mapKeyValueList;
|
||||
public void iterateUsingLambda(Map<String, Integer> map) {
|
||||
map.forEach((k, v) -> System.out.println((k + ":" + v)));
|
||||
}
|
||||
|
||||
public List<String> iterateUsingIteratorAndEntry(Map<String, Integer> map) {
|
||||
ArrayList<String> mapKeyValueList = new ArrayList<>();
|
||||
public void iterateUsingIteratorAndEntry(Map<String, Integer> map) {
|
||||
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
|
||||
|
||||
while (iterator.hasNext()) {
|
||||
Map.Entry<String, Integer> pair = iterator.next();
|
||||
mapKeyValueList.add(pair.getKey() + ":" + pair.getValue());
|
||||
System.out.println(pair.getKey() + ":" + pair.getValue());
|
||||
}
|
||||
|
||||
return mapKeyValueList;
|
||||
}
|
||||
|
||||
public List<String> iterateUsingKeySetAndForeach(Map<String, Integer> map) {
|
||||
List<String> mapKeyValueList = new ArrayList<>();
|
||||
public void iterateUsingKeySetAndForeach(Map<String, Integer> map) {
|
||||
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) {
|
||||
ArrayList<String> mapKeyValueList = new ArrayList<>();
|
||||
map.entrySet().stream().forEach(e -> mapKeyValueList.add(e.getKey() + ":" + e.getValue()));
|
||||
return mapKeyValueList;
|
||||
public void iterateUsingStreamAPI(Map<String, Integer> map) {
|
||||
map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
|
||||
}
|
||||
|
||||
public ArrayList<String> iterateKeys(Map<String, Integer> map) {
|
||||
ArrayList<String> mapKeyList = new ArrayList<>();
|
||||
public void iterateKeys(Map<String, Integer> map) {
|
||||
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>
|
||||
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
<org.springframework.security.version>4.2.3.RELEASE</org.springframework.security.version>
|
||||
</properties>
|
||||
|
||||
<prerequisites>
|
||||
@ -136,6 +137,34 @@
|
||||
<artifactId>standard</artifactId>
|
||||
<version>1.1.2</version>
|
||||
</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>
|
||||
|
||||
<build>
|
||||
@ -378,4 +407,18 @@
|
||||
</properties>
|
||||
</profile>
|
||||
</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>
|
||||
|
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);
|
||||
|
||||
}
|
||||
}
|
@ -1,9 +1,8 @@
|
||||
<?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">
|
||||
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>kotlin</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
@ -13,6 +12,13 @@
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>central</id>
|
||||
<url>http://jcenter.bintray.com</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
@ -31,9 +37,19 @@
|
||||
<version>${kotlin-reflect.version}</version>
|
||||
<scope>test</scope>
|
||||
</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>
|
||||
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
@ -104,10 +120,12 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<kotlin-maven-plugin.version>1.1.1</kotlin-maven-plugin.version>
|
||||
<kotlin-test-junit.version>1.1.1</kotlin-test-junit.version>
|
||||
<kotlin-stdlib.version>1.1.1</kotlin-stdlib.version>
|
||||
<kotlin-reflect.version>1.1.1</kotlin-reflect.version>
|
||||
<kotlin-maven-plugin.version>1.1.2</kotlin-maven-plugin.version>
|
||||
<kotlin-test-junit.version>1.1.2</kotlin-test-junit.version>
|
||||
<kotlin-stdlib.version>1.1.2</kotlin-stdlib.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>
|
||||
|
||||
</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)
|
||||
- [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)
|
||||
- [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.
|
||||
|
@ -1,6 +1,6 @@
|
||||
<?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">
|
||||
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>
|
||||
@ -59,7 +59,7 @@
|
||||
<props>${basedir}/datanucleus.properties</props>
|
||||
<log4jConfiguration>${basedir}/log4j.properties</log4jConfiguration>
|
||||
<verbose>true</verbose>
|
||||
<fork>false</fork> <!-- Solve windows line too long error -->
|
||||
<fork>false</fork> <!-- Solve windows line too long error -->
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
@ -70,32 +70,6 @@
|
||||
</execution>
|
||||
</executions>
|
||||
</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>
|
||||
</build>
|
||||
|
||||
@ -107,15 +81,20 @@
|
||||
<version>${cglib.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-beanutils</groupId>
|
||||
<artifactId>commons-beanutils</artifactId>
|
||||
<version>${commons-beanutils.version}</version>
|
||||
</dependency>
|
||||
<groupId>commons-beanutils</groupId>
|
||||
<artifactId>commons-beanutils</artifactId>
|
||||
<version>${commons-beanutils.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-text</artifactId>
|
||||
<version>${commons-text.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
@ -216,12 +195,6 @@
|
||||
<artifactId>serenity-core</artifactId>
|
||||
<version>${serenity.version}</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.asciidoctor</groupId>
|
||||
<artifactId>asciidoctor-java-integration</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.serenity-bdd</groupId>
|
||||
@ -277,7 +250,7 @@
|
||||
<groupId>org.datanucleus</groupId>
|
||||
<artifactId>datanucleus-maven-plugin</artifactId>
|
||||
<version>5.0.2</version>
|
||||
</dependency>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.datanucleus</groupId>
|
||||
<artifactId>datanucleus-xml</artifactId>
|
||||
@ -329,11 +302,11 @@
|
||||
<version>1.4.195</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>pl.pragmatists</groupId>
|
||||
<artifactId>JUnitParams</artifactId>
|
||||
<version>${jUnitParams.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<groupId>pl.pragmatists</groupId>
|
||||
<artifactId>JUnitParams</artifactId>
|
||||
<version>${jUnitParams.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.quartz-scheduler</groupId>
|
||||
<artifactId>quartz</artifactId>
|
||||
@ -365,17 +338,7 @@
|
||||
<artifactId>netty-all</artifactId>
|
||||
<version>${netty.version}</version>
|
||||
</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>
|
||||
<groupId>org.apache.opennlp</groupId>
|
||||
<artifactId>opennlp-tools</artifactId>
|
||||
@ -392,12 +355,24 @@
|
||||
<artifactId>java-lsh</artifactId>
|
||||
<version>${java-lsh.version}</version>
|
||||
</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>
|
||||
<properties>
|
||||
<multiverse.version>0.7.0</multiverse.version>
|
||||
<cglib.version>3.2.4</cglib.version>
|
||||
<commons-lang.version>3.5</commons-lang.version>
|
||||
<commons-beanutils.version>1.9.3</commons-beanutils.version>
|
||||
<commons-text.version>1.1</commons-text.version>
|
||||
<commons-beanutils.version>1.9.3</commons-beanutils.version>
|
||||
<jasypt.version>1.9.2</jasypt.version>
|
||||
<javatuples.version>1.2</javatuples.version>
|
||||
<javaassist.version>3.21.0-GA</javaassist.version>
|
||||
@ -421,6 +396,7 @@
|
||||
<commons.collections.version>4.1</commons.collections.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<java-lsh.version>0.10</java-lsh.version>
|
||||
<pact.version>3.5.0</pact.version>
|
||||
</properties>
|
||||
|
||||
</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,32 +3,38 @@ package com.baeldung.commons.beanutils;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.beanutils.BeanUtils;
|
||||
import org.apache.commons.beanutils.PropertyUtils;
|
||||
|
||||
public class CourseService {
|
||||
|
||||
public static void setValues(Course course, String name, List<String> codes)
|
||||
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
||||
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
||||
// Setting the simple properties
|
||||
PropertyUtils.setSimpleProperty(course, "name", name);
|
||||
PropertyUtils.setSimpleProperty(course, "codes", codes);
|
||||
}
|
||||
|
||||
public static void setIndexedValue(Course course, int codeIndex, String code)
|
||||
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
||||
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
||||
// Setting the indexed properties
|
||||
PropertyUtils.setIndexedProperty(course, "codes[" + codeIndex + "]", code);
|
||||
}
|
||||
|
||||
public static void setMappedValue(Course course, String enrollId, Student student)
|
||||
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
||||
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
||||
// Setting the mapped properties
|
||||
PropertyUtils.setMappedProperty(course, "enrolledStudent(" + enrollId + ")", student);
|
||||
}
|
||||
|
||||
public static String getNestedValue(Course course, String enrollId, String nestedPropertyName)
|
||||
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
||||
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
||||
return (String) PropertyUtils.getNestedProperty(
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
@ -11,7 +11,7 @@ public class CourseServiceTest {
|
||||
|
||||
@Test
|
||||
public void givenCourse_whenSetValuesUsingPropertyUtil_thenReturnSetValues()
|
||||
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
||||
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
||||
Course course = new Course();
|
||||
String name = "Computer Science";
|
||||
List<String> codes = Arrays.asList("CS", "CS01");
|
||||
@ -35,4 +35,19 @@ public class CourseServiceTest {
|
||||
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;
|
||||
|
||||
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.OrderedMapIterator;
|
||||
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.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class OrderedMapUnitTest {
|
||||
|
||||
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:
|
||||
|
||||
OrderedMapIterator<String, Integer> runnersIterator = this.runnersLinkedMap.mapIterator();
|
||||
for (int i = 0; runnersIterator.hasNext(); i++) {
|
||||
int i = 0;
|
||||
while (runnersIterator.hasNext()) {
|
||||
runnersIterator.next();
|
||||
|
||||
assertEquals(runnersIterator.getKey(), this.names[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:
|
||||
|
||||
OrderedMapIterator<String, Integer> runnersIterator = this.runnersListOrderedMap.mapIterator();
|
||||
for (int i = 0; runnersIterator.hasNext(); i++) {
|
||||
int i = 0;
|
||||
while (runnersIterator.hasNext()) {
|
||||
runnersIterator.next();
|
||||
|
||||
assertEquals(runnersIterator.getKey(), this.names[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
|
||||
|
||||
String name = this.runnersLinkedMap.firstKey();
|
||||
for (int i = 0; name != null; i++) {
|
||||
int i = 0;
|
||||
while (name != null) {
|
||||
assertEquals(name, this.names[i]);
|
||||
name = this.runnersLinkedMap.nextKey(name);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
@ -85,9 +89,11 @@ public class OrderedMapUnitTest {
|
||||
// as defined in the constant arrays of names and ages
|
||||
|
||||
String name = this.runnersListOrderedMap.firstKey();
|
||||
for (int i = 0; name != null; i++) {
|
||||
int i = 0;
|
||||
while (name != null) {
|
||||
assertEquals(name, this.names[i]);
|
||||
name = this.runnersListOrderedMap.nextKey(name);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
@ -97,9 +103,11 @@ public class OrderedMapUnitTest {
|
||||
// as defined in the constant arrays of names and ages
|
||||
|
||||
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]);
|
||||
name = this.runnersLinkedMap.previousKey(name);
|
||||
i--;
|
||||
}
|
||||
}
|
||||
|
||||
@ -109,9 +117,11 @@ public class OrderedMapUnitTest {
|
||||
// as defined in the constant arrays of names and ages
|
||||
|
||||
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]);
|
||||
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