This commit is contained in:
Ahmed Tawila 2017-07-08 14:31:38 +02:00
commit 32d4dfa8f4
319 changed files with 7100 additions and 2322 deletions

8
.gitignore vendored
View File

@ -33,3 +33,11 @@ spring-openid/src/main/resources/application.properties
spring-security-openid/src/main/resources/application.properties
spring-all/*.log
*.jar
SpringDataInjectionDemo/.mvn/wrapper/maven-wrapper.properties
spring-call-getters-using-reflection/.mvn/wrapper/maven-wrapper.properties
spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties

View File

@ -0,0 +1,14 @@
package com.baeldung.algorithms.minimax;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class GameOfBones {
static List<Integer> getPossibleStates(int noOfBonesInHeap) {
return IntStream.rangeClosed(1, 3).boxed()
.map(i -> noOfBonesInHeap - i)
.filter(newHeapCount -> newHeapCount >= 0)
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.algorithms.minimax;
import java.util.Comparator;
import java.util.List;
import java.util.NoSuchElementException;
public class MiniMax {
private Tree tree;
public Tree getTree() {
return tree;
}
public void constructTree(int noOfBones) {
tree = new Tree();
Node root = new Node(noOfBones, true);
tree.setRoot(root);
constructTree(root);
}
private void constructTree(Node node) {
List<Integer> listofPossibleHeaps = GameOfBones.getPossibleStates(node.getNoOfBones());
boolean isMaxPlayer = !node.isMaxPlayer();
listofPossibleHeaps.forEach(n -> {
Node newNode = new Node(n, isMaxPlayer);
node.addChild(newNode);
if (newNode.getNoOfBones() > 0) {
constructTree(newNode);
}
});
}
public boolean checkWin() {
Node root = tree.getRoot();
checkWin(root);
return root.getScore() == 1;
}
private void checkWin(Node node) {
List<Node> children = node.getChildren();
boolean isMaxPlayer = node.isMaxPlayer();
children.forEach(child -> {
if (child.getNoOfBones() == 0) {
child.setScore(isMaxPlayer ? 1 : -1);
} else {
checkWin(child);
}
});
Node bestChild = findBestChild(isMaxPlayer, children);
node.setScore(bestChild.getScore());
}
private Node findBestChild(boolean isMaxPlayer, List<Node> children) {
Comparator<Node> byScoreComparator = Comparator.comparing(Node::getScore);
return children.stream()
.max(isMaxPlayer ? byScoreComparator : byScoreComparator.reversed())
.orElseThrow(NoSuchElementException::new);
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.algorithms.minimax;
import java.util.ArrayList;
import java.util.List;
public class Node {
private int noOfBones;
private boolean isMaxPlayer;
private int score;
private List<Node> children;
public Node(int noOfBones, boolean isMaxPlayer) {
this.noOfBones = noOfBones;
this.isMaxPlayer = isMaxPlayer;
children = new ArrayList<>();
}
int getNoOfBones() {
return noOfBones;
}
boolean isMaxPlayer() {
return isMaxPlayer;
}
int getScore() {
return score;
}
void setScore(int score) {
this.score = score;
}
List<Node> getChildren() {
return children;
}
void addChild(Node newNode) {
children.add(newNode);
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.algorithms.minimax;
public class Tree {
private Node root;
Tree() {
}
Node getRoot() {
return root;
}
void setRoot(Node root) {
this.root = root;
}
}

View File

@ -0,0 +1,92 @@
package algorithms;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.algorithms.mcts.montecarlo.MonteCarloTreeSearch;
import com.baeldung.algorithms.mcts.montecarlo.State;
import com.baeldung.algorithms.mcts.montecarlo.UCT;
import com.baeldung.algorithms.mcts.tictactoe.Board;
import com.baeldung.algorithms.mcts.tictactoe.Position;
import com.baeldung.algorithms.mcts.tree.Tree;
public class MCTSTest {
Tree gameTree;
MonteCarloTreeSearch mcts;
@Before
public void initGameTree() {
gameTree = new Tree();
mcts = new MonteCarloTreeSearch();
}
@Test
public void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() {
double uctValue = 15.79;
assertEquals(UCT.uctValue(600, 300, 20), uctValue, 0.01);
}
@Test
public void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() {
State initState = gameTree.getRoot().getState();
List<State> possibleStates = initState.getAllPossibleStates();
assertTrue(possibleStates.size() > 0);
}
@Test
public void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() {
Board board = new Board();
int initAvailablePositions = board.getEmptyPositions().size();
board.performMove(Board.P1, new Position(1, 1));
int availablePositions = board.getEmptyPositions().size();
assertTrue(initAvailablePositions > availablePositions);
}
@Test
public void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() {
Board board = new Board();
int player = Board.P1;
int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
for (int i = 0; i < totalMoves; i++) {
board = mcts.findNextMove(board, player);
if (board.checkStatus() != -1) {
break;
}
player = 3 - player;
}
int winStatus = board.checkStatus();
assertEquals(winStatus, Board.DRAW);
}
@Test
public void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() {
Board board = new Board();
MonteCarloTreeSearch mcts1 = new MonteCarloTreeSearch();
mcts1.setLevel(1);
MonteCarloTreeSearch mcts3 = new MonteCarloTreeSearch();
mcts3.setLevel(3);
int player = Board.P1;
int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
for (int i = 0; i < totalMoves; i++) {
if (player == Board.P1)
board = mcts3.findNextMove(board, player);
else
board = mcts1.findNextMove(board, player);
if (board.checkStatus() != -1) {
break;
}
player = 3 - player;
}
int winStatus = board.checkStatus();
assertTrue(winStatus == Board.DRAW || winStatus == Board.P1);
}
}

View File

@ -0,0 +1,36 @@
package algorithms.minimax;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import com.baeldung.algorithms.minimax.MiniMax;
import com.baeldung.algorithms.minimax.Tree;
public class MinimaxTest {
private Tree gameTree;
private MiniMax miniMax;
@Before
public void initMiniMaxUtility() {
miniMax = new MiniMax();
}
@Test
public void givenMiniMax_whenConstructTree_thenNotNullTree() {
assertNull(gameTree);
miniMax.constructTree(6);
gameTree = miniMax.getTree();
assertNotNull(gameTree);
}
@Test
public void givenMiniMax_whenCheckWin_thenComputeOptimal() {
miniMax.constructTree(6);
boolean result = miniMax.checkWin();
assertTrue(result);
miniMax.constructTree(8);
result = miniMax.checkWin();
assertFalse(result);
}
}

15
camel-api/README.md Normal file
View 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
View 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>

View 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));
}
}
}

View File

@ -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);
}
}

View 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;
}
}

View 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

View 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

View 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>

View File

@ -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>

View File

@ -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;
}

View File

@ -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;

View File

@ -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;
}

View File

@ -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;

View File

@ -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;
}

View File

@ -7,9 +7,6 @@ import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/**
* Created by cv on 24/6/17.
*/
public class CyclicBarrierDemo {
private CyclicBarrier cyclicBarrier;
@ -19,7 +16,7 @@ public class CyclicBarrierDemo {
private int NUM_WORKERS;
public void runSimulation(int numWorkers, int numberOfPartialResults) {
private void runSimulation(int numWorkers, int numberOfPartialResults) {
NUM_PARTIAL_RESULTS = numberOfPartialResults;
NUM_WORKERS = numWorkers;
@ -49,9 +46,7 @@ public class CyclicBarrierDemo {
try {
System.out.println(thisThreadName + " waiting for others to reach barrier.");
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}

View File

@ -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;
}

View File

@ -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;
}

View File

@ -9,7 +9,7 @@ public class DelayQueueProducer implements Runnable {
private final Integer numberOfElementsToProduce;
private final Integer delayOfEachProducedMessageMilliseconds;
public DelayQueueProducer(BlockingQueue<DelayObject> queue,
DelayQueueProducer(BlockingQueue<DelayObject> queue,
Integer numberOfElementsToProduce,
Integer delayOfEachProducedMessageMilliseconds) {
this.queue = queue;

View File

@ -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;
}
}
}

View File

@ -7,7 +7,7 @@ public class FactorialSquareCalculator extends RecursiveTask<Integer> {
final private Integer n;
public FactorialSquareCalculator(Integer n) {
FactorialSquareCalculator(Integer n) {
this.n = n;
}

View File

@ -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;

View File

@ -13,23 +13,23 @@ 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 {
private void pushToStack(String item) throws InterruptedException {
try {
lock.lock();
if (stack.size() == CAPACITY) {
logger.info(Thread.currentThread().getName() + " wait on stack full");
LOG.info(Thread.currentThread().getName() + " wait on stack full");
stackFullCondition.await();
}
logger.info("Pushing the item " + item);
LOG.info("Pushing the item " + item);
stack.push(item);
stackEmptyCondition.signalAll();
} finally {
@ -38,11 +38,11 @@ public class ReentrantLockWithCondition {
}
public String popFromStack() throws InterruptedException {
private String popFromStack() throws InterruptedException {
try {
lock.lock();
if (stack.size() == 0) {
logger.info(Thread.currentThread().getName() + " wait on stack empty");
LOG.info(Thread.currentThread().getName() + " wait on stack empty");
stackEmptyCondition.await();
}
return stack.pop();
@ -70,7 +70,7 @@ public class ReentrantLockWithCondition {
service.execute(() -> {
for (int i = 0; i < 10; i++) {
try {
logger.info("Item popped " + object.popFromStack());
LOG.info("Item popped " + object.popFromStack());
} catch (InterruptedException e) {
e.printStackTrace();
}

View File

@ -12,48 +12,48 @@ 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");
LOG.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
try {
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
LOG.info("Thread - " + Thread.currentThread().getName() + " processing");
counter++;
} catch (Exception exception) {
logger.error(" Interrupted Exception ", exception);
LOG.error(" Interrupted Exception ", exception);
} finally {
lock.unlock();
logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
LOG.info("Thread - " + Thread.currentThread().getName() + " released the lock");
}
}
public void performTryLock() {
private void performTryLock() {
logger.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock");
LOG.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock");
try {
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() + " acquired the lock");
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
LOG.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() + " released the lock");
}
}
} catch (InterruptedException exception) {
logger.error(" Interrupted Exception ", exception);
LOG.error(" Interrupted Exception ", exception);
}
logger.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock");
LOG.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock");
}
public ReentrantLock getLock() {
@ -78,12 +78,8 @@ public class SharedObjectWithLock {
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();

View File

@ -12,8 +12,8 @@ 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();
@ -44,7 +44,7 @@ public class StampedLockDemo {
}
public String readWithOptimisticLock(String key) throws InterruptedException {
private String readWithOptimisticLock(String key) throws InterruptedException {
long stamp = lock.tryOptimisticRead();
String value = map.get(key);

View File

@ -15,8 +15,8 @@ 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();
@ -84,7 +84,7 @@ public class SynchronizedHashMapWithRWLock {
SynchronizedHashMapWithRWLock object;
public Reader(SynchronizedHashMapWithRWLock object) {
Reader(SynchronizedHashMapWithRWLock object) {
this.object = object;
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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;
}
}

View File

@ -5,21 +5,21 @@ 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()));
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));
}
public ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
return events.headMap(ZonedDateTime
.now()
.minusMinutes(1));

View File

@ -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");

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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());
}
}

View File

@ -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);
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.deserialization;
import java.io.Serializable;
public class AppleProduct implements Serializable {
private static final long serialVersionUID = 1234567L; // user-defined (i.e. not default or generated)
// private static final long serialVersionUID = 7654321L; // user-defined (i.e. not default or generated)
public String headphonePort;
public String thunderboltPort;
public String lighteningPort;
public String getHeadphonePort() {
return headphonePort;
}
public String getThunderboltPort() {
return thunderboltPort;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.deserialization;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Base64;
public class DeserializationUtility {
public static void main(String[] args) throws ClassNotFoundException, IOException {
String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
System.out.println("Deserializing AppleProduct...");
AppleProduct deserializedObj = (AppleProduct) deSerializeObjectFromString(serializedObj);
System.out.println("Headphone port of AppleProduct:" + deserializedObj.getHeadphonePort());
System.out.println("Thunderbolt port of AppleProduct:" + deserializedObj.getThunderboltPort());
}
public static Object deSerializeObjectFromString(String s) throws IOException, ClassNotFoundException {
byte[] data = Base64.getDecoder().decode(s);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
Object o = ois.readObject();
ois.close();
return o;
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.deserialization;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Base64;
public class SerializationUtility {
public static void main(String[] args) throws ClassNotFoundException, IOException {
AppleProduct macBook = new AppleProduct();
macBook.headphonePort = "headphonePort2020";
macBook.thunderboltPort = "thunderboltPort2020";
String serializedObj = serializeObjectToString(macBook);
System.out.println("Serialized AppleProduct object to string:");
System.out.println(serializedObj);
}
public static String serializeObjectToString(Serializable o) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
return Base64.getEncoder().encodeToString(baos.toByteArray());
}
}

View File

@ -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"));

View File

@ -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);
}

View File

@ -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);
}

View File

@ -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);
}

View File

@ -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()) {

View File

@ -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);

View File

@ -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();

View File

@ -0,0 +1,91 @@
package com.baeldung.javanetworking.uriurl;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class URIDemo {
private final Logger logger = LoggerFactory.getLogger(URIDemo.class);
String URISTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
// parsed locator
String URISCHEME = "https";
String URISCHEMESPECIFIC;
String URIHOST = "wordpress.org";
String URIAUTHORITY = "wordpress.org:443";
String URIPATH = "/support/topic/page-jumps-within-wordpress/";
int URIPORT = 443;
String URIQUERY = "replies=3";
String URIFRAGMENT = "post-2278484";
String URIUSERINFO;
String URICOMPOUND = URISCHEME + "://" + URIHOST + ":" + URIPORT + URIPATH + "?" + URIQUERY + "#" + URIFRAGMENT;
URI uri;
URL url;
BufferedReader in = null;
String URIContent = "";
private String getParsedPieces(URI uri) {
logger.info("*** List of parsed pieces ***");
URISCHEME = uri.getScheme();
logger.info("URISCHEME: " + URISCHEME);
URISCHEMESPECIFIC = uri.getSchemeSpecificPart();
logger.info("URISCHEMESPECIFIC: " + URISCHEMESPECIFIC);
URIHOST = uri.getHost();
URIAUTHORITY = uri.getAuthority();
logger.info("URIAUTHORITY: " + URIAUTHORITY);
logger.info("URIHOST: " + URIHOST);
URIPATH = uri.getPath();
logger.info("URIPATH: " + URIPATH);
URIPORT = uri.getPort();
logger.info("URIPORT: " + URIPORT);
URIQUERY = uri.getQuery();
logger.info("URIQUERY: " + URIQUERY);
URIFRAGMENT = uri.getFragment();
logger.info("URIFRAGMENT: " + URIFRAGMENT);
try {
url = uri.toURL();
} catch (MalformedURLException e) {
logger.info("MalformedURLException thrown: " + e.getMessage());
e.printStackTrace();
} catch (IllegalArgumentException e) {
logger.info("IllegalArgumentException thrown: " + e.getMessage());
e.printStackTrace();
}
return url.toString();
}
public String testURIAsNew(String URIString) {
// creating URI object
try {
uri = new URI(URIString);
} catch (URISyntaxException e) {
logger.info("URISyntaxException thrown: " + e.getMessage());
e.printStackTrace();
throw new IllegalArgumentException();
}
return getParsedPieces(uri);
}
public String testURIAsCreate(String URIString) {
// creating URI object
uri = URI.create(URIString);
return getParsedPieces(uri);
}
public static void main(String[] args) throws Exception {
URIDemo demo = new URIDemo();
String contentCreate = demo.testURIAsCreate(demo.URICOMPOUND);
demo.logger.info(contentCreate);
String contentNew = demo.testURIAsNew(demo.URICOMPOUND);
demo.logger.info(contentNew);
}
}

View File

@ -1,9 +1,10 @@
package com.baeldung.javanetworking.url;
package com.baeldung.javanetworking.uriurl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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();
}
}

View File

@ -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);
}
}
}

