resolve conflict
This commit is contained in:
commit
54a5079a35
8
.gitignore
vendored
8
.gitignore
vendored
@ -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
|
||||
|
@ -6,3 +6,5 @@
|
||||
- [Validating Input With Finite Automata in Java](http://www.baeldung.com/finite-automata-java)
|
||||
- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics)
|
||||
- [Check If a Number Is Prime in Java](http://www.baeldung.com/java-prime-numbers)
|
||||
- [Example of Hill Climbing Algorithm](http://www.baeldung.com/java-hill-climbing-algorithm)
|
||||
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](http://www.baeldung.com/java-monte-carlo-tree-search)
|
||||
|
@ -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());
|
||||
}
|
||||
}
|
@ -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 parentNode) {
|
||||
List<Integer> listofPossibleHeaps = GameOfBones.getPossibleStates(parentNode.getNoOfBones());
|
||||
boolean isChildMaxPlayer = !parentNode.isMaxPlayer();
|
||||
listofPossibleHeaps.forEach(n -> {
|
||||
Node newNode = new Node(n, isChildMaxPlayer);
|
||||
parentNode.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);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
92
algorithms/src/test/java/algorithms/MCTSTest.java
Normal file
92
algorithms/src/test/java/algorithms/MCTSTest.java
Normal 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);
|
||||
}
|
||||
|
||||
}
|
36
algorithms/src/test/java/algorithms/minimax/MinimaxTest.java
Normal file
36
algorithms/src/test/java/algorithms/minimax/MinimaxTest.java
Normal 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);
|
||||
}
|
||||
}
|
32
aws/pom.xml
32
aws/pom.xml
@ -18,9 +18,41 @@
|
||||
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
|
||||
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
|
||||
<gson.version>2.8.0</gson.version>
|
||||
<aws-java-sdk.version>1.11.154</aws-java-sdk.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito-core.version>2.8.9</mockito-core.version>
|
||||
<assertj-core.version>3.8.0</assertj-core.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-java-sdk</artifactId>
|
||||
<version>${aws-java-sdk.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-lambda-java-core</artifactId>
|
||||
|
87
aws/src/main/java/com/baeldung/s3/AWSS3Service.java
Normal file
87
aws/src/main/java/com/baeldung/s3/AWSS3Service.java
Normal file
@ -0,0 +1,87 @@
|
||||
package com.baeldung.s3;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.amazonaws.services.s3.AmazonS3Client;
|
||||
import com.amazonaws.services.s3.model.Bucket;
|
||||
import com.amazonaws.services.s3.model.CopyObjectResult;
|
||||
import com.amazonaws.services.s3.model.DeleteObjectsRequest;
|
||||
import com.amazonaws.services.s3.model.DeleteObjectsResult;
|
||||
import com.amazonaws.services.s3.model.ObjectListing;
|
||||
import com.amazonaws.services.s3.model.PutObjectResult;
|
||||
import com.amazonaws.services.s3.model.S3Object;
|
||||
|
||||
public class AWSS3Service {
|
||||
private final AmazonS3 s3client;
|
||||
|
||||
public AWSS3Service() {
|
||||
this(new AmazonS3Client() {
|
||||
});
|
||||
}
|
||||
|
||||
public AWSS3Service(AmazonS3 s3client) {
|
||||
this.s3client = s3client;
|
||||
}
|
||||
|
||||
//is bucket exist?
|
||||
public boolean doesBucketExist(String bucketName) {
|
||||
return s3client.doesBucketExist(bucketName);
|
||||
}
|
||||
|
||||
//create a bucket
|
||||
public Bucket createBucket(String bucketName) {
|
||||
return s3client.createBucket(bucketName);
|
||||
}
|
||||
|
||||
//list all buckets
|
||||
public List<Bucket> listBuckets() {
|
||||
return s3client.listBuckets();
|
||||
}
|
||||
|
||||
//delete a bucket
|
||||
public void deleteBucket(String bucketName) {
|
||||
s3client.deleteBucket(bucketName);
|
||||
}
|
||||
|
||||
//uploading object
|
||||
public PutObjectResult putObject(String bucketName, String key, File file) {
|
||||
return s3client.putObject(bucketName, key, file);
|
||||
}
|
||||
|
||||
//listing objects
|
||||
public ObjectListing listObjects(String bucketName) {
|
||||
return s3client.listObjects(bucketName);
|
||||
}
|
||||
|
||||
//get an object
|
||||
public S3Object getObject(String bucketName, String objectKey) {
|
||||
return s3client.getObject(bucketName, objectKey);
|
||||
}
|
||||
|
||||
//copying an object
|
||||
public CopyObjectResult copyObject(
|
||||
String sourceBucketName,
|
||||
String sourceKey,
|
||||
String destinationBucketName,
|
||||
String destinationKey
|
||||
) {
|
||||
return s3client.copyObject(
|
||||
sourceBucketName,
|
||||
sourceKey,
|
||||
destinationBucketName,
|
||||
destinationKey
|
||||
);
|
||||
}
|
||||
|
||||
//deleting an object
|
||||
public void deleteObject(String bucketName, String objectKey) {
|
||||
s3client.deleteObject(bucketName, objectKey);
|
||||
}
|
||||
|
||||
//deleting multiple Objects
|
||||
public DeleteObjectsResult deleteObjects(DeleteObjectsRequest delObjReq) {
|
||||
return s3client.deleteObjects(delObjReq);
|
||||
}
|
||||
}
|
108
aws/src/main/java/com/baeldung/s3/S3Application.java
Normal file
108
aws/src/main/java/com/baeldung/s3/S3Application.java
Normal file
@ -0,0 +1,108 @@
|
||||
package com.baeldung.s3;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
import com.amazonaws.auth.AWSCredentials;
|
||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
||||
import com.amazonaws.auth.BasicAWSCredentials;
|
||||
import com.amazonaws.regions.Regions;
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
|
||||
import com.amazonaws.services.s3.model.Bucket;
|
||||
import com.amazonaws.services.s3.model.DeleteObjectsRequest;
|
||||
import com.amazonaws.services.s3.model.ObjectListing;
|
||||
import com.amazonaws.services.s3.model.S3Object;
|
||||
import com.amazonaws.services.s3.model.S3ObjectInputStream;
|
||||
import com.amazonaws.services.s3.model.S3ObjectSummary;
|
||||
|
||||
public class S3Application {
|
||||
|
||||
private static final AWSCredentials credentials;
|
||||
private static String bucketName;
|
||||
|
||||
static {
|
||||
//put your accesskey and secretkey here
|
||||
credentials = new BasicAWSCredentials(
|
||||
"<AWS accesskey>",
|
||||
"<AWS secretkey>"
|
||||
);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
//set-up the client
|
||||
AmazonS3 s3client = AmazonS3ClientBuilder
|
||||
.standard()
|
||||
.withCredentials(new AWSStaticCredentialsProvider(credentials))
|
||||
.withRegion(Regions.US_EAST_2)
|
||||
.build();
|
||||
|
||||
AWSS3Service awsService = new AWSS3Service(s3client);
|
||||
|
||||
bucketName = "baeldung-bucket";
|
||||
|
||||
//creating a bucket
|
||||
if(awsService.doesBucketExist(bucketName)) {
|
||||
System.out.println("Bucket name is not available."
|
||||
+ " Try again with a different Bucket name.");
|
||||
return;
|
||||
}
|
||||
awsService.createBucket(bucketName);
|
||||
|
||||
//list all the buckets
|
||||
for(Bucket s : awsService.listBuckets() ) {
|
||||
System.out.println(s.getName());
|
||||
}
|
||||
|
||||
//deleting bucket
|
||||
awsService.deleteBucket("baeldung-bucket-test2");
|
||||
|
||||
//uploading object
|
||||
awsService.putObject(
|
||||
bucketName,
|
||||
"Document/hello.txt",
|
||||
new File("/Users/user/Document/hello.txt")
|
||||
);
|
||||
|
||||
//listing objects
|
||||
ObjectListing objectListing = awsService.listObjects(bucketName);
|
||||
for(S3ObjectSummary os : objectListing.getObjectSummaries()) {
|
||||
System.out.println(os.getKey());
|
||||
}
|
||||
|
||||
//downloading an object
|
||||
S3Object s3object = awsService.getObject(bucketName, "Document/hello.txt");
|
||||
S3ObjectInputStream inputStream = s3object.getObjectContent();
|
||||
FileOutputStream fos = new FileOutputStream(new File("/Users/user/Desktop/hello.txt"));
|
||||
|
||||
int read = 0;
|
||||
byte[] bytes = new byte[1024];
|
||||
while ((read = inputStream.read(bytes)) != -1) {
|
||||
fos.write(bytes, 0, read);
|
||||
}
|
||||
inputStream.close();
|
||||
fos.close();
|
||||
|
||||
//copying an object
|
||||
awsService.copyObject(
|
||||
"baeldung-bucket",
|
||||
"picture/pic.png",
|
||||
"baeldung-bucket2",
|
||||
"Document/picture.png"
|
||||
);
|
||||
|
||||
//deleting an object
|
||||
awsService.deleteObject(bucketName, "Document/hello.txt");
|
||||
|
||||
//deleting multiple objects
|
||||
String objkeyArr[] = {
|
||||
"Document/hello2.txt",
|
||||
"Document/picture.png"
|
||||
};
|
||||
|
||||
DeleteObjectsRequest delObjReq = new DeleteObjectsRequest("baeldung-bucket")
|
||||
.withKeys(objkeyArr);
|
||||
awsService.deleteObjects(delObjReq);
|
||||
}
|
||||
}
|
@ -0,0 +1,113 @@
|
||||
package com.baeldung.s3;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.amazonaws.services.s3.model.CopyObjectResult;
|
||||
import com.amazonaws.services.s3.model.DeleteObjectsRequest;
|
||||
import com.amazonaws.services.s3.model.DeleteObjectsResult;
|
||||
import com.amazonaws.services.s3.model.PutObjectResult;
|
||||
|
||||
public class AWSS3ServiceIntegrationTest {
|
||||
|
||||
private static final String BUCKET_NAME = "bucket_name";
|
||||
private static final String KEY_NAME = "key_name";
|
||||
private static final String BUCKET_NAME2 = "bucket_name2";
|
||||
private static final String KEY_NAME2 = "key_name2";
|
||||
|
||||
private AmazonS3 s3;
|
||||
private AWSS3Service service;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
s3 = mock(AmazonS3.class);
|
||||
service = new AWSS3Service(s3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInitializingAWSS3Service_thenNotNull() {
|
||||
assertThat(new AWSS3Service()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerifyingIfS3BucketExist_thenCorrect() {
|
||||
service.doesBucketExist(BUCKET_NAME);
|
||||
verify(s3).doesBucketExist(BUCKET_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerifyingCreationOfS3Bucket_thenCorrect() {
|
||||
service.createBucket(BUCKET_NAME);
|
||||
verify(s3).createBucket(BUCKET_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerifyingListBuckets_thenCorrect() {
|
||||
service.listBuckets();
|
||||
verify(s3).listBuckets();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeletingBucket_thenCorrect() {
|
||||
service.deleteBucket(BUCKET_NAME);
|
||||
verify(s3).deleteBucket(BUCKET_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerifyingPutObject_thenCorrect() {
|
||||
File file = mock(File.class);
|
||||
PutObjectResult result = mock(PutObjectResult.class);
|
||||
when(s3.putObject(anyString(), anyString(), (File) any())).thenReturn(result);
|
||||
|
||||
assertThat(service.putObject(BUCKET_NAME, KEY_NAME, file)).isEqualTo(result);
|
||||
verify(s3).putObject(BUCKET_NAME, KEY_NAME, file);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerifyingListObjects_thenCorrect() {
|
||||
service.listObjects(BUCKET_NAME);
|
||||
verify(s3).listObjects(BUCKET_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerifyingGetObject_thenCorrect() {
|
||||
service.getObject(BUCKET_NAME, KEY_NAME);
|
||||
verify(s3).getObject(BUCKET_NAME, KEY_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerifyingCopyObject_thenCorrect() {
|
||||
CopyObjectResult result = mock(CopyObjectResult.class);
|
||||
when(s3.copyObject(anyString(), anyString(), anyString(), anyString())).thenReturn(result);
|
||||
|
||||
assertThat(service.copyObject(BUCKET_NAME, KEY_NAME, BUCKET_NAME2, KEY_NAME2)).isEqualTo(result);
|
||||
verify(s3).copyObject(BUCKET_NAME, KEY_NAME, BUCKET_NAME2, KEY_NAME2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerifyingDeleteObject_thenCorrect() {
|
||||
service.deleteObject(BUCKET_NAME, KEY_NAME);
|
||||
verify(s3).deleteObject(BUCKET_NAME, KEY_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerifyingDeleteObjects_thenCorrect() {
|
||||
DeleteObjectsRequest request = mock(DeleteObjectsRequest.class);
|
||||
DeleteObjectsResult result = mock(DeleteObjectsResult.class);
|
||||
when(s3.deleteObjects((DeleteObjectsRequest)any())).thenReturn(result);
|
||||
|
||||
assertThat(service.deleteObjects(request)).isEqualTo(result);
|
||||
verify(s3).deleteObjects(request);
|
||||
}
|
||||
|
||||
}
|
@ -13,3 +13,6 @@
|
||||
- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api)
|
||||
- [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api)
|
||||
- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity)
|
||||
- [Java 9 Optional API Additions](http://www.baeldung.com/java-9-optional)
|
||||
- [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams)
|
||||
- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
|
||||
|
@ -113,6 +113,16 @@
|
||||
- [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep)
|
||||
- [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator)
|
||||
- [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer)
|
||||
- [The Dining Philosophers Problem in Java](http://www.baeldung.com/java-dining-philoshophers)
|
||||
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
|
||||
- [How to Round a Number to N Decimal Places in Java](http://www.baeldung.com/java-round-decimal-number)
|
||||
- [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params)
|
||||
- [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null)
|
||||
- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream)
|
||||
- [Changing the Order in a Sum Operation Can Produce Different Results?](http://www.baeldung.com/java-floating-point-sum-order)
|
||||
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)
|
||||
- [Iterate over a Map in Java](http://www.baeldung.com/java-iterate-map)
|
||||
- [CyclicBarrier in Java](http://www.baeldung.com/java-cyclic-barrier)
|
||||
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
|
||||
- [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy)
|
||||
- [Introduction to JDBC](http://www.baeldung.com/java-jdbc)
|
||||
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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;
|
||||
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.temporaladjuster;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.temporal.ChronoField;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.time.temporal.Temporal;
|
||||
import java.time.temporal.TemporalAdjuster;
|
||||
|
||||
public class CustomTemporalAdjuster implements TemporalAdjuster {
|
||||
|
||||
@Override
|
||||
public Temporal adjustInto(Temporal temporal) {
|
||||
DayOfWeek dayOfWeek = DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK));
|
||||
int daysToAdd;
|
||||
if (dayOfWeek == DayOfWeek.FRIDAY)
|
||||
daysToAdd = 3;
|
||||
else if (dayOfWeek == DayOfWeek.SATURDAY)
|
||||
daysToAdd = 2;
|
||||
else
|
||||
daysToAdd = 1;
|
||||
return temporal.plus(daysToAdd, ChronoUnit.DAYS);
|
||||
}
|
||||
}
|
@ -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
|
||||
|
@ -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(() -> {
|
||||
|
@ -24,8 +24,8 @@ public class LongAccumulatorUnitTest {
|
||||
|
||||
//when
|
||||
Runnable accumulateAction = () -> IntStream
|
||||
.rangeClosed(0, numberOfIncrements)
|
||||
.forEach(accumulator::accumulate);
|
||||
.rangeClosed(0, numberOfIncrements)
|
||||
.forEach(accumulator::accumulate);
|
||||
|
||||
for (int i = 0; i < numberOfThreads; i++) {
|
||||
executorService.execute(accumulateAction);
|
||||
|
@ -17,7 +17,7 @@ public class CopyOnWriteArrayListUnitTest {
|
||||
public void givenCopyOnWriteList_whenIterateAndAddElementToUnderneathList_thenShouldNotChangeIterator() {
|
||||
//given
|
||||
final CopyOnWriteArrayList<Integer> numbers =
|
||||
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
|
||||
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
|
||||
|
||||
//when
|
||||
Iterator<Integer> iterator = numbers.iterator();
|
||||
@ -42,7 +42,7 @@ public class CopyOnWriteArrayListUnitTest {
|
||||
public void givenCopyOnWriteList_whenIterateOverItAndTryToRemoveElement_thenShouldThrowException() {
|
||||
//given
|
||||
final CopyOnWriteArrayList<Integer> numbers =
|
||||
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
|
||||
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
|
||||
|
||||
//when
|
||||
Iterator<Integer> iterator = numbers.iterator();
|
||||
|
@ -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;
|
||||
|
||||
@ -19,7 +23,7 @@ public class DelayQueueIntegrationTest {
|
||||
int delayOfEachProducedMessageMilliseconds = 500;
|
||||
DelayQueueConsumer consumer = new DelayQueueConsumer(queue, numberOfElementsToProduce);
|
||||
DelayQueueProducer producer
|
||||
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
|
||||
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
|
||||
|
||||
//when
|
||||
executor.submit(producer);
|
||||
@ -41,7 +45,7 @@ public class DelayQueueIntegrationTest {
|
||||
int delayOfEachProducedMessageMilliseconds = 10_000;
|
||||
DelayQueueConsumer consumer = new DelayQueueConsumer(queue, numberOfElementsToProduce);
|
||||
DelayQueueProducer producer
|
||||
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
|
||||
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
|
||||
|
||||
//when
|
||||
executor.submit(producer);
|
||||
@ -63,7 +67,7 @@ public class DelayQueueIntegrationTest {
|
||||
int delayOfEachProducedMessageMilliseconds = -10_000;
|
||||
DelayQueueConsumer consumer = new DelayQueueConsumer(queue, numberOfElementsToProduce);
|
||||
DelayQueueProducer producer
|
||||
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
|
||||
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
|
||||
|
||||
//when
|
||||
executor.submit(producer);
|
||||
|
@ -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 {
|
||||
|
||||
|
@ -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;
|
||||
|
@ -9,65 +9,65 @@ import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class SharedObjectWithLockManualTest {
|
||||
|
||||
@Test
|
||||
public void whenLockAcquired_ThenLockedIsTrue() {
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
@Test
|
||||
public void whenLockAcquired_ThenLockedIsTrue() {
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
|
||||
final int threadCount = 2;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final int threadCount = 2;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
|
||||
executeThreads(object, threadCount, service);
|
||||
executeThreads(object, threadCount, service);
|
||||
|
||||
assertEquals(true, object.isLocked());
|
||||
assertEquals(true, object.isLocked());
|
||||
|
||||
service.shutdown();
|
||||
}
|
||||
service.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLocked_ThenQueuedThread() {
|
||||
final int threadCount = 4;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
@Test
|
||||
public void whenLocked_ThenQueuedThread() {
|
||||
final int threadCount = 4;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
|
||||
executeThreads(object, threadCount, service);
|
||||
executeThreads(object, threadCount, service);
|
||||
|
||||
assertEquals(object.hasQueuedThreads(), true);
|
||||
assertEquals(object.hasQueuedThreads(), true);
|
||||
|
||||
service.shutdown();
|
||||
service.shutdown();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public void whenTryLock_ThenQueuedThread() {
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
public void whenTryLock_ThenQueuedThread() {
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
|
||||
final int threadCount = 2;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final int threadCount = 2;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
|
||||
executeThreads(object, threadCount, service);
|
||||
executeThreads(object, threadCount, service);
|
||||
|
||||
assertEquals(true, object.isLocked());
|
||||
assertEquals(true, object.isLocked());
|
||||
|
||||
service.shutdown();
|
||||
}
|
||||
service.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetCount_ThenCorrectCount() throws InterruptedException {
|
||||
final int threadCount = 4;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
@Test
|
||||
public void whenGetCount_ThenCorrectCount() throws InterruptedException {
|
||||
final int threadCount = 4;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
|
||||
executeThreads(object, threadCount, service);
|
||||
Thread.sleep(1000);
|
||||
assertEquals(object.getCounter(), 4);
|
||||
executeThreads(object, threadCount, service);
|
||||
Thread.sleep(1000);
|
||||
assertEquals(object.getCounter(), 4);
|
||||
|
||||
service.shutdown();
|
||||
service.shutdown();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private void executeThreads(SharedObjectWithLock object, int threadCount, ExecutorService service) {
|
||||
for (int i = 0; i < threadCount; i++) {
|
||||
service.execute(object::perform);
|
||||
}
|
||||
}
|
||||
private void executeThreads(SharedObjectWithLock object, int threadCount, ExecutorService service) {
|
||||
for (int i = 0; i < threadCount; i++) {
|
||||
service.execute(object::perform);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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;
|
||||
@ -10,49 +9,49 @@ import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class SynchronizedHashMapWithRWLockManualTest {
|
||||
|
||||
@Test
|
||||
public void whenWriting_ThenNoReading() {
|
||||
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
|
||||
final int threadCount = 3;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
@Test
|
||||
public void whenWriting_ThenNoReading() {
|
||||
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
|
||||
final int threadCount = 3;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
|
||||
executeWriterThreads(object, threadCount, service);
|
||||
executeWriterThreads(object, threadCount, service);
|
||||
|
||||
assertEquals(object.isReadLockAvailable(), false);
|
||||
assertEquals(object.isReadLockAvailable(), false);
|
||||
|
||||
service.shutdown();
|
||||
}
|
||||
service.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReading_ThenMultipleReadingAllowed() {
|
||||
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
|
||||
final int threadCount = 5;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
@Test
|
||||
public void whenReading_ThenMultipleReadingAllowed() {
|
||||
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
|
||||
final int threadCount = 5;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
|
||||
executeReaderThreads(object, threadCount, service);
|
||||
executeReaderThreads(object, threadCount, service);
|
||||
|
||||
assertEquals(object.isReadLockAvailable(), true);
|
||||
assertEquals(object.isReadLockAvailable(), true);
|
||||
|
||||
service.shutdown();
|
||||
}
|
||||
service.shutdown();
|
||||
}
|
||||
|
||||
private void executeWriterThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
|
||||
for (int i = 0; i < threadCount; i++) {
|
||||
service.execute(() -> {
|
||||
try {
|
||||
object.put("key" + threadCount, "value" + threadCount);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
private void executeWriterThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
|
||||
for (int i = 0; i < threadCount; i++) {
|
||||
service.execute(() -> {
|
||||
try {
|
||||
object.put("key" + threadCount, "value" + threadCount);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void executeReaderThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
|
||||
for (int i = 0; i < threadCount; i++)
|
||||
service.execute(() -> {
|
||||
object.get("key" + threadCount);
|
||||
});
|
||||
}
|
||||
private void executeReaderThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
|
||||
for (int i = 0; i < threadCount; i++)
|
||||
service.execute(() -> {
|
||||
object.get("key" + threadCount);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -42,7 +42,7 @@ public class PriorityBlockingQueueIntegrationTest {
|
||||
try {
|
||||
Integer poll = queue.take();
|
||||
LOG.debug("Polled: " + poll);
|
||||
} catch (InterruptedException e) {
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
@ -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 {
|
||||
|
||||
@ -17,7 +17,7 @@ public class BaeldungSychronizedBlockTest {
|
||||
BaeldungSynchronizedBlocks synchronizedBlocks = new BaeldungSynchronizedBlocks();
|
||||
|
||||
IntStream.range(0, 1000)
|
||||
.forEach(count -> service.submit(synchronizedBlocks::performSynchronisedTask));
|
||||
.forEach(count -> service.submit(synchronizedBlocks::performSynchronisedTask));
|
||||
service.awaitTermination(100, TimeUnit.MILLISECONDS);
|
||||
|
||||
assertEquals(1000, synchronizedBlocks.getCount());
|
||||
@ -28,7 +28,7 @@ public class BaeldungSychronizedBlockTest {
|
||||
ExecutorService service = Executors.newCachedThreadPool();
|
||||
|
||||
IntStream.range(0, 1000)
|
||||
.forEach(count -> service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask));
|
||||
.forEach(count -> service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask));
|
||||
service.awaitTermination(100, TimeUnit.MILLISECONDS);
|
||||
|
||||
assertEquals(1000, BaeldungSynchronizedBlocks.getStaticCount());
|
||||
|
@ -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 {
|
||||
|
||||
@ -19,7 +19,7 @@ public class BaeldungSynchronizeMethodsTest {
|
||||
BaeldungSynchronizedMethods method = new BaeldungSynchronizedMethods();
|
||||
|
||||
IntStream.range(0, 1000)
|
||||
.forEach(count -> service.submit(method::calculate));
|
||||
.forEach(count -> service.submit(method::calculate));
|
||||
service.awaitTermination(100, TimeUnit.MILLISECONDS);
|
||||
|
||||
assertEquals(1000, method.getSum());
|
||||
@ -31,7 +31,7 @@ public class BaeldungSynchronizeMethodsTest {
|
||||
BaeldungSynchronizedMethods method = new BaeldungSynchronizedMethods();
|
||||
|
||||
IntStream.range(0, 1000)
|
||||
.forEach(count -> service.submit(method::synchronisedCalculate));
|
||||
.forEach(count -> service.submit(method::synchronisedCalculate));
|
||||
service.awaitTermination(100, TimeUnit.MILLISECONDS);
|
||||
|
||||
assertEquals(1000, method.getSyncSum());
|
||||
@ -42,7 +42,7 @@ public class BaeldungSynchronizeMethodsTest {
|
||||
ExecutorService service = Executors.newCachedThreadPool();
|
||||
|
||||
IntStream.range(0, 1000)
|
||||
.forEach(count -> service.submit(BaeldungSynchronizedMethods::syncStaticCalculate));
|
||||
.forEach(count -> service.submit(BaeldungSynchronizedMethods::syncStaticCalculate));
|
||||
service.awaitTermination(100, TimeUnit.MILLISECONDS);
|
||||
|
||||
assertEquals(1000, BaeldungSynchronizedMethods.staticSum);
|
||||
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
@ -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")));
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
|
@ -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 {
|
||||
|
@ -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;
|
||||
|
@ -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);
|
||||
|
@ -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 {
|
||||
|
||||
|
@ -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);
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
@ -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";
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
@ -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
|
||||
@ -29,11 +30,11 @@ public class ListOfListsUnitTest {
|
||||
@Test
|
||||
public void givenListOfLists_thenCheckNames() {
|
||||
assertEquals("Pen 1", ((Pen) listOfLists.get(0)
|
||||
.get(0)).getName());
|
||||
.get(0)).getName());
|
||||
assertEquals("Pencil 1", ((Pencil) listOfLists.get(1)
|
||||
.get(0)).getName());
|
||||
.get(0)).getName());
|
||||
assertEquals("Rubber 1", ((Rubber) listOfLists.get(2)
|
||||
.get(0)).getName());
|
||||
.get(0)).getName());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@ -43,10 +44,10 @@ public class ListOfListsUnitTest {
|
||||
((ArrayList<Pencil>) listOfLists.get(1)).remove(0);
|
||||
listOfLists.remove(1);
|
||||
assertEquals("Rubber 1", ((Rubber) listOfLists.get(1)
|
||||
.get(0)).getName());
|
||||
.get(0)).getName());
|
||||
listOfLists.remove(0);
|
||||
assertEquals("Rubber 1", ((Rubber) listOfLists.get(0)
|
||||
.get(0)).getName());
|
||||
.get(0)).getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -67,10 +68,10 @@ public class ListOfListsUnitTest {
|
||||
list.add(rubbers);
|
||||
|
||||
assertEquals("Pen 1", ((Pen) list.get(0)
|
||||
.get(0)).getName());
|
||||
.get(0)).getName());
|
||||
assertEquals("Pencil 1", ((Pencil) list.get(1)
|
||||
.get(0)).getName());
|
||||
.get(0)).getName());
|
||||
assertEquals("Rubber 1", ((Rubber) list.get(2)
|
||||
.get(0)).getName());
|
||||
.get(0)).getName());
|
||||
}
|
||||
}
|
||||
|
@ -47,7 +47,7 @@ public class MappedByteBufferUnitTest {
|
||||
|
||||
//when
|
||||
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite,
|
||||
EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
|
||||
EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
|
||||
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, charBuffer.length());
|
||||
|
||||
if (mappedByteBuffer != null) {
|
||||
@ -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());
|
||||
}
|
||||
|
@ -1,9 +1,10 @@
|
||||
package com.baeldung.maths;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class BigDecimalImplTest {
|
||||
|
||||
|
@ -1,11 +1,10 @@
|
||||
package com.baeldung.maths;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
import org.junit.Assert;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
public class BigIntegerImplTest {
|
||||
|
||||
@Test
|
||||
|
@ -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;
|
||||
|
@ -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,17 +40,16 @@ public class JavaMoneyUnitTest {
|
||||
@Test(expected = UnknownCurrencyException.class)
|
||||
public void givenCurrencyCode_whenNoExist_thanThrowsError() {
|
||||
Monetary.getCurrency("AAA");
|
||||
fail(); // if no exception
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAmounts_whenStringified_thanEquals() {
|
||||
CurrencyUnit usd = Monetary.getCurrency("USD");
|
||||
MonetaryAmount fstAmtUSD = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency(usd)
|
||||
.setNumber(200)
|
||||
.create();
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency(usd)
|
||||
.setNumber(200)
|
||||
.create();
|
||||
Money moneyof = Money.of(12, usd);
|
||||
FastMoney fastmoneyof = FastMoney.of(2, usd);
|
||||
|
||||
@ -59,10 +62,10 @@ public class JavaMoneyUnitTest {
|
||||
@Test
|
||||
public void givenCurrencies_whenCompared_thanNotequal() {
|
||||
MonetaryAmount oneDolar = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
Money oneEuro = Money.of(1, "EUR");
|
||||
|
||||
assertFalse(oneEuro.equals(FastMoney.of(1, "EUR")));
|
||||
@ -72,10 +75,10 @@ public class JavaMoneyUnitTest {
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void givenAmount_whenDivided_thanThrowsException() {
|
||||
MonetaryAmount oneDolar = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
oneDolar.divide(3);
|
||||
fail(); // if no exception
|
||||
}
|
||||
@ -85,8 +88,8 @@ public class JavaMoneyUnitTest {
|
||||
List<MonetaryAmount> monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF"));
|
||||
|
||||
Money sumAmtCHF = (Money) monetaryAmounts
|
||||
.stream()
|
||||
.reduce(Money.of(0, "CHF"), MonetaryAmount::add);
|
||||
.stream()
|
||||
.reduce(Money.of(0, "CHF"), MonetaryAmount::add);
|
||||
|
||||
assertEquals("CHF 111.35", sumAmtCHF.toString());
|
||||
}
|
||||
@ -97,18 +100,18 @@ public class JavaMoneyUnitTest {
|
||||
|
||||
Money moneyof = Money.of(12, usd);
|
||||
MonetaryAmount fstAmtUSD = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency(usd)
|
||||
.setNumber(200.50)
|
||||
.create();
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency(usd)
|
||||
.setNumber(200.50)
|
||||
.create();
|
||||
MonetaryAmount oneDolar = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
Money subtractedAmount = Money
|
||||
.of(1, "USD")
|
||||
.subtract(fstAmtUSD);
|
||||
.of(1, "USD")
|
||||
.subtract(fstAmtUSD);
|
||||
MonetaryAmount multiplyAmount = oneDolar.multiply(0.25);
|
||||
MonetaryAmount divideAmount = oneDolar.divide(0.25);
|
||||
|
||||
@ -124,22 +127,23 @@ public class JavaMoneyUnitTest {
|
||||
@Test
|
||||
public void givenAmount_whenRounded_thanEquals() {
|
||||
MonetaryAmount fstAmtEUR = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("EUR")
|
||||
.setNumber(1.30473908)
|
||||
.create();
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("EUR")
|
||||
.setNumber(1.30473908)
|
||||
.create();
|
||||
MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding());
|
||||
assertEquals("EUR 1.30473908", fstAmtEUR.toString());
|
||||
assertEquals("EUR 1.3", roundEUR.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore("Currency providers are not always available")
|
||||
public void givenAmount_whenConversion_thenNotNull() {
|
||||
MonetaryAmount oneDollar = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
|
||||
CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR");
|
||||
|
||||
@ -152,10 +156,10 @@ public class JavaMoneyUnitTest {
|
||||
@Test
|
||||
public void givenLocale_whenFormatted_thanEquals() {
|
||||
MonetaryAmount oneDollar = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US);
|
||||
String usFormatted = formatUSD.format(oneDollar);
|
||||
|
||||
@ -167,16 +171,16 @@ public class JavaMoneyUnitTest {
|
||||
@Test
|
||||
public void givenAmount_whenCustomFormat_thanEquals() {
|
||||
MonetaryAmount oneDollar = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
|
||||
MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder
|
||||
.of(Locale.US)
|
||||
.set(CurrencyStyle.NAME)
|
||||
.set("pattern", "00000.00 ¤")
|
||||
.build());
|
||||
.of(Locale.US)
|
||||
.set(CurrencyStyle.NAME)
|
||||
.set("pattern", "00000.00 ¤")
|
||||
.build());
|
||||
String customFormatted = customFormat.format(oneDollar);
|
||||
|
||||
assertNotNull(customFormat);
|
||||
|
@ -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
|
||||
@ -38,17 +40,17 @@ public class EscapingCharsTest {
|
||||
String strInput = "foo|bar|hello|world";
|
||||
String strRegex = "|";
|
||||
|
||||
assertEquals(4,strInput.split(Pattern.quote(strRegex)).length);
|
||||
assertEquals(4, strInput.split(Pattern.quote(strRegex)).length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithDollar_whenReplacing_thenNotReplace() {
|
||||
String strInput = "I gave $50 to my brother."
|
||||
+ "He bought candy for $35. Now he has $15 left.";
|
||||
+ "He bought candy for $35. Now he has $15 left.";
|
||||
String strRegex = "$";
|
||||
String strReplacement = "£";
|
||||
String output = "I gave £50 to my brother."
|
||||
+ "He bought candy for £35. Now he has £15 left.";
|
||||
+ "He bought candy for £35. Now he has £15 left.";
|
||||
Pattern p = Pattern.compile(strRegex);
|
||||
Matcher m = p.matcher(strInput);
|
||||
|
||||
@ -58,14 +60,14 @@ public class EscapingCharsTest {
|
||||
@Test
|
||||
public void givenRegexWithDollarEsc_whenReplacing_thenReplace() {
|
||||
String strInput = "I gave $50 to my brother."
|
||||
+ "He bought candy for $35. Now he has $15 left.";
|
||||
+ "He bought candy for $35. Now he has $15 left.";
|
||||
String strRegex = "\\$";
|
||||
String strReplacement = "£";
|
||||
String output = "I gave £50 to my brother."
|
||||
+ "He bought candy for £35. Now he has £15 left.";
|
||||
+ "He bought candy for £35. Now he has £15 left.";
|
||||
Pattern p = Pattern.compile(strRegex);
|
||||
Matcher m = p.matcher(strInput);
|
||||
|
||||
assertEquals(output,m.replaceAll(strReplacement));
|
||||
assertEquals(output, m.replaceAll(strReplacement));
|
||||
}
|
||||
}
|
||||
|
@ -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;
|
||||
|
@ -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,57 +8,57 @@ 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 {
|
||||
|
||||
@Test
|
||||
public void whenSerializingAndDeserializing_ThenObjectIsTheSame() throws IOException, ClassNotFoundException {
|
||||
Person p = new Person();
|
||||
p.setAge(20);
|
||||
p.setName("Joe");
|
||||
@Test
|
||||
public void whenSerializingAndDeserializing_ThenObjectIsTheSame() throws IOException, ClassNotFoundException {
|
||||
Person p = new Person();
|
||||
p.setAge(20);
|
||||
p.setName("Joe");
|
||||
|
||||
FileOutputStream fileOutputStream = new FileOutputStream("yofile.txt");
|
||||
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
|
||||
objectOutputStream.writeObject(p);
|
||||
objectOutputStream.flush();
|
||||
objectOutputStream.close();
|
||||
FileOutputStream fileOutputStream = new FileOutputStream("yofile.txt");
|
||||
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
|
||||
objectOutputStream.writeObject(p);
|
||||
objectOutputStream.flush();
|
||||
objectOutputStream.close();
|
||||
|
||||
FileInputStream fileInputStream = new FileInputStream("yofile.txt");
|
||||
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
|
||||
Person p2 = (Person) objectInputStream.readObject();
|
||||
objectInputStream.close();
|
||||
FileInputStream fileInputStream = new FileInputStream("yofile.txt");
|
||||
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
|
||||
Person p2 = (Person) objectInputStream.readObject();
|
||||
objectInputStream.close();
|
||||
|
||||
assertTrue(p2.getAge() == p.getAge());
|
||||
assertTrue(p2.getName().equals(p.getName()));
|
||||
}
|
||||
assertTrue(p2.getAge() == p.getAge());
|
||||
assertTrue(p2.getName().equals(p.getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCustomSerializingAndDeserializing_ThenObjectIsTheSame() throws IOException, ClassNotFoundException {
|
||||
Person p = new Person();
|
||||
p.setAge(20);
|
||||
p.setName("Joe");
|
||||
@Test
|
||||
public void whenCustomSerializingAndDeserializing_ThenObjectIsTheSame() throws IOException, ClassNotFoundException {
|
||||
Person p = new Person();
|
||||
p.setAge(20);
|
||||
p.setName("Joe");
|
||||
|
||||
Address a = new Address();
|
||||
a.setHouseNumber(1);
|
||||
Address a = new Address();
|
||||
a.setHouseNumber(1);
|
||||
|
||||
Employee e = new Employee();
|
||||
e.setPerson(p);
|
||||
e.setAddress(a);
|
||||
Employee e = new Employee();
|
||||
e.setPerson(p);
|
||||
e.setAddress(a);
|
||||
|
||||
FileOutputStream fileOutputStream = new FileOutputStream("yofile2.txt");
|
||||
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
|
||||
objectOutputStream.writeObject(e);
|
||||
objectOutputStream.flush();
|
||||
objectOutputStream.close();
|
||||
FileOutputStream fileOutputStream = new FileOutputStream("yofile2.txt");
|
||||
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
|
||||
objectOutputStream.writeObject(e);
|
||||
objectOutputStream.flush();
|
||||
objectOutputStream.close();
|
||||
|
||||
FileInputStream fileInputStream = new FileInputStream("yofile2.txt");
|
||||
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
|
||||
Employee e2 = (Employee) objectInputStream.readObject();
|
||||
objectInputStream.close();
|
||||
FileInputStream fileInputStream = new FileInputStream("yofile2.txt");
|
||||
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
|
||||
Employee e2 = (Employee) objectInputStream.readObject();
|
||||
objectInputStream.close();
|
||||
|
||||
assertTrue(e2.getPerson().getAge() == e.getPerson().getAge());
|
||||
assertTrue(e2.getAddress().getHouseNumber() == (e.getAddress().getHouseNumber()));
|
||||
}
|
||||
assertTrue(e2.getPerson().getAge() == e.getPerson().getAge());
|
||||
assertTrue(e2.getAddress().getHouseNumber() == (e.getAddress().getHouseNumber()));
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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;
|
||||
|
||||
|
@ -1,11 +1,10 @@
|
||||
package com.baeldung.stackoverflowerror;
|
||||
|
||||
import static org.junit.Assert.fail;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CyclicDependancyManualTest {
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void whenInstanciatingClassOne_thenThrowsException() {
|
||||
ClassOne obj = new ClassOne();
|
||||
ClassOne obj = new ClassOne();
|
||||
}
|
||||
}
|
||||
|
@ -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() {
|
||||
@ -23,9 +23,9 @@ public class InfiniteRecursionWithTerminationConditionManualTest {
|
||||
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void givenNegativeInt_whenCalcFact_thenThrowsException() {
|
||||
int numToCalcFactorial = -1;
|
||||
InfiniteRecursionWithTerminationCondition irtc = new InfiniteRecursionWithTerminationCondition();
|
||||
int numToCalcFactorial = -1;
|
||||
InfiniteRecursionWithTerminationCondition irtc = new InfiniteRecursionWithTerminationCondition();
|
||||
|
||||
irtc.calculateFactorial(numToCalcFactorial);
|
||||
irtc.calculateFactorial(numToCalcFactorial);
|
||||
}
|
||||
}
|
||||
|
@ -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() {
|
||||
|
@ -6,7 +6,7 @@ import org.junit.Test;
|
||||
public class UnintendedInfiniteRecursionManualTest {
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void givenPositiveIntNoOne_whenCalFact_thenThrowsException() {
|
||||
int numToCalcFactorial= 1;
|
||||
int numToCalcFactorial = 1;
|
||||
UnintendedInfiniteRecursion uir = new UnintendedInfiniteRecursion();
|
||||
|
||||
uir.calculateFactorial(numToCalcFactorial);
|
||||
@ -14,7 +14,7 @@ public class UnintendedInfiniteRecursionManualTest {
|
||||
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void givenPositiveIntGtOne_whenCalcFact_thenThrowsException() {
|
||||
int numToCalcFactorial= 2;
|
||||
int numToCalcFactorial = 2;
|
||||
UnintendedInfiniteRecursion uir = new UnintendedInfiniteRecursion();
|
||||
|
||||
uir.calculateFactorial(numToCalcFactorial);
|
||||
@ -22,7 +22,7 @@ public class UnintendedInfiniteRecursionManualTest {
|
||||
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void givenNegativeInt_whenCalcFact_thenThrowsException() {
|
||||
int numToCalcFactorial= -1;
|
||||
int numToCalcFactorial = -1;
|
||||
UnintendedInfiniteRecursion uir = new UnintendedInfiniteRecursion();
|
||||
|
||||
uir.calculateFactorial(numToCalcFactorial);
|
||||
|
@ -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 {
|
||||
@ -26,7 +28,7 @@ public class StrategyDesignPatternUnitTest {
|
||||
public void shouldDivideByTwo_WhenApplyingStaffDiscounterWithAnonyousTypes() {
|
||||
Discounter staffDiscounter = new Discounter() {
|
||||
@Override
|
||||
public BigDecimal apply( BigDecimal amount) {
|
||||
public BigDecimal apply(BigDecimal amount) {
|
||||
return amount.multiply(BigDecimal.valueOf(0.5));
|
||||
}
|
||||
};
|
||||
|
@ -5,7 +5,6 @@ import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
@ -22,8 +21,8 @@ public class InfiniteStreamUnitTest {
|
||||
|
||||
//when
|
||||
List<Integer> collect = infiniteStream
|
||||
.limit(10)
|
||||
.collect(Collectors.toList());
|
||||
.limit(10)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
//then
|
||||
assertEquals(collect, Arrays.asList(0, 2, 4, 6, 8, 10, 12, 14, 16, 18));
|
||||
@ -37,9 +36,9 @@ public class InfiniteStreamUnitTest {
|
||||
|
||||
//when
|
||||
List<UUID> randomInts = infiniteStreamOfRandomUUID
|
||||
.skip(10)
|
||||
.limit(10)
|
||||
.collect(Collectors.toList());
|
||||
.skip(10)
|
||||
.limit(10)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
//then
|
||||
assertEquals(randomInts.size(), 10);
|
||||
|
@ -1,10 +1,12 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StreamAddUnitTest {
|
||||
|
||||
@ -25,7 +27,7 @@ public class StreamAddUnitTest {
|
||||
Stream<Integer> newStream = Stream.concat(Stream.of(99), anStream);
|
||||
|
||||
assertEquals(newStream.findFirst()
|
||||
.get(), (Integer) 99);
|
||||
.get(), (Integer) 99);
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -38,7 +40,7 @@ public class StreamAddUnitTest {
|
||||
assertEquals(resultList.get(3), (Double) 9.9);
|
||||
}
|
||||
|
||||
public <T> Stream<T> insertInStream(Stream<T> stream, T elem, int index) {
|
||||
private <T> Stream<T> insertInStream(Stream<T> stream, T elem, int index) {
|
||||
List<T> result = stream.collect(Collectors.toList());
|
||||
result.add(index, elem);
|
||||
return result.stream();
|
||||
|
@ -1,68 +1,66 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.string.JoinerSplitter;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class JoinerSplitterUnitTest {
|
||||
|
||||
@Test
|
||||
public void provided_array_convert_to_stream_and_convert_to_string() {
|
||||
@Test
|
||||
public void provided_array_convert_to_stream_and_convert_to_string() {
|
||||
|
||||
String[] programming_languages = {"java", "python", "nodejs", "ruby"};
|
||||
String[] programming_languages = {"java", "python", "nodejs", "ruby"};
|
||||
|
||||
String expectation = "java,python,nodejs,ruby";
|
||||
String expectation = "java,python,nodejs,ruby";
|
||||
|
||||
String result = JoinerSplitter.join(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
String result = JoinerSplitter.join(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_transformedToStream_convertToPrefixPostfixString() {
|
||||
@Test
|
||||
public void givenArray_transformedToStream_convertToPrefixPostfixString() {
|
||||
|
||||
String[] programming_languages = {"java", "python",
|
||||
"nodejs", "ruby"};
|
||||
String expectation = "[java,python,nodejs,ruby]";
|
||||
String[] programming_languages = {"java", "python",
|
||||
"nodejs", "ruby"};
|
||||
String expectation = "[java,python,nodejs,ruby]";
|
||||
|
||||
String result = JoinerSplitter.joinWithPrefixPostFix(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
String result = JoinerSplitter.joinWithPrefixPostFix(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_transformedToStream_convertToList() {
|
||||
@Test
|
||||
public void givenString_transformedToStream_convertToList() {
|
||||
|
||||
String programming_languages = "java,python,nodejs,ruby";
|
||||
String programming_languages = "java,python,nodejs,ruby";
|
||||
|
||||
List<String> expectation = new ArrayList<String>();
|
||||
expectation.add("java");
|
||||
expectation.add("python");
|
||||
expectation.add("nodejs");
|
||||
expectation.add("ruby");
|
||||
List<String> expectation = new ArrayList<String>();
|
||||
expectation.add("java");
|
||||
expectation.add("python");
|
||||
expectation.add("nodejs");
|
||||
expectation.add("ruby");
|
||||
|
||||
List<String> result = JoinerSplitter.split(programming_languages);
|
||||
List<String> result = JoinerSplitter.split(programming_languages);
|
||||
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_transformedToStream_convertToListOfChar() {
|
||||
@Test
|
||||
public void givenString_transformedToStream_convertToListOfChar() {
|
||||
|
||||
String programming_languages = "java,python,nodejs,ruby";
|
||||
String programming_languages = "java,python,nodejs,ruby";
|
||||
|
||||
List<Character> expectation = new ArrayList<Character>();
|
||||
char[] charArray = programming_languages.toCharArray();
|
||||
for (char c : charArray) {
|
||||
expectation.add(c);
|
||||
}
|
||||
List<Character> expectation = new ArrayList<Character>();
|
||||
char[] charArray = programming_languages.toCharArray();
|
||||
for (char c : charArray) {
|
||||
expectation.add(c);
|
||||
}
|
||||
|
||||
List<Character> result = JoinerSplitter.splitToListOfChar(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
List<Character> result = JoinerSplitter.splitToListOfChar(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -2,7 +2,6 @@ package com.baeldung.string;
|
||||
|
||||
import com.google.common.base.Splitter;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.assertj.core.util.Lists;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
@ -1,9 +1,10 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringHelperUnitTest {
|
||||
|
||||
|
@ -0,0 +1,56 @@
|
||||
package com.baeldung.temporaladjusters;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
import java.time.temporal.TemporalAdjuster;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.temporaladjuster.CustomTemporalAdjuster;
|
||||
|
||||
public class CustomTemporalAdjusterTest {
|
||||
|
||||
@Test
|
||||
public void whenAdjustAndImplementInterface_thenNextWorkingDay() {
|
||||
LocalDate localDate = LocalDate.of(2017, 07, 8);
|
||||
CustomTemporalAdjuster temporalAdjuster = new CustomTemporalAdjuster();
|
||||
LocalDate nextWorkingDay = localDate.with(temporalAdjuster);
|
||||
|
||||
Assert.assertEquals("2017-07-10", nextWorkingDay.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAdjust_thenNextWorkingDay() {
|
||||
LocalDate localDate = LocalDate.of(2017, 07, 8);
|
||||
TemporalAdjuster temporalAdjuster = NEXT_WORKING_DAY;
|
||||
LocalDate date = localDate.with(temporalAdjuster);
|
||||
|
||||
Assert.assertEquals("2017-07-10", date.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAdjust_thenFourteenDaysAfterDate() {
|
||||
LocalDate localDate = LocalDate.of(2017, 07, 8);
|
||||
TemporalAdjuster temporalAdjuster = (t) -> t.plus(Period.ofDays(14));
|
||||
LocalDate result = localDate.with(temporalAdjuster);
|
||||
|
||||
String fourteenDaysAfterDate = "2017-07-22";
|
||||
|
||||
Assert.assertEquals(fourteenDaysAfterDate, result.toString());
|
||||
}
|
||||
|
||||
static TemporalAdjuster NEXT_WORKING_DAY = TemporalAdjusters.ofDateAdjuster(date -> {
|
||||
DayOfWeek dayOfWeek = date.getDayOfWeek();
|
||||
int daysToAdd;
|
||||
if (dayOfWeek == DayOfWeek.FRIDAY)
|
||||
daysToAdd = 3;
|
||||
else if (dayOfWeek == DayOfWeek.SATURDAY)
|
||||
daysToAdd = 2;
|
||||
else
|
||||
daysToAdd = 1;
|
||||
return date.plusDays(daysToAdd);
|
||||
});
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.baeldung.temporaladjusters;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TemporalAdjustersTest {
|
||||
|
||||
@Test
|
||||
public void whenAdjust_thenNextSunday() {
|
||||
LocalDate localDate = LocalDate.of(2017, 07, 8);
|
||||
LocalDate nextSunday = localDate.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
|
||||
|
||||
String expected = "2017-07-09";
|
||||
|
||||
Assert.assertEquals(expected, nextSunday.toString());
|
||||
}
|
||||
|
||||
}
|
@ -15,7 +15,7 @@ class OffHeapArray {
|
||||
return (Unsafe) f.get(null);
|
||||
}
|
||||
|
||||
public OffHeapArray(long size) throws NoSuchFieldException, IllegalAccessException {
|
||||
OffHeapArray(long size) throws NoSuchFieldException, IllegalAccessException {
|
||||
this.size = size;
|
||||
address = getUnsafe().allocateMemory(size * BYTE);
|
||||
}
|
||||
@ -32,7 +32,7 @@ class OffHeapArray {
|
||||
return size;
|
||||
}
|
||||
|
||||
public void freeMemory() throws NoSuchFieldException, IllegalAccessException {
|
||||
void freeMemory() throws NoSuchFieldException, IllegalAccessException {
|
||||
getUnsafe().freeMemory(address);
|
||||
}
|
||||
|
||||
|
@ -1,3 +1,4 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [Guide to EJB Set-up](http://www.baeldung.com/ejb-intro)
|
||||
- [Java EE Session Beans](http://www.baeldung.com/ejb-session-beans)
|
||||
|
@ -28,3 +28,4 @@
|
||||
- [Guide to Guava ClassToInstanceMap](http://www.baeldung.com/guava-class-to-instance-map)
|
||||
- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](http://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue)
|
||||
- [Guide to Mathematical Utilities in Guava](http://www.baeldung.com/guava-math)
|
||||
- [Bloom Filter in Java using Guava](http://www.baeldung.com/guava-bloom-filter)
|
||||
|
@ -3,11 +3,11 @@ package org.baeldung.guava;
|
||||
public class CustomEvent {
|
||||
private String action;
|
||||
|
||||
public CustomEvent(String action) {
|
||||
CustomEvent(String action) {
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
public String getAction() {
|
||||
String getAction() {
|
||||
return action;
|
||||
}
|
||||
|
||||
|
@ -28,11 +28,11 @@ public class EventListener {
|
||||
eventsHandled++;
|
||||
}
|
||||
|
||||
public int getEventsHandled() {
|
||||
int getEventsHandled() {
|
||||
return eventsHandled;
|
||||
}
|
||||
|
||||
public void resetEventsHandled() {
|
||||
void resetEventsHandled() {
|
||||
eventsHandled = 0;
|
||||
}
|
||||
}
|
||||
|
54
guava/src/test/java/org/baeldung/guava/BloomFilterTest.java
Normal file
54
guava/src/test/java/org/baeldung/guava/BloomFilterTest.java
Normal file
@ -0,0 +1,54 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
|
||||
import com.google.common.hash.BloomFilter;
|
||||
import com.google.common.hash.Funnels;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class BloomFilterTest {
|
||||
|
||||
@Test
|
||||
public void givenBloomFilter_whenAddNStringsToIt_thenShouldNotReturnAnyFalsePositive() {
|
||||
//when
|
||||
BloomFilter<Integer> filter = BloomFilter.create(
|
||||
Funnels.integerFunnel(),
|
||||
500,
|
||||
0.01);
|
||||
|
||||
//when
|
||||
filter.put(1);
|
||||
filter.put(2);
|
||||
filter.put(3);
|
||||
|
||||
//then
|
||||
// the probability that it returns true, but is actually false is 1%
|
||||
assertThat(filter.mightContain(1)).isTrue();
|
||||
assertThat(filter.mightContain(2)).isTrue();
|
||||
assertThat(filter.mightContain(3)).isTrue();
|
||||
|
||||
assertThat(filter.mightContain(100)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBloomFilter_whenAddNStringsToItMoreThanDefinedExpectedInsertions_thenItWillReturnTrueForAlmostAllElements() {
|
||||
//when
|
||||
BloomFilter<Integer> filter = BloomFilter.create(
|
||||
Funnels.integerFunnel(),
|
||||
5,
|
||||
0.01);
|
||||
|
||||
//when
|
||||
IntStream.range(0, 100_000).forEach(filter::put);
|
||||
|
||||
|
||||
//then
|
||||
assertThat(filter.mightContain(1)).isTrue();
|
||||
assertThat(filter.mightContain(2)).isTrue();
|
||||
assertThat(filter.mightContain(3)).isTrue();
|
||||
assertThat(filter.mightContain(1_000_000)).isTrue();
|
||||
}
|
||||
}
|
@ -0,0 +1,82 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
|
||||
import com.google.common.util.concurrent.RateLimiter;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class RateLimiterLongRunningUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenLimitedResource_whenUseRateLimiter_thenShouldLimitPermits() {
|
||||
//given
|
||||
RateLimiter rateLimiter = RateLimiter.create(100);
|
||||
|
||||
//when
|
||||
long startTime = ZonedDateTime.now().getSecond();
|
||||
IntStream.range(0, 1000).forEach(i -> {
|
||||
rateLimiter.acquire();
|
||||
doSomeLimitedOperation();
|
||||
});
|
||||
long elapsedTimeSeconds = ZonedDateTime.now().getSecond() - startTime;
|
||||
|
||||
//then
|
||||
assertThat(elapsedTimeSeconds >= 10);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLimitedResource_whenRequestTwice_thenShouldPermitWithoutBlocking() {
|
||||
//given
|
||||
RateLimiter rateLimiter = RateLimiter.create(2);
|
||||
|
||||
//when
|
||||
long startTime = ZonedDateTime.now().getSecond();
|
||||
rateLimiter.acquire(1);
|
||||
doSomeLimitedOperation();
|
||||
rateLimiter.acquire(1);
|
||||
doSomeLimitedOperation();
|
||||
long elapsedTimeSeconds = ZonedDateTime.now().getSecond() - startTime;
|
||||
|
||||
//then
|
||||
assertThat(elapsedTimeSeconds <= 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLimitedResource_whenRequestOnce_thenShouldPermitWithoutBlocking() {
|
||||
//given
|
||||
RateLimiter rateLimiter = RateLimiter.create(100);
|
||||
|
||||
//when
|
||||
long startTime = ZonedDateTime.now().getSecond();
|
||||
rateLimiter.acquire(100);
|
||||
doSomeLimitedOperation();
|
||||
long elapsedTimeSeconds = ZonedDateTime.now().getSecond() - startTime;
|
||||
|
||||
//then
|
||||
assertThat(elapsedTimeSeconds <= 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLimitedResource_whenTryAcquire_shouldNotBlockIndefinitely() {
|
||||
//given
|
||||
RateLimiter rateLimiter = RateLimiter.create(1);
|
||||
|
||||
//when
|
||||
rateLimiter.acquire();
|
||||
boolean result = rateLimiter.tryAcquire(2, 10, TimeUnit.MILLISECONDS);
|
||||
|
||||
//then
|
||||
assertThat(result).isFalse();
|
||||
|
||||
}
|
||||
|
||||
private void doSomeLimitedOperation() {
|
||||
//some computing
|
||||
}
|
||||
|
||||
}
|
@ -4,8 +4,7 @@
|
||||
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.guava</groupId>
|
||||
<artifactId>tutorial</artifactId>
|
||||
<artifactId>guava21</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
@ -15,12 +14,17 @@
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>21.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.jooq</groupId>
|
||||
<artifactId>jool</artifactId>
|
||||
<version>0.9.12</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
|
@ -0,0 +1,85 @@
|
||||
package com.baeldung.guava.zip;
|
||||
|
||||
import com.google.common.collect.Streams;
|
||||
import org.jooq.lambda.Seq;
|
||||
import org.jooq.lambda.tuple.Tuple2;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ZipCollectionTest {
|
||||
|
||||
private List<String> names;
|
||||
private List<Integer> ages;
|
||||
private List<String> expectedOutput;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
names = Arrays.asList("John", "Jane", "Jack", "Dennis");
|
||||
ages = Arrays.asList(24, 25, 27);
|
||||
expectedOutput = Arrays.asList("John:24", "Jane:25", "Jack:27");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void zipCollectionUsingGuava21() {
|
||||
List<String> output = Streams
|
||||
.zip(names.stream(), ages.stream(), (name, age) -> name + ":" + age)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(output, expectedOutput);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void zipCollectionUsingIntStream() {
|
||||
List<String> output = IntStream
|
||||
.range(0, Math.min(names.size(), ages.size()))
|
||||
.mapToObj(i -> names.get(i) + ":" + ages.get(i))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(output, expectedOutput);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void zipCollectionUsingJool() {
|
||||
Seq<String> output = Seq
|
||||
.of("John", "Jane", "Jack")
|
||||
.zip(Seq.of(24, 25, 27), (x, y) -> x + ":" + y);
|
||||
|
||||
assertEquals(output.toList(), expectedOutput);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void zipCollectionUsingJoolTuple() {
|
||||
Seq<Tuple2<String, Integer>> output = Seq
|
||||
.of("John", "Jane", "Dennis")
|
||||
.zip(Seq.of(24, 25, 27));
|
||||
|
||||
Tuple2<String, Integer> element1 = new Tuple2<String, Integer>("John", 24);
|
||||
Tuple2<String, Integer> element2 = new Tuple2<String, Integer>("Jane", 25);
|
||||
Tuple2<String, Integer> element3 = new Tuple2<String, Integer>("Dennis", 27);
|
||||
|
||||
List<Tuple2> expectedOutput = Arrays.asList(element1, element2, element3);
|
||||
assertEquals(output.collect(Collectors.toList()), expectedOutput);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void zipCollectionUsingJoolWithIndex() {
|
||||
Seq<Tuple2<String, Long>> output = Seq
|
||||
.of("John", "Jane", "Dennis")
|
||||
.zipWithIndex();
|
||||
|
||||
Tuple2<String, Long> element1 = new Tuple2<>("John", 0L);
|
||||
Tuple2<String, Long> element2 = new Tuple2<>("Jane", 1L);
|
||||
Tuple2<String, Long> element3 = new Tuple2<>("Dennis", 2L);
|
||||
|
||||
List<Tuple2> expectedOutput = Arrays.asList(element1, element2, element3);
|
||||
assertEquals(output.collect(Collectors.toList()), expectedOutput);
|
||||
}
|
||||
|
||||
}
|
@ -1,3 +1,5 @@
|
||||
package com.baeldung.guava.tutorial;
|
||||
|
||||
import com.google.common.util.concurrent.AtomicLongMap;
|
||||
import org.junit.Test;
|
||||
|
@ -1,3 +1,5 @@
|
||||
package com.baeldung.guava.tutorial;
|
||||
|
||||
import com.google.common.collect.Comparators;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
@ -1,21 +1,33 @@
|
||||
package com.baeldung.guava.tutorial;
|
||||
|
||||
import com.google.common.collect.Streams;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.OptionalLong;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.DoubleStream;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.LongStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static com.baeldung.guava.tutorial.StreamUtility.assertStreamEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class GuavaStreamsUnitTest {
|
||||
|
||||
List<Integer> numbers;
|
||||
private List<Integer> numbers;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
|
||||
numbers = IntStream.rangeClosed(1, 20).boxed().collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -24,17 +36,17 @@ public class GuavaStreamsUnitTest {
|
||||
Stream streamFromCollection = Streams.stream(numbers);
|
||||
|
||||
//Assert.assertNotNull(streamFromCollection);
|
||||
StreamUtility.assertStreamEquals(streamFromCollection, numbers.stream());
|
||||
assertStreamEquals(streamFromCollection, numbers.stream());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createStreamsWithIterable() {
|
||||
Iterable<Integer> numbersIterable = (Iterable<Integer>) numbers;
|
||||
Iterable<Integer> numbersIterable = numbers;
|
||||
|
||||
Stream streamFromIterable = Streams.stream(numbersIterable);
|
||||
|
||||
Assert.assertNotNull(streamFromIterable);
|
||||
StreamUtility.assertStreamEquals(streamFromIterable, numbers.stream());
|
||||
assertNotNull(streamFromIterable);
|
||||
assertStreamEquals(streamFromIterable, numbers.stream());
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -43,8 +55,8 @@ public class GuavaStreamsUnitTest {
|
||||
|
||||
Stream streamFromIterator = Streams.stream(numbersIterator);
|
||||
|
||||
Assert.assertNotNull(streamFromIterator);
|
||||
StreamUtility.assertStreamEquals(streamFromIterator, numbers.stream());
|
||||
assertNotNull(streamFromIterator);
|
||||
assertStreamEquals(streamFromIterator, numbers.stream());
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -52,8 +64,8 @@ public class GuavaStreamsUnitTest {
|
||||
|
||||
Stream streamFromOptional = Streams.stream(Optional.of(1));
|
||||
|
||||
Assert.assertNotNull(streamFromOptional);
|
||||
Assert.assertEquals(streamFromOptional.count(), 1);
|
||||
assertNotNull(streamFromOptional);
|
||||
assertEquals(streamFromOptional.count(), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -61,8 +73,8 @@ public class GuavaStreamsUnitTest {
|
||||
|
||||
LongStream streamFromOptionalLong = Streams.stream(OptionalLong.of(1));
|
||||
|
||||
Assert.assertNotNull(streamFromOptionalLong);
|
||||
Assert.assertEquals(streamFromOptionalLong.count(), 1);
|
||||
assertNotNull(streamFromOptionalLong);
|
||||
assertEquals(streamFromOptionalLong.count(), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -71,7 +83,7 @@ public class GuavaStreamsUnitTest {
|
||||
IntStream streamFromOptionalInt = Streams.stream(OptionalInt.of(1));
|
||||
|
||||
//Assert.assertNotNull(streamFromOptionalInt);
|
||||
Assert.assertEquals(streamFromOptionalInt.count(), 1);
|
||||
assertEquals(streamFromOptionalInt.count(), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -80,63 +92,54 @@ public class GuavaStreamsUnitTest {
|
||||
DoubleStream streamFromOptionalDouble = Streams.stream(OptionalDouble.of(1.0));
|
||||
|
||||
//Assert.assertNotNull(streamFromOptionalDouble);
|
||||
Assert.assertEquals(streamFromOptionalDouble.count(), 1);
|
||||
assertEquals(streamFromOptionalDouble.count(), 1);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void concatStreamsOfSameType() {
|
||||
Stream oddNumbers = Arrays
|
||||
.asList(1, 3, 5, 7, 9, 11, 13, 15, 17, 19)
|
||||
.stream();
|
||||
Stream evenNumbers = Arrays
|
||||
.asList(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
|
||||
.stream();
|
||||
List<Integer> oddNumbers = Arrays
|
||||
.asList(1, 3, 5, 7, 9, 11, 13, 15, 17, 19);
|
||||
List<Integer> evenNumbers = Arrays
|
||||
.asList(2, 4, 6, 8, 10, 12, 14, 16, 18, 20);
|
||||
|
||||
Stream combinedStreams = Streams.concat(oddNumbers, evenNumbers);
|
||||
Stream<Integer> combinedStreams = Streams.concat(oddNumbers.stream(), evenNumbers.stream());
|
||||
|
||||
//Assert.assertNotNull(combinedStreams);
|
||||
StreamUtility.assertStreamEquals(combinedStreams, Stream.concat(oddNumbers, evenNumbers));
|
||||
assertStreamEquals(combinedStreams, Stream.concat(oddNumbers.stream(), evenNumbers.stream()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void concatStreamsOfTypeLongStream() {
|
||||
LongStream firstTwenty = LongStream.range(1, 20);
|
||||
LongStream nextTwenty = LongStream.range(21, 40);
|
||||
LongStream combinedStreams = Streams.concat(LongStream.range(1, 21), LongStream.range(21, 40));
|
||||
|
||||
LongStream combinedStreams = Streams.concat(firstTwenty, nextTwenty);
|
||||
|
||||
Assert.assertNotNull(combinedStreams);
|
||||
StreamUtility.assertStreamEquals(combinedStreams, LongStream.concat(firstTwenty, nextTwenty));
|
||||
assertNotNull(combinedStreams);
|
||||
assertStreamEquals(combinedStreams, LongStream.range(1, 40));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void concatStreamsOfTypeIntStream() {
|
||||
IntStream firstTwenty = IntStream.range(1, 20);
|
||||
IntStream nextTwenty = IntStream.range(21, 40);
|
||||
IntStream combinedStreams = Streams.concat(IntStream.range(1, 20), IntStream.range(21, 40));
|
||||
|
||||
IntStream combinedStreams = Streams.concat(firstTwenty, nextTwenty);
|
||||
|
||||
Assert.assertNotNull(combinedStreams);
|
||||
StreamUtility.assertStreamEquals(combinedStreams, IntStream.concat(firstTwenty, nextTwenty));
|
||||
assertNotNull(combinedStreams);
|
||||
assertStreamEquals(combinedStreams, IntStream.concat(IntStream.range(1, 20), IntStream.range(21, 40)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findLastOfStream() {
|
||||
Optional<Integer> lastElement = Streams.findLast(numbers.stream());
|
||||
|
||||
Assert.assertNotNull(lastElement.get());
|
||||
Assert.assertEquals(lastElement.get(), numbers.get(20));
|
||||
assertEquals(lastElement.get(), numbers.get(19));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mapWithIndexTest() {
|
||||
Stream stringSream = Stream.of("a", "b", "c");
|
||||
Stream<String> stringStream = Stream.of("a", "b", "c");
|
||||
|
||||
Stream<String> mappedStream = Streams.mapWithIndex(stringSream, (str, index) -> str + ":" + index);
|
||||
Stream<String> mappedStream = Streams.mapWithIndex(stringStream, (str, index) -> str + ":" + index);
|
||||
|
||||
//Assert.assertNotNull(mappedStream);
|
||||
Assert.assertEquals(mappedStream
|
||||
assertEquals(mappedStream
|
||||
.findFirst()
|
||||
.get(), "a:0");
|
||||
|
||||
@ -144,12 +147,12 @@ public class GuavaStreamsUnitTest {
|
||||
|
||||
@Test
|
||||
public void streamsZipTest() {
|
||||
Stream stringSream = Stream.of("a", "b", "c");
|
||||
Stream intStream = Stream.of(1, 2, 3);
|
||||
Stream<String> stringSream = Stream.of("a", "b", "c");
|
||||
Stream<Integer> intStream = Stream.of(1, 2, 3);
|
||||
Stream<String> mappedStream = Streams.zip(stringSream, intStream, (str, index) -> str + ":" + index);
|
||||
|
||||
//Assert.assertNotNull(mappedStream);
|
||||
Assert.assertEquals(mappedStream
|
||||
assertEquals(mappedStream
|
||||
.findFirst()
|
||||
.get(), "a:1");
|
||||
|
@ -1,3 +1,5 @@
|
||||
package com.baeldung.guava.tutorial;
|
||||
|
||||
import com.google.common.collect.Interner;
|
||||
import com.google.common.collect.Interners;
|
||||
import org.junit.Assert;
|
@ -1,3 +1,5 @@
|
||||
package com.baeldung.guava.tutorial;
|
||||
|
||||
import com.google.common.util.concurrent.Monitor;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
@ -1,3 +1,5 @@
|
||||
package com.baeldung.guava.tutorial;
|
||||
|
||||
import com.google.common.collect.MoreCollectors;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
@ -1,3 +1,5 @@
|
||||
package com.baeldung.guava.tutorial;
|
||||
|
||||
import org.junit.Assert;
|
||||
|
||||
import java.util.Iterator;
|
@ -39,7 +39,7 @@
|
||||
|
||||
<properties>
|
||||
<javax.servlet.version>3.1.0</javax.servlet.version>
|
||||
<org.apache.httpcomponents.version>4.5.2</org.apache.httpcomponents.version>
|
||||
<org.apache.httpcomponents.version>4.5.3</org.apache.httpcomponents.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -1,24 +1,24 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.impl.client.DefaultHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class FormServletLiveTest {
|
||||
|
||||
@Test
|
||||
public void whenPostRequestUsingHttpClient_thenCorrect() throws Exception {
|
||||
|
||||
HttpClient client = new DefaultHttpClient();
|
||||
HttpClient client = HttpClientBuilder.create().build();
|
||||
HttpPost method = new HttpPost("http://localhost:8080/calculateServlet");
|
||||
|
||||
List<BasicNameValuePair> nvps = new ArrayList<>();
|
||||
|
@ -23,6 +23,6 @@
|
||||
|
||||
<properties>
|
||||
<!-- json-path -->
|
||||
<json-path.version>2.2.0</json-path.version>
|
||||
<json-path.version>2.4.0</json-path.version>
|
||||
</properties>
|
||||
</project>
|
@ -1,10 +1,10 @@
|
||||
package com.baeldung.jsonpath.introduction;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.hamcrest.CoreMatchers.not;
|
||||
|
||||
import com.jayway.jsonpath.Criteria;
|
||||
import com.jayway.jsonpath.DocumentContext;
|
||||
import com.jayway.jsonpath.Filter;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.jayway.jsonpath.Predicate;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.InputStream;
|
||||
@ -12,15 +12,14 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Scanner;
|
||||
|
||||
import com.jayway.jsonpath.Criteria;
|
||||
import com.jayway.jsonpath.DocumentContext;
|
||||
import com.jayway.jsonpath.Filter;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.jayway.jsonpath.Predicate;
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.hamcrest.CoreMatchers.not;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class OperationIntegrationTest {
|
||||
InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_api.json");
|
||||
String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next();
|
||||
private InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_api.json");
|
||||
private String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next();
|
||||
|
||||
@Test
|
||||
public void givenJsonPathWithoutPredicates_whenReading_thenCorrect() {
|
||||
@ -46,12 +45,7 @@ public class OperationIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenJsonPathWithCustomizedPredicate_whenReading_thenCorrect() {
|
||||
Predicate expensivePredicate = new Predicate() {
|
||||
public boolean apply(PredicateContext context) {
|
||||
String value = context.item(Map.class).get("price").toString();
|
||||
return Float.valueOf(value) > 20.00;
|
||||
}
|
||||
};
|
||||
Predicate expensivePredicate = context -> Float.valueOf(context.item(Map.class).get("price").toString()) > 20.00;
|
||||
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensivePredicate);
|
||||
predicateUsageAssertionHelper(expensive);
|
||||
}
|
||||
|
@ -1,9 +1,9 @@
|
||||
package com.baeldung.jsonpath.introduction;
|
||||
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
|
||||
import com.jayway.jsonpath.Configuration;
|
||||
import com.jayway.jsonpath.DocumentContext;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.jayway.jsonpath.Option;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.InputStream;
|
||||
@ -13,14 +13,13 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Scanner;
|
||||
|
||||
import com.jayway.jsonpath.Configuration;
|
||||
import com.jayway.jsonpath.DocumentContext;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.jayway.jsonpath.Option;
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class ServiceTest {
|
||||
InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_service.json");
|
||||
String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next();
|
||||
private InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_service.json");
|
||||
private String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next();
|
||||
|
||||
@Test
|
||||
public void givenId_whenRequestingRecordData_thenSucceed() {
|
||||
|
@ -4,3 +4,4 @@
|
||||
- [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests)
|
||||
- [A Guide to @RepeatedTest in Junit 5](http://www.baeldung.com/junit-5-repeated-test)
|
||||
- [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests)
|
||||
- [A Guied to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions)
|
||||
|
@ -19,14 +19,24 @@
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<junit.jupiter.version>5.0.0-M4</junit.jupiter.version>
|
||||
<junit.platform.version>1.0.0-M4</junit.platform.version>
|
||||
<junit.jupiter.version>5.0.0-M5</junit.jupiter.version>
|
||||
<junit.platform.version>1.0.0-M5</junit.platform.version>
|
||||
<junit.vintage.version>4.12.0-M5</junit.vintage.version>
|
||||
<log4j2.version>2.8.2</log4j2.version>
|
||||
<h2.version>1.4.196</h2.version>
|
||||
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<junit4.version>4.12</junit4.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/test/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
@ -47,6 +57,21 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>1.6.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>java</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.TestLauncher</mainClass>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
@ -57,5 +82,35 @@
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit.vintage.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>${log4j2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit4.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
48
junit5/src/test/java/com/baeldung/EmployeesTest.java
Normal file
48
junit5/src/test/java/com/baeldung/EmployeesTest.java
Normal file
@ -0,0 +1,48 @@
|
||||
package com.baeldung;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
|
||||
import com.baeldung.extensions.EmployeeDaoParameterResolver;
|
||||
import com.baeldung.extensions.EmployeeDatabaseSetupExtension;
|
||||
import com.baeldung.extensions.EnvironmentExtension;
|
||||
import com.baeldung.extensions.IgnoreFileNotFoundExceptionExtension;
|
||||
import com.baeldung.extensions.LoggingExtension;
|
||||
import com.baeldung.helpers.Employee;
|
||||
import com.baeldung.helpers.EmployeeJdbcDao;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@ExtendWith({ EnvironmentExtension.class, EmployeeDatabaseSetupExtension.class, EmployeeDaoParameterResolver.class })
|
||||
@ExtendWith(LoggingExtension.class)
|
||||
@ExtendWith(IgnoreFileNotFoundExceptionExtension.class)
|
||||
public class EmployeesTest {
|
||||
|
||||
private EmployeeJdbcDao employeeDao;
|
||||
|
||||
private Logger logger;
|
||||
|
||||
public EmployeesTest(EmployeeJdbcDao employeeDao) {
|
||||
this.employeeDao = employeeDao;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddEmployee_thenGetEmployee() throws SQLException {
|
||||
Employee emp = new Employee(1, "john");
|
||||
employeeDao.add(emp);
|
||||
assertEquals(1, employeeDao.findAll().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetEmployees_thenEmptyList() throws SQLException {
|
||||
assertEquals(0, employeeDao.findAll().size());
|
||||
}
|
||||
|
||||
public void setLogger(Logger logger) {
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
}
|
37
junit5/src/test/java/com/baeldung/TestLauncher.java
Normal file
37
junit5/src/test/java/com/baeldung/TestLauncher.java
Normal file
@ -0,0 +1,37 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.junit.platform.launcher.LauncherDiscoveryRequest;
|
||||
import org.junit.platform.launcher.TestExecutionListener;
|
||||
import org.junit.platform.launcher.TestPlan;
|
||||
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
|
||||
import org.junit.platform.launcher.core.LauncherFactory;
|
||||
import org.junit.platform.launcher.listeners.SummaryGeneratingListener;
|
||||
|
||||
import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
|
||||
import org.junit.platform.launcher.Launcher;
|
||||
|
||||
public class TestLauncher {
|
||||
public static void main(String[] args) {
|
||||
|
||||
//@formatter:off
|
||||
LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
|
||||
.selectors(selectClass("com.baeldung.EmployeesTest"))
|
||||
.configurationParameter("junit.conditions.deactivate", "com.baeldung.extensions.*")
|
||||
.configurationParameter("junit.extensions.autodetection.enabled", "true")
|
||||
.build();
|
||||
|
||||
//@formatter:on
|
||||
|
||||
TestPlan plan = LauncherFactory.create().discover(request);
|
||||
Launcher launcher = LauncherFactory.create();
|
||||
SummaryGeneratingListener summaryGeneratingListener = new SummaryGeneratingListener();
|
||||
launcher.execute(request, new TestExecutionListener[] { summaryGeneratingListener });
|
||||
launcher.execute(request);
|
||||
|
||||
summaryGeneratingListener.getSummary().printTo(new PrintWriter(System.out));
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.extensions;
|
||||
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
import org.junit.jupiter.api.extension.ParameterContext;
|
||||
import org.junit.jupiter.api.extension.ParameterResolutionException;
|
||||
import org.junit.jupiter.api.extension.ParameterResolver;
|
||||
|
||||
import com.baeldung.helpers.EmployeeJdbcDao;
|
||||
import com.baeldung.helpers.JdbcConnectionUtil;
|
||||
|
||||
public class EmployeeDaoParameterResolver implements ParameterResolver {
|
||||
|
||||
@Override
|
||||
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
|
||||
return parameterContext.getParameter().getType().equals(EmployeeJdbcDao.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
|
||||
return new EmployeeJdbcDao(JdbcConnectionUtil.getConnection());
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,46 @@
|
||||
package com.baeldung.extensions;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Savepoint;
|
||||
|
||||
import org.junit.jupiter.api.extension.AfterAllCallback;
|
||||
import org.junit.jupiter.api.extension.AfterEachCallback;
|
||||
import org.junit.jupiter.api.extension.BeforeAllCallback;
|
||||
import org.junit.jupiter.api.extension.BeforeEachCallback;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
|
||||
import com.baeldung.helpers.EmployeeJdbcDao;
|
||||
import com.baeldung.helpers.JdbcConnectionUtil;
|
||||
|
||||
public class EmployeeDatabaseSetupExtension implements BeforeAllCallback, AfterAllCallback, BeforeEachCallback, AfterEachCallback {
|
||||
|
||||
private Connection con = JdbcConnectionUtil.getConnection();
|
||||
private EmployeeJdbcDao employeeDao = new EmployeeJdbcDao(con);
|
||||
private Savepoint savepoint;
|
||||
|
||||
@Override
|
||||
public void afterAll(ExtensionContext context) throws SQLException {
|
||||
if (con != null) {
|
||||
con.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeAll(ExtensionContext context) throws SQLException {
|
||||
employeeDao.createTable();
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterEach(ExtensionContext context) throws SQLException {
|
||||
con.rollback(savepoint);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeEach(ExtensionContext context) throws SQLException {
|
||||
con.setAutoCommit(false);
|
||||
savepoint = con.setSavepoint("before");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.baeldung.extensions;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
|
||||
import org.junit.jupiter.api.extension.ExecutionCondition;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
|
||||
public class EnvironmentExtension implements ExecutionCondition {
|
||||
|
||||
@Override
|
||||
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
|
||||
Properties props = new Properties();
|
||||
|
||||
try {
|
||||
props.load(EnvironmentExtension.class.getResourceAsStream("application.properties"));
|
||||
String env = props.getProperty("env");
|
||||
if ("qa".equalsIgnoreCase(env)) {
|
||||
return ConditionEvaluationResult.disabled("Test disabled on QA environment");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return ConditionEvaluationResult.enabled("Test enabled on QA environment");
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.extensions;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
|
||||
|
||||
public class IgnoreFileNotFoundExceptionExtension implements TestExecutionExceptionHandler {
|
||||
|
||||
Logger logger = LogManager.getLogger(IgnoreFileNotFoundExceptionExtension.class);
|
||||
|
||||
@Override
|
||||
public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
|
||||
|
||||
if (throwable instanceof FileNotFoundException) {
|
||||
logger.error("File not found:" + throwable.getMessage());
|
||||
return;
|
||||
}
|
||||
throw throwable;
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
package com.baeldung.extensions;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
import org.junit.jupiter.api.extension.TestInstancePostProcessor;
|
||||
|
||||
public class LoggingExtension implements TestInstancePostProcessor {
|
||||
|
||||
@Override
|
||||
public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception {
|
||||
Logger logger = LogManager.getLogger(testInstance.getClass());
|
||||
testInstance.getClass().getMethod("setLogger", Logger.class).invoke(testInstance, logger);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
package com.baeldung.helpers;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
public class EmployeeJdbcDao {
|
||||
|
||||
private Connection con;
|
||||
|
||||
public EmployeeJdbcDao(Connection con) {
|
||||
this.con = con;
|
||||
}
|
||||
|
||||
public void createTable() throws SQLException {
|
||||
String createQuery = "CREATE TABLE employees(id long primary key, firstName varchar(50))";
|
||||
PreparedStatement pstmt = con.prepareStatement(createQuery);
|
||||
|
||||
pstmt.execute();
|
||||
}
|
||||
|
||||
public void add(Employee emp) throws SQLException {
|
||||
String insertQuery = "INSERT INTO employees(id, firstName) VALUES(?,?)";
|
||||
PreparedStatement pstmt = con.prepareStatement(insertQuery);
|
||||
pstmt.setLong(1, emp.getId());
|
||||
pstmt.setString(2, emp.getFirstName());
|
||||
|
||||
pstmt.executeUpdate();
|
||||
|
||||
}
|
||||
|
||||
public List<Employee> findAll() throws SQLException {
|
||||
List<Employee> employees = new ArrayList<>();
|
||||
String query = "SELECT * FROM employees";
|
||||
PreparedStatement pstmt = con.prepareStatement(query);
|
||||
|
||||
ResultSet rs = pstmt.executeQuery();
|
||||
while (rs.next()) {
|
||||
Employee emp = new Employee(rs.getLong("id"), rs.getString("firstName"));
|
||||
employees.add(emp);
|
||||
}
|
||||
|
||||
return employees;
|
||||
}
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
package com.baeldung.helpers;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Properties;
|
||||
|
||||
public class JdbcConnectionUtil {
|
||||
|
||||
private static Connection con;
|
||||
|
||||
public static Connection getConnection() {
|
||||
if (con == null) {
|
||||
try {
|
||||
Properties props = new Properties();
|
||||
props.load(JdbcConnectionUtil.class.getResourceAsStream("jdbc.properties"));
|
||||
Class.forName(props.getProperty("jdbc.driver"));
|
||||
con = DriverManager.getConnection(props.getProperty("jdbc.url"), props.getProperty("jdbc.user"), props.getProperty("jdbc.password"));
|
||||
return con;
|
||||
} catch (IOException exc) {
|
||||
exc.printStackTrace();
|
||||
} catch (ClassNotFoundException exc) {
|
||||
exc.printStackTrace();
|
||||
} catch (SQLException exc) {
|
||||
exc.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return con;
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.migration.junit4;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.junit.experimental.categories.Category;
|
||||
|
||||
import com.baeldung.migration.junit4.categories.Annotations;
|
||||
import com.baeldung.migration.junit4.categories.JUnit4Tests;
|
||||
|
||||
@Category(value = { Annotations.class, JUnit4Tests.class })
|
||||
public class AnnotationTestExampleTest {
|
||||
@Test(expected = Exception.class)
|
||||
public void shouldRaiseAnException() throws Exception {
|
||||
throw new Exception("This is my expected exception");
|
||||
}
|
||||
|
||||
@Test(timeout = 1)
|
||||
@Ignore
|
||||
public void shouldFailBecauseTimeout() throws InterruptedException {
|
||||
Thread.sleep(10);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.baeldung.migration.junit4;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class AssertionsExampleTest {
|
||||
@Test
|
||||
@Ignore
|
||||
public void shouldFailBecauseTheNumbersAreNotEqualld() {
|
||||
assertEquals("Numbers are not equal!", 2, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldAssertAllTheGroup() {
|
||||
List<Integer> list = Arrays.asList(1, 2, 3);
|
||||
assertEquals("List is not incremental", list.get(0)
|
||||
.intValue(), 1);
|
||||
assertEquals("List is not incremental", list.get(1)
|
||||
.intValue(), 2);
|
||||
assertEquals("List is not incremental", list.get(2)
|
||||
.intValue(), 3);
|
||||
}
|
||||
}
|
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