View File

@ -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;
}
}

View File

@ -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);
}
}

View 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;
}
}

View File

@ -9,6 +9,8 @@ import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertTrue;
public class ArrayCopyUtilUnitTest {
private static Employee[] employees;
private static final int MAX = 2;
@ -46,10 +48,10 @@ public class ArrayCopyUtilUnitTest {
System.arraycopy(array, 2, copiedArray, 0, 3);
Assert.assertTrue(3 == copiedArray.length);
Assert.assertTrue(copiedArray[0] == array[2]);
Assert.assertTrue(copiedArray[1] == array[3]);
Assert.assertTrue(copiedArray[2] == array[4]);
assertTrue(3 == copiedArray.length);
assertTrue(copiedArray[0] == array[2]);
assertTrue(copiedArray[1] == array[3]);
assertTrue(copiedArray[2] == array[4]);
}
@Test
@ -58,10 +60,10 @@ public class ArrayCopyUtilUnitTest {
int[] copiedArray = Arrays.copyOfRange(array, 1, 4);
Assert.assertTrue(3 == copiedArray.length);
Assert.assertTrue(copiedArray[0] == array[1]);
Assert.assertTrue(copiedArray[1] == array[2]);
Assert.assertTrue(copiedArray[2] == array[3]);
assertTrue(3 == copiedArray.length);
assertTrue(copiedArray[0] == array[1]);
assertTrue(copiedArray[1] == array[2]);
assertTrue(copiedArray[2] == array[3]);
}
@Test
@ -73,9 +75,9 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, array);
array[0] = 9;
Assert.assertTrue(copiedArray[0] != array[0]);
assertTrue(copiedArray[0] != array[0]);
copiedArray[1] = 12;
Assert.assertTrue(copiedArray[1] != array[1]);
assertTrue(copiedArray[1] != array[1]);
}
@Test
@ -85,7 +87,7 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element caused change in the copied array
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
@ -96,9 +98,9 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, array);
array[0] = 9;
Assert.assertTrue(copiedArray[0] != array[0]);
assertTrue(copiedArray[0] != array[0]);
copiedArray[1] = 12;
Assert.assertTrue(copiedArray[1] != array[1]);
assertTrue(copiedArray[1] != array[1]);
}
@Test
@ -108,7 +110,7 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, employees);;
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element changed the copied array
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
@ -138,7 +140,7 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element didn't change in the copied array
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test

View File

@ -24,7 +24,7 @@ public class CompletableFutureLongRunningUnitTest {
assertEquals("Hello", result);
}
public Future<String> calculateAsync() throws InterruptedException {
private Future<String> calculateAsync() throws InterruptedException {
CompletableFuture<String> completableFuture = new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> {
@ -44,7 +44,7 @@ public class CompletableFutureLongRunningUnitTest {
assertEquals("Hello", result);
}
public Future<String> calculateAsyncWithCancellation() throws InterruptedException {
private Future<String> calculateAsyncWithCancellation() throws InterruptedException {
CompletableFuture<String> completableFuture = new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> {

View File

@ -4,7 +4,11 @@ import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.util.concurrent.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static junit.framework.TestCase.assertEquals;

View File

@ -1,10 +1,10 @@
package com.baeldung.concurrent.future;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import java.util.concurrent.ForkJoinPool;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class FactorialSquareCalculatorUnitTest {

View File

@ -8,7 +8,12 @@ import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.*;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

View File

@ -1,6 +1,5 @@
package com.baeldung.concurrent.locks;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.junit.Test;
import java.util.concurrent.ExecutorService;

View File

@ -42,7 +42,7 @@ public class PriorityBlockingQueueIntegrationTest {
try {
Integer poll = queue.take();
LOG.debug("Polled: " + poll);
} catch (InterruptedException e) {
} catch (InterruptedException ignored) {
}
}
});

View File

@ -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());
}
}

View File

@ -1,13 +1,13 @@
package com.baeldung.concurrent.synchronize;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class BaeldungSychronizedBlockTest {

View File

@ -1,14 +1,14 @@
package com.baeldung.concurrent.synchronize;
import static org.junit.Assert.assertEquals;
import org.junit.Ignore;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class BaeldungSynchronizeMethodsTest {

View File

@ -7,13 +7,15 @@ import java.time.Month;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class UseLocalDateTimeUnitTest {
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
@Test
public void givenString_whenUsingParse_thenLocalDateTime() {
Assert.assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
Assert.assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
}
}

View File

@ -7,48 +7,50 @@ import java.time.LocalDateTime;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class UseLocalDateUnitTest {
UseLocalDate useLocalDate = new UseLocalDate();
@Test
public void givenValues_whenUsingFactoryOf_thenLocalDate() {
Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString());
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString());
}
@Test
public void givenString_whenUsingParse_thenLocalDate() {
Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
}
@Test
public void whenUsingClock_thenLocalDate() {
Assert.assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock());
assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock());
}
@Test
public void givenDate_whenUsingPlus_thenNextDay() {
Assert.assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
}
@Test
public void givenDate_whenUsingMinus_thenPreviousDay() {
Assert.assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
}
@Test
public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek() {
Assert.assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
}
@Test
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() {
Assert.assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth());
assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth());
}
@Test
public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight() {
Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
}
}

View File

@ -0,0 +1,67 @@
package com.baeldung.deserialization;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.InvalidClassException;
import org.junit.Ignore;
import org.junit.Test;
public class DeserializationUnitTest {
private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
private static long userDefinedSerialVersionUID = 1234567L;
/**
* Tests the deserialization of the original "AppleProduct" (no exceptions are thrown)
* @throws ClassNotFoundException
* @throws IOException
*/
@Test
public void testDeserializeObj_compatible() throws IOException, ClassNotFoundException {
assertEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
AppleProduct macBook = new AppleProduct();
macBook.headphonePort = "headphonePort2020";
macBook.thunderboltPort = "thunderboltPort2020";
// serializes the "AppleProduct" object
String serializedProduct = SerializationUtility.serializeObjectToString(macBook);
// deserializes the "AppleProduct" object
AppleProduct deserializedProduct = (AppleProduct) DeserializationUtility.deSerializeObjectFromString(serializedProduct);
assertTrue(deserializedProduct.headphonePort.equalsIgnoreCase(macBook.headphonePort));
assertTrue(deserializedProduct.thunderboltPort.equalsIgnoreCase(macBook.thunderboltPort));
}
/**
* Tests the deserialization of the modified (non-compatible) "AppleProduct".
* The test should result in an InvalidClassException being thrown.
*
* Note: to run this test:
* 1. Modify the value of the serialVersionUID identifier in AppleProduct.java
* 2. Remove the @Ignore annotation
* 3. Run the test individually (do not run the entire set of tests)
* 4. Revert the changes made in 1 & 2 (so that you're able to re-run the tests successfully)
*
* @throws ClassNotFoundException
* @throws IOException
*/
@Ignore
@Test(expected = InvalidClassException.class)
public void testDeserializeObj_incompatible() throws ClassNotFoundException, IOException {
assertNotEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
// attempts to deserialize the "AppleProduct" object
DeserializationUtility.deSerializeObjectFromString(serializedObj);
}
}

View File

@ -83,7 +83,7 @@ public class ComputerUtilsUnitTest {
final TriFunction<Integer, String, Integer, MacbookPro> integerStringIntegerObjectTriFunction = MacbookPro::new;
final MacbookPro macbookPro = integerStringIntegerObjectTriFunction.apply(2010, "black", 100);
Double initialValue = new Double(999.99);
Double initialValue = 999.99;
final Double actualValue = macbookPro.calculateValue(initialValue);
Assert.assertEquals(766.659, actualValue, 0.0);
}

View File

@ -6,7 +6,12 @@ import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import java.io.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
@ -14,6 +19,10 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
public class FileOperationsManualTest {
@Test
@ -25,7 +34,7 @@ public class FileOperationsManualTest {
InputStream inputStream = new FileInputStream(file);
String data = readFromInputStream(inputStream);
Assert.assertEquals(expectedData, data.trim());
assertEquals(expectedData, data.trim());
}
@Test
@ -36,7 +45,7 @@ public class FileOperationsManualTest {
InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
String data = readFromInputStream(inputStream);
Assert.assertEquals(expectedData, data.trim());
assertEquals(expectedData, data.trim());
}
@Test
@ -47,7 +56,7 @@ public class FileOperationsManualTest {
InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
String data = readFromInputStream(inputStream);
Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
assertThat(data.trim(), CoreMatchers.containsString(expectedData));
}
@Test
@ -61,7 +70,7 @@ public class FileOperationsManualTest {
InputStream inputStream = urlConnection.getInputStream();
String data = readFromInputStream(inputStream);
Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
assertThat(data.trim(), CoreMatchers.containsString(expectedData));
}
@Test
@ -72,7 +81,7 @@ public class FileOperationsManualTest {
File file = new File(classLoader.getResource("fileTest.txt").getFile());
String data = FileUtils.readFileToString(file);
Assert.assertEquals(expectedData, data.trim());
assertEquals(expectedData, data.trim());
}
@Test
@ -84,7 +93,7 @@ public class FileOperationsManualTest {
byte[] fileBytes = Files.readAllBytes(path);
String data = new String(fileBytes);
Assert.assertEquals(expectedData, data.trim());
assertEquals(expectedData, data.trim());
}
@Test
@ -98,7 +107,7 @@ public class FileOperationsManualTest {
lines.forEach(line -> data.append(line).append("\n"));
lines.close();
Assert.assertEquals(expectedData, data.toString().trim());
assertEquals(expectedData, data.toString().trim());
}
private String readFromInputStream(InputStream inputStream) throws IOException {

View File

@ -1,15 +1,13 @@
package com.baeldung.filesystem.jndi.test;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import com.baeldung.filesystem.jndi.LookupFSJNDI;
import org.junit.Test;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.io.File;
import org.junit.Test;
import com.baeldung.filesystem.jndi.LookupFSJNDI;
import static org.junit.Assert.assertNotNull;
public class LookupFSJNDIIntegrationTest {
LookupFSJNDI fsjndi;

View File

@ -25,7 +25,7 @@ public class FunctionalInterfaceUnitTest {
@Test
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
Map<String, Integer> nameMap = new HashMap<>();
Integer value = nameMap.computeIfAbsent("John", s -> s.length());
Integer value = nameMap.computeIfAbsent("John", String::length);
assertEquals(new Integer(4), nameMap.get("John"));
assertEquals(new Integer(4), value);

View File

@ -2,7 +2,7 @@ package com.baeldung.hashing;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
public class SHA256HashingUnitTest {

View File

@ -2,7 +2,6 @@ package com.baeldung.http;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
@ -17,6 +16,9 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class HttpRequestLiveTest {
@Test
@ -39,7 +41,7 @@ public class HttpRequestLiveTest {
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
@ -67,7 +69,7 @@ public class HttpRequestLiveTest {
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}

View File

@ -0,0 +1,65 @@
package com.baeldung.javanetworking.uriurl.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.javanetworking.uriurl.URLDemo;
@FixMethodOrder
public class URIDemoTest {
private final Logger log = LoggerFactory.getLogger(URIDemoTest.class);
String URISTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
// parsed locator
static String URISCHEME = "https";
String URISCHEMESPECIFIC;
static String URIHOST = "wordpress.org";
static String URIAUTHORITY = "wordpress.org:443";
static String URIPATH = "/support/topic/page-jumps-within-wordpress/";
int URIPORT = 443;
static int URIDEFAULTPORT = 443;
static String URIQUERY = "replies=3";
static String URIFRAGMENT = "post-2278484";
static String URICOMPOUND = URISCHEME + "://" + URIHOST + ":" + URIDEFAULTPORT + URIPATH + "?" + URIQUERY + "#" + URIFRAGMENT;
static URI uri;
URL url;
BufferedReader in = null;
String URIContent = "";
@BeforeClass
public static void givenEmplyURL_whenInitializeURL_thenSuccess() throws URISyntaxException {
uri = new URI(URICOMPOUND);
}
// check parsed URL
@Test
public void givenURI_whenURIIsParsed_thenSuccess() {
assertNotNull("URI is null", uri);
assertEquals("URI string is not equal", uri.toString(), URISTRING);
assertEquals("Scheme is not equal", uri.getScheme(), URISCHEME);
assertEquals("Authority is not equal", uri.getAuthority(), URIAUTHORITY);
assertEquals("Host string is not equal", uri.getHost(), URIHOST);
assertEquals("Path string is not equal", uri.getPath(), URIPATH);
assertEquals("Port number is not equal", uri.getPort(), URIPORT);
assertEquals("Query string is not equal", uri.getQuery(), URIQUERY);
assertEquals("Fragment string is not equal", uri.getFragment(), URIFRAGMENT);
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.javanetworking.url.test;
package com.baeldung.javanetworking.uriurl.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@ -18,11 +18,11 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.javanetworking.url.URLDemo;
import com.baeldung.javanetworking.uriurl.URLDemo;
@FixMethodOrder
public class URLDemoTest {
private final Logger log = LoggerFactory.getLogger(URLDemo.class);
private final Logger log = LoggerFactory.getLogger(URLDemoTest.class);
static String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
// parsed locator
static String URLPROTOCOL = "https";

View File

@ -14,7 +14,7 @@ import org.hamcrest.collection.IsIterableContainingInOrder;
import org.junit.Test;
public class FlattenNestedListUnitTest {
List<List<String>> lol = asList(asList("one:one"), asList("two:one", "two:two", "two:three"), asList("three:one", "three:two", "three:three", "three:four"));
private List<List<String>> lol = asList(asList("one:one"), asList("two:one", "two:two", "two:three"), asList("three:one", "three:two", "three:three", "three:four"));
@Test
public void givenNestedList_thenFlattenImperatively() {
@ -36,13 +36,13 @@ public class FlattenNestedListUnitTest {
assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four"));
}
public <T> List<T> flattenListOfListsImperatively(List<List<T>> list) {
private <T> List<T> flattenListOfListsImperatively(List<List<T>> list) {
List<T> ls = new ArrayList<>();
list.forEach(ls::addAll);
return ls;
}
public <T> List<T> flattenListOfListsStream(List<List<T>> list) {
private <T> List<T> flattenListOfListsStream(List<List<T>> list) {
return list.stream().flatMap(Collection::stream).collect(Collectors.toList());
}
}

View File

@ -1,18 +1,19 @@
package com.baeldung.list.listoflist;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class ListOfListsUnitTest {
private List<ArrayList<? extends Stationery>> listOfLists = new ArrayList<ArrayList<? extends Stationery>>();
private ArrayList<Pen> penList = new ArrayList<>();
private ArrayList<Pencil> pencilList = new ArrayList<>();
private ArrayList<Rubber> rubberList = new ArrayList<>();
private List<List<? extends Stationery>> listOfLists = new ArrayList<>();
private List<Pen> penList = new ArrayList<>();
private List<Pencil> pencilList = new ArrayList<>();
private List<Rubber> rubberList = new ArrayList<>();
@SuppressWarnings("unchecked")
@Before

View File

@ -61,7 +61,7 @@ public class MappedByteBufferUnitTest {
}
public Path getFileURIFromResources(String fileName) throws Exception {
private Path getFileURIFromResources(String fileName) throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
return Paths.get(classLoader.getResource(fileName).getPath());
}

View File

@ -0,0 +1,25 @@
package com.baeldung.maths;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.math.RoundingMode;
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);
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.maths;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigInteger;
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);
}
}

View File

@ -5,6 +5,9 @@ import org.decimal4j.util.DoubleRounder;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class RoundTest {
private double value = 2.03456d;
private int places = 2;

View File

@ -3,13 +3,13 @@ package com.baeldung.money;
import org.javamoney.moneta.FastMoney;
import org.javamoney.moneta.Money;
import org.javamoney.moneta.format.CurrencyStyle;
import org.junit.Ignore;
import org.junit.Test;
import javax.money.CurrencyUnit;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.money.UnknownCurrencyException;
import javax.money.convert.ConversionQueryBuilder;
import javax.money.convert.CurrencyConversion;
import javax.money.convert.MonetaryConversions;
import javax.money.format.AmountFormatQueryBuilder;
@ -19,7 +19,11 @@ import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class JavaMoneyUnitTest {
@ -36,7 +40,6 @@ public class JavaMoneyUnitTest {
@Test(expected = UnknownCurrencyException.class)
public void givenCurrencyCode_whenNoExist_thanThrowsError() {
Monetary.getCurrency("AAA");
fail(); // if no exception
}
@Test
@ -134,6 +137,7 @@ public class JavaMoneyUnitTest {
}
@Test
@Ignore("Currency providers are not always available")
public void givenAmount_whenConversion_thenNotNull() {
MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory()

View File

@ -1,12 +1,14 @@
package com.baeldung.regexp;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import org.junit.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
public class EscapingCharsTest {
@Test

View File

@ -4,7 +4,11 @@ import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import javax.script.*;
import javax.script.Bindings;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

View File

@ -1,6 +1,6 @@
package com.baeldung.serialization;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@ -8,7 +8,7 @@ import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class PersonUnitTest {

View File

@ -1,14 +1,14 @@
package com.baeldung.socket;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.Executors;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.concurrent.Executors;
import static org.junit.Assert.assertEquals;
public class EchoIntegrationTest {
private static final Integer PORT = 4444;

View File

@ -1,6 +1,5 @@
package com.baeldung.stackoverflowerror;
import static org.junit.Assert.fail;
import org.junit.Test;
public class CyclicDependancyManualTest {

View File

@ -1,9 +1,9 @@
package com.baeldung.stackoverflowerror;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
public class InfiniteRecursionWithTerminationConditionManualTest {
@Test
public void givenPositiveIntNoOne_whenCalcFact_thenCorrectlyCalc() {

View File

@ -1,9 +1,9 @@
package com.baeldung.stackoverflowerror;
import static junit.framework.TestCase.assertEquals;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
public class RecursionWithCorrectTerminationConditionManualTest {
@Test
public void givenNegativeInt_whenCalcFact_thenCorrectlyCalc() {

View File

@ -7,7 +7,9 @@ import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import static com.baeldung.strategy.Discounter.*;
import static com.baeldung.strategy.Discounter.christmas;
import static com.baeldung.strategy.Discounter.easter;
import static com.baeldung.strategy.Discounter.newYear;
import static org.assertj.core.api.Assertions.assertThat;
public class StrategyDesignPatternUnitTest {

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