Merge branch 'master' into bael-1908
This commit is contained in:
commit
c23c12831c
|
@ -1,3 +0,0 @@
|
|||
[submodule "testgitrepo"]
|
||||
path = testgitrepo
|
||||
url = /home/prd/Development/projects/idea/tutorials/spring-boot/src/main/resources/testgitrepo/
|
|
@ -22,3 +22,6 @@
|
|||
- [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words)
|
||||
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)
|
||||
- [Find All Pairs of Numbers in an Array That Add Up to a Given Sum](http://www.baeldung.com/java-algorithm-number-pairs-sum)
|
||||
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
|
||||
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
|
||||
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
|
||||
|
|
|
@ -10,7 +10,7 @@ public class MonteCarloTreeSearch {
|
|||
|
||||
private static final int WIN_SCORE = 10;
|
||||
private int level;
|
||||
private int oponent;
|
||||
private int opponent;
|
||||
|
||||
public MonteCarloTreeSearch() {
|
||||
this.level = 3;
|
||||
|
@ -32,11 +32,11 @@ public class MonteCarloTreeSearch {
|
|||
long start = System.currentTimeMillis();
|
||||
long end = start + 60 * getMillisForCurrentLevel();
|
||||
|
||||
oponent = 3 - playerNo;
|
||||
opponent = 3 - playerNo;
|
||||
Tree tree = new Tree();
|
||||
Node rootNode = tree.getRoot();
|
||||
rootNode.getState().setBoard(board);
|
||||
rootNode.getState().setPlayerNo(oponent);
|
||||
rootNode.getState().setPlayerNo(opponent);
|
||||
|
||||
while (System.currentTimeMillis() < end) {
|
||||
// Phase 1 - Selection
|
||||
|
@ -93,7 +93,7 @@ public class MonteCarloTreeSearch {
|
|||
State tempState = tempNode.getState();
|
||||
int boardStatus = tempState.getBoard().checkStatus();
|
||||
|
||||
if (boardStatus == oponent) {
|
||||
if (boardStatus == opponent) {
|
||||
tempNode.getParent().getState().setWinScore(Integer.MIN_VALUE);
|
||||
return boardStatus;
|
||||
}
|
||||
|
|
|
@ -0,0 +1,52 @@
|
|||
package com.baeldung.algorithms.romannumerals;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
class RomanArabicConverter {
|
||||
|
||||
public static int romanToArabic(String input) {
|
||||
String romanNumeral = input.toUpperCase();
|
||||
int result = 0;
|
||||
|
||||
List<RomanNumeral> romanNumerals = RomanNumeral.getReverseSortedValues();
|
||||
|
||||
int i = 0;
|
||||
|
||||
while ((romanNumeral.length() > 0) && (i < romanNumerals.size())) {
|
||||
RomanNumeral symbol = romanNumerals.get(i);
|
||||
if (romanNumeral.startsWith(symbol.name())) {
|
||||
result += symbol.getValue();
|
||||
romanNumeral = romanNumeral.substring(symbol.name().length());
|
||||
} else {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
if (romanNumeral.length() > 0) {
|
||||
throw new IllegalArgumentException(input + " cannot be converted to a Roman Numeral");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static String arabicToRoman(int number) {
|
||||
if ((number <= 0) || (number > 4000)) {
|
||||
throw new IllegalArgumentException(number + " is not in range (0,4000]");
|
||||
}
|
||||
|
||||
List<RomanNumeral> romanNumerals = RomanNumeral.getReverseSortedValues();
|
||||
|
||||
int i = 0;
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
while (number > 0 && i < romanNumerals.size()) {
|
||||
RomanNumeral currentSymbol = romanNumerals.get(i);
|
||||
if (currentSymbol.getValue() <= number) {
|
||||
sb.append(currentSymbol.name());
|
||||
number -= currentSymbol.getValue();
|
||||
} else {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.algorithms.romannumerals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
enum RomanNumeral {
|
||||
I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000);
|
||||
|
||||
private int value;
|
||||
|
||||
RomanNumeral(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public static List<RomanNumeral> getReverseSortedValues() {
|
||||
return Arrays.stream(values())
|
||||
.sorted(Comparator.comparing((RomanNumeral e) -> e.value).reversed())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.algorithms.romannumerals;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RomanArabicConverterUnitTest {
|
||||
|
||||
@Test
|
||||
public void given2018Roman_WhenConvertingToArabic_ThenReturn2018() {
|
||||
|
||||
String roman2018 = "MMXVIII";
|
||||
|
||||
int result = RomanArabicConverter.romanToArabic(roman2018);
|
||||
|
||||
assertThat(result).isEqualTo(2018);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given1999Arabic_WhenConvertingToRoman_ThenReturnMCMXCIX() {
|
||||
|
||||
int arabic1999 = 1999;
|
||||
|
||||
String result = RomanArabicConverter.arabicToRoman(arabic1999);
|
||||
|
||||
assertThat(result).isEqualTo("MCMXCIX");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Java with ANTLR](http://www.baeldung.com/java-antlr)
|
|
@ -0,0 +1,57 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-meecrowave</artifactId>
|
||||
<version>0.0.1</version>
|
||||
<name>apache-meecrowave</name>
|
||||
<description>A sample REST API application with Meecrowave</description>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.meecrowave/meecrowave-core -->
|
||||
<dependency>
|
||||
<groupId>org.apache.meecrowave</groupId>
|
||||
<artifactId>meecrowave-core</artifactId>
|
||||
<version>1.2.1</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.meecrowave/meecrowave-jpa -->
|
||||
<dependency>
|
||||
<groupId>org.apache.meecrowave</groupId>
|
||||
<artifactId>meecrowave-jpa</artifactId>
|
||||
<version>1.2.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
<version>3.10.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.meecrowave</groupId>
|
||||
<artifactId>meecrowave-junit</artifactId>
|
||||
<version>1.2.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/junit/junit -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.10</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.meecrowave</groupId>
|
||||
<artifactId>meecrowave-maven-plugin</artifactId>
|
||||
<version>1.2.1</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.meecrowave;
|
||||
|
||||
public class Article {
|
||||
private String name;
|
||||
private String author;
|
||||
|
||||
public Article() {
|
||||
}
|
||||
|
||||
public Article(String name, String author) {
|
||||
this.author = author;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public void setAuthor(String author) {
|
||||
this.author = author;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.meecrowave;
|
||||
|
||||
import javax.enterprise.context.RequestScoped;
|
||||
import javax.inject.Inject;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
|
||||
@RequestScoped
|
||||
@Path("article")
|
||||
public class ArticleEndpoints {
|
||||
|
||||
@Inject
|
||||
ArticleService articleService;
|
||||
|
||||
@GET
|
||||
public Response getArticle() {
|
||||
return Response.ok()
|
||||
.entity(new Article("name", "author"))
|
||||
.build();
|
||||
|
||||
}
|
||||
|
||||
@POST
|
||||
public Response createArticle(Article article) {
|
||||
return Response.status(Status.CREATED)
|
||||
.entity(articleService.createArticle(article))
|
||||
.build();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.meecrowave;
|
||||
|
||||
import javax.enterprise.context.ApplicationScoped;
|
||||
|
||||
@ApplicationScoped
|
||||
public class ArticleService {
|
||||
public Article createArticle(Article article) {
|
||||
return article;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.meecrowave;
|
||||
|
||||
import org.apache.meecrowave.Meecrowave;
|
||||
|
||||
public class Server {
|
||||
public static void main(String[] args) {
|
||||
final Meecrowave.Builder builder = new Meecrowave.Builder();
|
||||
builder.setScanningPackageIncludes("com.baeldung.meecrowave");
|
||||
builder.setJaxrsMapping("/api/*");
|
||||
builder.setJsonpPrettify(true);
|
||||
|
||||
try (Meecrowave meecrowave = new Meecrowave(builder)) {
|
||||
meecrowave.bake().await();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.meecrowave;
|
||||
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.meecrowave.Meecrowave;
|
||||
import org.apache.meecrowave.junit.MonoMeecrowave;
|
||||
import org.apache.meecrowave.testing.ConfigurationInject;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
@RunWith(MonoMeecrowave.Runner.class)
|
||||
public class ArticleEndpointsTest {
|
||||
|
||||
@ConfigurationInject
|
||||
private Meecrowave.Builder config;
|
||||
private static OkHttpClient client;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
client = new OkHttpClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRetunedArticle_thenCorrect() throws IOException {
|
||||
final String base = "http://localhost:"+config.getHttpPort();
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(base+"/article")
|
||||
.build();
|
||||
Response response = client.newCall(request).execute();
|
||||
assertEquals(200, response.code());
|
||||
}
|
||||
}
|
|
@ -12,7 +12,7 @@ import org.apache.solr.common.SolrDocumentList;
|
|||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SolrJavaIntegrationTest {
|
||||
public class SolrJavaLiveTest {
|
||||
|
||||
private SolrJavaIntegration solrJavaIntegration;
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant Articles:
|
||||
- [Using AWS Lambda with API Gateway](http://www.baeldung.com/aws-lambda-api-gateway)
|
||||
- [Introduction to AWS Serverless Application Model](http://www.baeldung.com/aws-serverless)
|
|
@ -0,0 +1,60 @@
|
|||
AWSTemplateFormatVersion: '2010-09-09'
|
||||
Transform: 'AWS::Serverless-2016-10-31'
|
||||
Description: Baeldung Serverless Application Model Example with Implicit API Definition
|
||||
Globals:
|
||||
Api:
|
||||
EndpointConfiguration: REGIONAL
|
||||
Name: "TestAPI"
|
||||
Resources:
|
||||
PersonTable:
|
||||
Type: AWS::Serverless::SimpleTable
|
||||
Properties:
|
||||
PrimaryKey:
|
||||
Name: id
|
||||
Type: Number
|
||||
TableName: Person
|
||||
StorePersonFunction:
|
||||
Type: AWS::Serverless::Function
|
||||
Properties:
|
||||
Handler: com.baeldung.lambda.apigateway.APIDemoHandler::handleRequest
|
||||
Runtime: java8
|
||||
Timeout: 15
|
||||
MemorySize: 512
|
||||
CodeUri: ../target/aws-lambda-0.1.0-SNAPSHOT.jar
|
||||
Policies:
|
||||
- DynamoDBCrudPolicy:
|
||||
TableName: !Ref PersonTable
|
||||
Environment:
|
||||
Variables:
|
||||
TABLE_NAME: !Ref PersonTable
|
||||
Events:
|
||||
StoreApi:
|
||||
Type: Api
|
||||
Properties:
|
||||
Path: /persons
|
||||
Method: PUT
|
||||
GetPersonByHTTPParamFunction:
|
||||
Type: AWS::Serverless::Function
|
||||
Properties:
|
||||
Handler: com.baeldung.lambda.apigateway.APIDemoHandler::handleGetByParam
|
||||
Runtime: java8
|
||||
Timeout: 15
|
||||
MemorySize: 512
|
||||
CodeUri: ../target/aws-lambda-0.1.0-SNAPSHOT.jar
|
||||
Policies:
|
||||
- DynamoDBReadPolicy:
|
||||
TableName: !Ref PersonTable
|
||||
Environment:
|
||||
Variables:
|
||||
TABLE_NAME: !Ref PersonTable
|
||||
Events:
|
||||
GetByPathApi:
|
||||
Type: Api
|
||||
Properties:
|
||||
Path: /persons/{id}
|
||||
Method: GET
|
||||
GetByQueryApi:
|
||||
Type: Api
|
||||
Properties:
|
||||
Path: /persons
|
||||
Method: GET
|
|
@ -0,0 +1,112 @@
|
|||
AWSTemplateFormatVersion: '2010-09-09'
|
||||
Transform: 'AWS::Serverless-2016-10-31'
|
||||
Description: Baeldung Serverless Application Model Example with Inline Swagger API Definition
|
||||
Resources:
|
||||
PersonTable:
|
||||
Type: AWS::Serverless::SimpleTable
|
||||
Properties:
|
||||
PrimaryKey:
|
||||
Name: id
|
||||
Type: Number
|
||||
TableName: Person
|
||||
StorePersonFunction:
|
||||
Type: AWS::Serverless::Function
|
||||
Properties:
|
||||
Handler: com.baeldung.lambda.apigateway.APIDemoHandler::handleRequest
|
||||
Runtime: java8
|
||||
Timeout: 15
|
||||
MemorySize: 512
|
||||
CodeUri: ../target/aws-lambda-0.1.0-SNAPSHOT.jar
|
||||
Policies:
|
||||
- DynamoDBCrudPolicy:
|
||||
TableName: !Ref PersonTable
|
||||
Environment:
|
||||
Variables:
|
||||
TABLE_NAME: !Ref PersonTable
|
||||
Events:
|
||||
StoreApi:
|
||||
Type: Api
|
||||
Properties:
|
||||
Path: /persons
|
||||
Method: PUT
|
||||
RestApiId:
|
||||
Ref: MyApi
|
||||
GetPersonByHTTPParamFunction:
|
||||
Type: AWS::Serverless::Function
|
||||
Properties:
|
||||
Handler: com.baeldung.lambda.apigateway.APIDemoHandler::handleGetByParam
|
||||
Runtime: java8
|
||||
Timeout: 15
|
||||
MemorySize: 512
|
||||
CodeUri: ../target/aws-lambda-0.1.0-SNAPSHOT.jar
|
||||
Policies:
|
||||
- DynamoDBReadPolicy:
|
||||
TableName: !Ref PersonTable
|
||||
Environment:
|
||||
Variables:
|
||||
TABLE_NAME: !Ref PersonTable
|
||||
Events:
|
||||
GetByPathApi:
|
||||
Type: Api
|
||||
Properties:
|
||||
Path: /persons/{id}
|
||||
Method: GET
|
||||
RestApiId:
|
||||
Ref: MyApi
|
||||
GetByQueryApi:
|
||||
Type: Api
|
||||
Properties:
|
||||
Path: /persons
|
||||
Method: GET
|
||||
RestApiId:
|
||||
Ref: MyApi
|
||||
MyApi:
|
||||
Type: AWS::Serverless::Api
|
||||
Properties:
|
||||
StageName: test
|
||||
EndpointConfiguration: REGIONAL
|
||||
DefinitionBody:
|
||||
swagger: "2.0"
|
||||
info:
|
||||
title: "TestAPI"
|
||||
paths:
|
||||
/persons:
|
||||
get:
|
||||
parameters:
|
||||
- name: "id"
|
||||
in: "query"
|
||||
required: true
|
||||
type: "string"
|
||||
x-amazon-apigateway-request-validator: "Validate query string parameters and\
|
||||
\ headers"
|
||||
x-amazon-apigateway-integration:
|
||||
uri:
|
||||
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${GetPersonByHTTPParamFunction.Arn}/invocations
|
||||
responses: {}
|
||||
httpMethod: "POST"
|
||||
type: "aws_proxy"
|
||||
put:
|
||||
x-amazon-apigateway-integration:
|
||||
uri:
|
||||
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${StorePersonFunction.Arn}/invocations
|
||||
responses: {}
|
||||
httpMethod: "POST"
|
||||
type: "aws_proxy"
|
||||
/persons/{id}:
|
||||
get:
|
||||
parameters:
|
||||
- name: "id"
|
||||
in: "path"
|
||||
required: true
|
||||
type: "string"
|
||||
responses: {}
|
||||
x-amazon-apigateway-integration:
|
||||
uri:
|
||||
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${GetPersonByHTTPParamFunction.Arn}/invocations
|
||||
responses: {}
|
||||
httpMethod: "POST"
|
||||
type: "aws_proxy"
|
||||
x-amazon-apigateway-request-validators:
|
||||
Validate query string parameters and headers:
|
||||
validateRequestParameters: true
|
||||
validateRequestBody: false
|
|
@ -36,9 +36,7 @@ public class APIDemoHandler implements RequestStreamHandler {
|
|||
|
||||
dynamoDb.getTable(DYNAMODB_TABLE_NAME)
|
||||
.putItem(new PutItemSpec().withItem(new Item().withNumber("id", person.getId())
|
||||
.withString("firstName", person.getFirstName())
|
||||
.withString("lastName", person.getLastName()).withNumber("age", person.getAge())
|
||||
.withString("address", person.getAddress())));
|
||||
.withString("name", person.getName())));
|
||||
}
|
||||
|
||||
JSONObject responseBody = new JSONObject();
|
||||
|
@ -61,8 +59,7 @@ public class APIDemoHandler implements RequestStreamHandler {
|
|||
writer.close();
|
||||
}
|
||||
|
||||
public void handleGetByPathParam(InputStream inputStream, OutputStream outputStream, Context context)
|
||||
throws IOException {
|
||||
public void handleGetByParam(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
|
||||
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
|
||||
JSONObject responseJson = new JSONObject();
|
||||
|
@ -81,61 +78,20 @@ public class APIDemoHandler implements RequestStreamHandler {
|
|||
if (pps.get("id") != null) {
|
||||
|
||||
int id = Integer.parseInt((String) pps.get("id"));
|
||||
result = dynamoDb.getTable(DYNAMODB_TABLE_NAME).getItem("id", id);
|
||||
result = dynamoDb.getTable(DYNAMODB_TABLE_NAME)
|
||||
.getItem("id", id);
|
||||
}
|
||||
|
||||
}
|
||||
if (result != null) {
|
||||
|
||||
Person person = new Person(result.toJSON());
|
||||
responseBody.put("Person", person);
|
||||
responseJson.put("statusCode", 200);
|
||||
} else {
|
||||
|
||||
responseBody.put("message", "No item found");
|
||||
responseJson.put("statusCode", 404);
|
||||
}
|
||||
|
||||
JSONObject headerJson = new JSONObject();
|
||||
headerJson.put("x-custom-header", "my custom header value");
|
||||
|
||||
responseJson.put("headers", headerJson);
|
||||
responseJson.put("body", responseBody.toString());
|
||||
|
||||
} catch (ParseException pex) {
|
||||
responseJson.put("statusCode", 400);
|
||||
responseJson.put("exception", pex);
|
||||
}
|
||||
|
||||
OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
|
||||
writer.write(responseJson.toString());
|
||||
writer.close();
|
||||
}
|
||||
|
||||
public void handleGetByQueryParam(InputStream inputStream, OutputStream outputStream, Context context)
|
||||
throws IOException {
|
||||
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
|
||||
JSONObject responseJson = new JSONObject();
|
||||
|
||||
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient();
|
||||
DynamoDB dynamoDb = new DynamoDB(client);
|
||||
|
||||
Item result = null;
|
||||
try {
|
||||
JSONObject event = (JSONObject) parser.parse(reader);
|
||||
JSONObject responseBody = new JSONObject();
|
||||
|
||||
if (event.get("queryStringParameters") != null) {
|
||||
} else if (event.get("queryStringParameters") != null) {
|
||||
|
||||
JSONObject qps = (JSONObject) event.get("queryStringParameters");
|
||||
if (qps.get("id") != null) {
|
||||
|
||||
int id = Integer.parseInt((String) qps.get("id"));
|
||||
result = dynamoDb.getTable(DYNAMODB_TABLE_NAME).getItem("id", id);
|
||||
result = dynamoDb.getTable(DYNAMODB_TABLE_NAME)
|
||||
.getItem("id", id);
|
||||
}
|
||||
}
|
||||
|
||||
if (result != null) {
|
||||
|
||||
Person person = new Person(result.toJSON());
|
||||
|
@ -162,5 +118,4 @@ public class APIDemoHandler implements RequestStreamHandler {
|
|||
writer.write(responseJson.toString());
|
||||
writer.close();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -6,19 +6,13 @@ import com.google.gson.GsonBuilder;
|
|||
public class Person {
|
||||
|
||||
private int id;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private int age;
|
||||
private String address;
|
||||
private String name;
|
||||
|
||||
public Person(String json) {
|
||||
Gson gson = new Gson();
|
||||
Person request = gson.fromJson(json, Person.class);
|
||||
this.id = request.getId();
|
||||
this.firstName = request.getFirstName();
|
||||
this.lastName = request.getLastName();
|
||||
this.age = request.getAge();
|
||||
this.address = request.getAddress();
|
||||
this.name = request.getName();
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
|
@ -34,35 +28,11 @@ public class Person {
|
|||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd"
|
||||
xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd">
|
||||
<description>Baeldung custom PMD rules</description>
|
||||
<rule name="UnitTestMustFollowNamingConventionRule" message="Test class name doesn't follow the naming convention" class="org.baeldung.pmd.UnitTestNamingConventionRule">
|
||||
<rule name="UnitTestMustFollowNamingConventionRule" message="Unit test class names need to end in 'UnitTest', integration tests with 'IntegrationTest', etc " class="org.baeldung.pmd.UnitTestNamingConventionRule">
|
||||
<description>Test does not follow Baeldung naming convention</description>
|
||||
<priority>3</priority>
|
||||
</rule>
|
||||
|
|
|
@ -1,2 +1,3 @@
|
|||
### Relevant Articles:
|
||||
- [CDI Interceptor vs Spring AspectJ](http://www.baeldung.com/cdi-interceptor-vs-spring-aspectj)
|
||||
- [An Introduction to CDI (Contexts and Dependency Injection) in Java](http://www.baeldung.com/java-ee-cdi)
|
||||
|
|
|
@ -54,3 +54,5 @@
|
|||
- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
|
||||
- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection)
|
||||
- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic)
|
||||
- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
|
||||
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
|
||||
|
|
|
@ -0,0 +1,54 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
import org.apache.commons.lang3.time.DateUtils;
|
||||
|
||||
public class AddHoursToDate {
|
||||
|
||||
public Date addHoursToJavaUtilDate(Date date, int hours) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
calendar.add(Calendar.HOUR_OF_DAY, hours);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public Date addHoursToDateUsingInstant(Date date, int hours) {
|
||||
return Date.from(date.toInstant()
|
||||
.plus(Duration.ofHours(hours)));
|
||||
}
|
||||
|
||||
public LocalDateTime addHoursToLocalDateTime(LocalDateTime localDateTime, int hours) {
|
||||
return localDateTime.plusHours(hours);
|
||||
}
|
||||
|
||||
public LocalDateTime subtractHoursToLocalDateTime(LocalDateTime localDateTime, int hours) {
|
||||
return localDateTime.minusHours(hours);
|
||||
}
|
||||
|
||||
public ZonedDateTime addHoursToZonedDateTime(ZonedDateTime zonedDateTime, int hours) {
|
||||
return zonedDateTime.plusHours(hours);
|
||||
}
|
||||
|
||||
public ZonedDateTime subtractHoursToZonedDateTime(ZonedDateTime zonedDateTime, int hours) {
|
||||
return zonedDateTime.minusHours(hours);
|
||||
}
|
||||
|
||||
public Instant addHoursToInstant(Instant instant, int hours) {
|
||||
return instant.plus(hours, ChronoUnit.HOURS);
|
||||
}
|
||||
|
||||
public Instant subtractHoursToInstant(Instant instant, int hours) {
|
||||
return instant.minus(hours, ChronoUnit.HOURS);
|
||||
}
|
||||
|
||||
public Date addHoursWithApacheCommons(Date date, int hours) {
|
||||
return DateUtils.addHours(date, hours);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,116 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Month;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class AddHoursToDateUnitTest {
|
||||
|
||||
private final AddHoursToDate addHoursToDateObj = new AddHoursToDate();
|
||||
|
||||
@Test
|
||||
public void givenJavaUtilDate_whenPositiveHours_thenAddHours() {
|
||||
Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime();
|
||||
Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 7, 0).getTime();
|
||||
|
||||
assertThat(addHoursToDateObj.addHoursToJavaUtilDate(actualDate, 2)).isEqualTo(expectedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJavaUtilDate_whenNegativeHours_thenMinusHours() {
|
||||
Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime();
|
||||
Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 3, 0).getTime();
|
||||
|
||||
assertThat(addHoursToDateObj.addHoursToJavaUtilDate(actualDate, -2)).isEqualTo(expectedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJavaUtilDate_whenUsingToInstantAndPostiveHours_thenAddHours() {
|
||||
Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime();
|
||||
Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 7, 0).getTime();
|
||||
|
||||
assertThat(addHoursToDateObj.addHoursToDateUsingInstant(actualDate, 2)).isEqualTo(expectedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJavaUtilDate_whenUsingToInstantAndNegativeHours_thenAddHours() {
|
||||
Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime();
|
||||
Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 3, 0).getTime();
|
||||
|
||||
assertThat(addHoursToDateObj.addHoursToDateUsingInstant(actualDate, -2)).isEqualTo(expectedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDateTime_whenUsingAddHoursToLocalDateTime_thenAddHours() {
|
||||
LocalDateTime actualDateTime = LocalDateTime.of(2018, Month.JUNE, 25, 5, 0);
|
||||
LocalDateTime expectedDateTime = LocalDateTime.of(2018, Month.JUNE, 25, 7, 0);
|
||||
|
||||
assertThat(addHoursToDateObj.addHoursToLocalDateTime(actualDateTime, 2)).isEqualTo(expectedDateTime);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDateTime_whenUsingMinusHoursToLocalDateTime_thenMinusHours() {
|
||||
LocalDateTime actualDateTime = LocalDateTime.of(2018, Month.JUNE, 25, 5, 0);
|
||||
LocalDateTime expectedDateTime = LocalDateTime.of(2018, Month.JUNE, 25, 3, 0);
|
||||
|
||||
assertThat(addHoursToDateObj.subtractHoursToLocalDateTime(actualDateTime, 2)).isEqualTo(expectedDateTime);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenZonedDateTime_whenUsingAddHoursToZonedDateTime_thenAddHours() {
|
||||
ZonedDateTime actualZonedDateTime = ZonedDateTime.of(LocalDateTime.of(2018, Month.JUNE, 25, 5, 0), ZoneId.systemDefault());
|
||||
ZonedDateTime expectedZonedDateTime = ZonedDateTime.of(LocalDateTime.of(2018, Month.JUNE, 25, 7, 0), ZoneId.systemDefault());
|
||||
|
||||
assertThat(addHoursToDateObj.addHoursToZonedDateTime(actualZonedDateTime, 2)).isEqualTo(expectedZonedDateTime);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenZonedDateTime_whenUsingMinusHoursToZonedDateTime_thenMinusHours() {
|
||||
ZonedDateTime actualZonedDateTime = ZonedDateTime.of(LocalDateTime.of(2018, Month.JUNE, 25, 5, 0), ZoneId.systemDefault());
|
||||
ZonedDateTime expectedZonedDateTime = ZonedDateTime.of(LocalDateTime.of(2018, Month.JUNE, 25, 3, 0), ZoneId.systemDefault());
|
||||
|
||||
assertThat(addHoursToDateObj.subtractHoursToZonedDateTime(actualZonedDateTime, 2)).isEqualTo(expectedZonedDateTime);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJavaUtilDate_whenUsingPositiveHrsAndAddHoursWithApacheCommons_thenAddHours() {
|
||||
Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime();
|
||||
Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 7, 0).getTime();
|
||||
|
||||
assertThat(addHoursToDateObj.addHoursWithApacheCommons(actualDate, 2)).isEqualTo(expectedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJavaUtilDate_whenUsingNegativeHrsAndAddHoursWithApacheCommons_thenMinusHours() {
|
||||
Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 7, 0).getTime();
|
||||
Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime();
|
||||
|
||||
assertThat(addHoursToDateObj.addHoursWithApacheCommons(actualDate, -2)).isEqualTo(expectedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInstant_whenUsingAddHoursToInstant_thenAddHours() {
|
||||
Instant actualValue = Instant.parse("2018-06-25T05:12:35Z");
|
||||
Instant expectedValue = Instant.parse("2018-06-25T07:12:35Z");
|
||||
|
||||
assertThat(addHoursToDateObj.addHoursToInstant(actualValue, 2)).isEqualTo(expectedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInstant_whenUsingSubtractHoursToInstant_thenMinusHours() {
|
||||
Instant actualValue = Instant.parse("2018-06-25T07:12:35Z");
|
||||
Instant expectedValue = Instant.parse("2018-06-25T05:12:35Z");
|
||||
|
||||
assertThat(addHoursToDateObj.subtractHoursToInstant(actualValue, 2)).isEqualTo(expectedValue);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.fileToBase64StringConversion;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileToBase64StringConversionUnitTest {
|
||||
|
||||
private String inputFilePath = "test_image.jpg";
|
||||
private String outputFilePath = "test_image_copy.jpg";
|
||||
|
||||
@Test
|
||||
public void fileToBase64StringConversion() throws IOException {
|
||||
//load file from /src/test/resources
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
File inputFile = new File(classLoader
|
||||
.getResource(inputFilePath)
|
||||
.getFile());
|
||||
|
||||
byte[] fileContent = FileUtils.readFileToByteArray(inputFile);
|
||||
String encodedString = Base64
|
||||
.getEncoder()
|
||||
.encodeToString(fileContent);
|
||||
|
||||
//create output file
|
||||
File outputFile = new File(inputFile
|
||||
.getParentFile()
|
||||
.getAbsolutePath() + File.pathSeparator + outputFilePath);
|
||||
|
||||
// decode the string and write to file
|
||||
byte[] decodedBytes = Base64
|
||||
.getDecoder()
|
||||
.decode(encodedString);
|
||||
FileUtils.writeByteArrayToFile(outputFile, decodedBytes);
|
||||
|
||||
assertTrue(FileUtils.contentEquals(inputFile, outputFile));
|
||||
}
|
||||
}
|
Binary file not shown.
After Width: | Height: | Size: 2.8 KiB |
|
@ -0,0 +1,80 @@
|
|||
package com.baeldung.java.list;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
|
||||
import org.apache.commons.collections4.iterators.ReverseListIterator;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
/**
|
||||
* Provides methods for iterating backward over a list.
|
||||
*/
|
||||
public class ReverseIterator {
|
||||
|
||||
/**
|
||||
* Iterate using the for loop.
|
||||
*
|
||||
* @param list the list
|
||||
*/
|
||||
public void iterateUsingForLoop(final List<String> list) {
|
||||
|
||||
for (int i = list.size(); i-- > 0; ) {
|
||||
System.out.println(list.get(i));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate using the Java {@link ListIterator}.
|
||||
*
|
||||
* @param list the list
|
||||
*/
|
||||
public void iterateUsingListIterator(final List<String> list) {
|
||||
|
||||
final ListIterator listIterator = list.listIterator(list.size());
|
||||
while (listIterator.hasPrevious()) {
|
||||
System.out.println(listIterator.previous());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate using Java {@link Collections} API.
|
||||
*
|
||||
* @param list the list
|
||||
*/
|
||||
public void iterateUsingCollections(final List<String> list) {
|
||||
|
||||
Collections.reverse(list);
|
||||
for (final String item : list) {
|
||||
System.out.println(item);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate using Apache Commons {@link ReverseListIterator}.
|
||||
*
|
||||
* @param list the list
|
||||
*/
|
||||
public void iterateUsingApacheReverseListIterator(final List<String> list) {
|
||||
|
||||
final ReverseListIterator listIterator = new ReverseListIterator(list);
|
||||
while (listIterator.hasNext()) {
|
||||
System.out.println(listIterator.next());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate using Guava {@link Lists} API.
|
||||
*
|
||||
* @param list the list
|
||||
*/
|
||||
public void iterateUsingGuava(final List<String> list) {
|
||||
|
||||
final List<String> reversedList = Lists.reverse(list);
|
||||
for (final String item : reversedList) {
|
||||
System.out.println(item);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,87 @@
|
|||
package com.baeldung.java.list;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
|
||||
import org.apache.commons.collections4.iterators.ReverseListIterator;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class ReverseIteratorUnitTest {
|
||||
|
||||
private final ReverseIterator reverseIterator = new ReverseIterator();
|
||||
|
||||
private List<String> list;
|
||||
|
||||
private final String originalString = "ABCDE";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
|
||||
list = Lists.newArrayList("A", "B", "C", "D", "E");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIteratingUsingForLoop_thenCorrect() {
|
||||
|
||||
String reverseString = "";
|
||||
for (int i = list.size(); i-- > 0; ) {
|
||||
reverseString += list.get(i);
|
||||
}
|
||||
assertEquals(reverseString, StringUtils.reverse(originalString));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIteratingUsingListIterator_thenCorrect() {
|
||||
|
||||
String reverseString = "";
|
||||
final ListIterator listIterator = list.listIterator(list.size());
|
||||
while (listIterator.hasPrevious()) {
|
||||
reverseString += listIterator.previous();
|
||||
}
|
||||
assertEquals(reverseString, StringUtils.reverse(originalString));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIteratingUsingCollections_thenCorrect() {
|
||||
|
||||
String reverseString = "";
|
||||
Collections.reverse(list);
|
||||
for (final String item : list) {
|
||||
reverseString += item;
|
||||
}
|
||||
assertEquals(reverseString, StringUtils.reverse(originalString));
|
||||
|
||||
assertEquals("E", list.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIteratingUsingApacheReverseListIterator_thenCorrect() {
|
||||
|
||||
String reverseString = "";
|
||||
final ReverseListIterator listIterator = new ReverseListIterator(list);
|
||||
while (listIterator.hasNext()) {
|
||||
reverseString += listIterator.next();
|
||||
}
|
||||
assertEquals(reverseString, StringUtils.reverse(originalString));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIteratingUsingGuava_thenCorrect() {
|
||||
|
||||
String reverseString = "";
|
||||
final List<String> reversedList = Lists.reverse(list);
|
||||
for (final String item : reversedList) {
|
||||
reverseString += item;
|
||||
}
|
||||
assertEquals(reverseString, StringUtils.reverse(originalString));
|
||||
|
||||
assertEquals("A", list.get(0));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
package com.baeldung.symlink;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.DirectoryStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import static java.nio.file.StandardOpenOption.*;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class SymLinkExample {
|
||||
|
||||
public void createSymbolicLink(Path link, Path target) throws IOException {
|
||||
if (Files.exists(link)) {
|
||||
Files.delete(link);
|
||||
}
|
||||
Files.createSymbolicLink(link, target);
|
||||
}
|
||||
|
||||
public void createHardLink(Path link, Path target) throws IOException {
|
||||
if (Files.exists(link)) {
|
||||
Files.delete(link);
|
||||
}
|
||||
Files.createLink(link, target);
|
||||
}
|
||||
|
||||
public Path createTextFile() throws IOException {
|
||||
byte[] content = IntStream.range(0, 10000)
|
||||
.mapToObj(i -> i + System.lineSeparator())
|
||||
.reduce("", String::concat)
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
Path filePath = Paths.get(".", "target_link.txt");
|
||||
Files.write(filePath, content, CREATE, TRUNCATE_EXISTING);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
public void printLinkFiles(Path path) throws IOException {
|
||||
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
|
||||
for (Path file : stream) {
|
||||
if (Files.isDirectory(file)) {
|
||||
printLinkFiles(file);
|
||||
} else if (Files.isSymbolicLink(file)) {
|
||||
System.out.format("File link '%s' with target '%s'%n", file, Files.readSymbolicLink(file));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
new SymLinkExample().printLinkFiles(Paths.get("."));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.symlink;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class SymLinkExampleUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingFiles_thenCreateSymbolicLink() throws IOException {
|
||||
SymLinkExample example = new SymLinkExample();
|
||||
Path filePath = example.createTextFile();
|
||||
Path linkPath = Paths.get(".", "symbolic_link.txt");
|
||||
example.createSymbolicLink(linkPath, filePath);
|
||||
assertTrue(Files.isSymbolicLink(linkPath));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFiles_thenCreateHardLink() throws IOException {
|
||||
SymLinkExample example = new SymLinkExample();
|
||||
Path filePath = example.createTextFile();
|
||||
Path linkPath = Paths.get(".", "hard_link.txt");
|
||||
example.createHardLink(linkPath, filePath);
|
||||
assertFalse(Files.isSymbolicLink(linkPath));
|
||||
assertEquals(filePath.toFile()
|
||||
.length(),
|
||||
linkPath.toFile()
|
||||
.length());
|
||||
}
|
||||
|
||||
}
|
|
@ -14,8 +14,10 @@ import org.slf4j.LoggerFactory;
|
|||
import java.io.*;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Scanner;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
@ -112,6 +114,19 @@ public class JavaInputStreamToXUnitTest {
|
|||
assertThat(writer.toString(), equalTo(originalString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingTempFile_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
|
||||
final String originalString = randomAlphabetic(DEFAULT_SIZE);
|
||||
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
|
||||
|
||||
// When
|
||||
Path tempFile = java.nio.file.Files.createTempDirectory("").resolve(UUID.randomUUID().toString() + ".tmp");
|
||||
java.nio.file.Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
|
||||
String result = new String(java.nio.file.Files.readAllBytes(tempFile));
|
||||
|
||||
assertThat(result, equalTo(originalString));
|
||||
}
|
||||
|
||||
// tests - InputStream to byte[]
|
||||
|
||||
@Test
|
||||
|
|
|
@ -160,3 +160,10 @@
|
|||
- [Guide to the super Java Keyword](http://www.baeldung.com/java-super)
|
||||
- [Guide to the this Java Keyword](http://www.baeldung.com/java-this)
|
||||
- [Jagged Arrays In Java](http://www.baeldung.com/java-jagged-arrays)
|
||||
- [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class)
|
||||
- [Extracting Year, Month and Day from Date in Java](http://www.baeldung.com/java-year-month-day)
|
||||
- [Get Date Without Time in Java](http://www.baeldung.com/java-date-without-time)
|
||||
- [Convert a String to Title Case](http://www.baeldung.com/java-string-title-case)
|
||||
- [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension)
|
||||
- [Immutable Objects in Java](http://www.baeldung.com/java-immutable-object)
|
||||
- [Console I/O in Java](http://www.baeldung.com/java-console-input-output)
|
||||
|
|
|
@ -198,11 +198,6 @@
|
|||
<artifactId>mail</artifactId>
|
||||
<version>${javax.mail.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.mail</groupId>
|
||||
<artifactId>mail</artifactId>
|
||||
<version>1.5.0-b01</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.ibm.icu</groupId>
|
||||
<artifactId>icu4j</artifactId>
|
||||
|
@ -255,6 +250,7 @@
|
|||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>${maven-jar-plugin.version}</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
|
@ -293,6 +289,7 @@
|
|||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>${maven-shade-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
|
@ -314,6 +311,7 @@
|
|||
<plugin>
|
||||
<groupId>com.jolira</groupId>
|
||||
<artifactId>onejar-maven-plugin</artifactId>
|
||||
<version>${onejar-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<configuration>
|
||||
|
@ -331,6 +329,7 @@
|
|||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
|
@ -478,6 +477,10 @@
|
|||
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
||||
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
|
||||
<javax.mail.version>1.5.0-b01</javax.mail.version>
|
||||
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
|
||||
<onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version>
|
||||
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
|
||||
<spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version>
|
||||
<icu4j.version>61.1</icu4j.version>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.console;
|
||||
|
||||
import java.io.Console;
|
||||
|
||||
public class ConsoleConsoleClass {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Console console = System.console();
|
||||
|
||||
if (console == null) {
|
||||
System.out.print("No console available");
|
||||
return;
|
||||
}
|
||||
|
||||
String progLanguauge = console.readLine("Enter your favourite programming language: ");
|
||||
console.printf(progLanguauge + " is very interesting!");
|
||||
|
||||
char[] pass = console.readPassword("To finish, enter password: ");
|
||||
|
||||
if ("BAELDUNG".equals(pass.toString().toUpperCase()))
|
||||
console.printf("Good! Regards!");
|
||||
else
|
||||
console.printf("Nice try. Regards.");
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,76 @@
|
|||
package com.baeldung.console;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.Scanner;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class ConsoleScannerClass {
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Please enter your name and surname: ");
|
||||
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
String nameSurname = scanner.nextLine();
|
||||
|
||||
System.out.println("Please enter your gender: ");
|
||||
|
||||
char gender = scanner.next().charAt(0);
|
||||
|
||||
System.out.println("Please enter your age: ");
|
||||
|
||||
int age = scanner.nextInt();
|
||||
|
||||
System.out.println("Please enter your height in meters: ");
|
||||
|
||||
double height = scanner.nextDouble();
|
||||
|
||||
System.out.println(nameSurname + ", " + age + ", is a great " + (gender == 'm' ? "guy" : "girl") + " with " + height + " meters height" + " and " + (gender == 'm' ? "he" : "she") + " reads Baeldung.");
|
||||
|
||||
System.out.print("Have a good");
|
||||
System.out.print(" one!");
|
||||
|
||||
System.out.println("\nPlease enter number of years of experience as a developer: ");
|
||||
|
||||
BufferedReader buffReader = new BufferedReader(new InputStreamReader(System.in));
|
||||
|
||||
int i = 0;
|
||||
|
||||
try {
|
||||
i = Integer.parseInt(buffReader.readLine());
|
||||
} catch (NumberFormatException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
System.out.println("You are a " + (i > 5 ? "great" : "good") + " developer!");
|
||||
|
||||
int sum = 0, count = 0;
|
||||
|
||||
System.out.println("Please enter your college degrees. To finish, enter baeldung website url");
|
||||
|
||||
while (scanner.hasNextInt()) {
|
||||
int nmbr = scanner.nextInt();
|
||||
sum += nmbr;
|
||||
count++;
|
||||
}
|
||||
int mean = sum / count;
|
||||
|
||||
System.out.println("Your average degree is " + mean);
|
||||
|
||||
if (scanner.hasNext(Pattern.compile("www.baeldung.com")))
|
||||
System.out.println("Correct!");
|
||||
else
|
||||
System.out.println("Baeldung website url is www.baeldung.com");
|
||||
|
||||
if (scanner != null)
|
||||
scanner.close();
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.customexception;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class FileManager {
|
||||
|
||||
public static String getFirstLine(String fileName) throws IncorrectFileNameException {
|
||||
try (Scanner file = new Scanner(new File(fileName))) {
|
||||
if (file.hasNextLine()) {
|
||||
return file.nextLine();
|
||||
} else {
|
||||
throw new IllegalArgumentException("Non readable file");
|
||||
}
|
||||
} catch (FileNotFoundException err) {
|
||||
if (!isCorrectFileName(fileName)) {
|
||||
throw new IncorrectFileNameException("Incorrect filename : " + fileName, err);
|
||||
}
|
||||
// Logging etc
|
||||
} catch (IllegalArgumentException err) {
|
||||
if (!containsExtension(fileName)) {
|
||||
throw new IncorrectFileExtensionException("Filename does not contain extension : " + fileName, err);
|
||||
}
|
||||
// Other error cases and logging
|
||||
}
|
||||
return "Default First Line";
|
||||
}
|
||||
|
||||
private static boolean containsExtension(String fileName) {
|
||||
if (fileName.contains(".txt") || fileName.contains(".doc"))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean isCorrectFileName(String fileName) {
|
||||
if (fileName.equals("wrongFileName.txt"))
|
||||
return false;
|
||||
else
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.customexception;
|
||||
|
||||
public class IncorrectFileExtensionException extends RuntimeException{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public IncorrectFileExtensionException(String errorMessage, Throwable err) {
|
||||
super(errorMessage, err);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.customexception;
|
||||
|
||||
public class IncorrectFileNameException extends Exception {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public IncorrectFileNameException(String errorMessage, Throwable err) {
|
||||
super(errorMessage, err);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
package com.baeldung.encrypt;
|
||||
|
||||
import javax.crypto.*;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import java.io.*;
|
||||
import java.security.InvalidAlgorithmParameterException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
class FileEncrypterDecrypter {
|
||||
|
||||
private SecretKey secretKey;
|
||||
private Cipher cipher;
|
||||
|
||||
FileEncrypterDecrypter(SecretKey secretKey, String cipher) throws NoSuchPaddingException, NoSuchAlgorithmException {
|
||||
this.secretKey = secretKey;
|
||||
this.cipher = Cipher.getInstance(cipher);
|
||||
}
|
||||
|
||||
void encrypt(String content, String fileName) throws InvalidKeyException, IOException {
|
||||
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
|
||||
byte[] iv = cipher.getIV();
|
||||
|
||||
try (
|
||||
FileOutputStream fileOut = new FileOutputStream(fileName);
|
||||
CipherOutputStream cipherOut = new CipherOutputStream(fileOut, cipher)
|
||||
) {
|
||||
fileOut.write(iv);
|
||||
cipherOut.write(content.getBytes());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
String decrypt(String fileName) throws InvalidAlgorithmParameterException, InvalidKeyException, IOException {
|
||||
|
||||
String content;
|
||||
|
||||
try (FileInputStream fileIn = new FileInputStream(fileName)) {
|
||||
byte[] fileIv = new byte[16];
|
||||
fileIn.read(fileIv);
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(fileIv));
|
||||
|
||||
try (
|
||||
CipherInputStream cipherIn = new CipherInputStream(fileIn, cipher);
|
||||
InputStreamReader inputReader = new InputStreamReader(cipherIn);
|
||||
BufferedReader reader = new BufferedReader(inputReader)
|
||||
) {
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
sb.append(line);
|
||||
}
|
||||
content = sb.toString();
|
||||
}
|
||||
|
||||
}
|
||||
return content;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.exceptions;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Arithmetic {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(Arithmetic.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
try {
|
||||
int result = 30 / 0; // Trying to divide by zero
|
||||
} catch (ArithmeticException e) {
|
||||
LOGGER.error("ArithmeticException caught!");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.exceptions;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class ArrayIndexOutOfBounds {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(ArrayIndexOutOfBounds.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
int[] nums = new int[] { 1, 2, 3 };
|
||||
|
||||
try {
|
||||
int numFromNegativeIndex = nums[-1]; // Trying to access at negative index
|
||||
int numFromGreaterIndex = nums[4]; // Trying to access at greater index
|
||||
int numFromLengthIndex = nums[3]; // Trying to access at index equal to size of the array
|
||||
} catch (ArrayIndexOutOfBoundsException e) {
|
||||
LOGGER.error("ArrayIndexOutOfBoundsException caught");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.exceptions;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
class Animal {
|
||||
|
||||
}
|
||||
|
||||
class Dog extends Animal {
|
||||
|
||||
}
|
||||
|
||||
class Lion extends Animal {
|
||||
|
||||
}
|
||||
|
||||
public class ClassCast {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(ClassCast.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
try {
|
||||
Animal animalOne = new Dog(); // At runtime the instance is dog
|
||||
Dog bruno = (Dog) animalOne; // Downcasting
|
||||
|
||||
Animal animalTwo = new Lion(); // At runtime the instance is animal
|
||||
Dog tommy = (Dog) animalTwo; // Downcasting
|
||||
} catch (ClassCastException e) {
|
||||
LOGGER.error("ClassCastException caught!");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.exceptions;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileReader;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class FileNotFound {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(FileNotFound.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
BufferedReader reader = null;
|
||||
try {
|
||||
reader = new BufferedReader(new FileReader(new File("/invalid/file/location")));
|
||||
} catch (FileNotFoundException e) {
|
||||
LOGGER.error("FileNotFoundException caught!");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.exceptions;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Handler globalExceptionHandler = new Handler();
|
||||
Thread.setDefaultUncaughtExceptionHandler(globalExceptionHandler);
|
||||
new GlobalExceptionHandler().performArithmeticOperation(10, 0);
|
||||
}
|
||||
|
||||
public int performArithmeticOperation(int num1, int num2) {
|
||||
return num1/num2;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class Handler implements Thread.UncaughtExceptionHandler {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(Handler.class);
|
||||
|
||||
public void uncaughtException(Thread t, Throwable e) {
|
||||
LOGGER.info("Unhandled exception caught!");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.exceptions;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class IllegalArgument {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(IllegalArgument.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
Thread.sleep(-1000);
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.error("IllegalArgumentException caught!");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.exceptions;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class IllegalState {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(IllegalState.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
List<Integer> intList = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < 10; i++) {
|
||||
intList.add(i);
|
||||
}
|
||||
|
||||
Iterator<Integer> intListIterator = intList.iterator(); // Initialized with index at -1
|
||||
|
||||
try {
|
||||
intListIterator.remove(); // IllegalStateException
|
||||
} catch (IllegalStateException e) {
|
||||
LOGGER.error("IllegalStateException caught!");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.exceptions;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
class ChildThread extends Thread {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(ChildThread.class);
|
||||
|
||||
public void run() {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.error("InterruptedException caught!");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public class InterruptedExceptionExample {
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
ChildThread childThread = new ChildThread();
|
||||
childThread.start();
|
||||
childThread.interrupt();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.exceptions;
|
||||
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class MalformedURL {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(MalformedURL.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
URL baeldungURL = null;
|
||||
|
||||
try {
|
||||
baeldungURL = new URL("malformedurl");
|
||||
} catch (MalformedURLException e) {
|
||||
LOGGER.error("MalformedURLException caught!");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.exceptions;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class NullPointer {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(NullPointer.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Person personObj = null;
|
||||
|
||||
try {
|
||||
String name = personObj.personName; // Accessing the field of a null object
|
||||
personObj.personName = "Jon Doe"; // Modifying the field of a null object
|
||||
} catch (NullPointerException e) {
|
||||
LOGGER.error("NullPointerException caught!");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
class Person {
|
||||
|
||||
public String personName;
|
||||
|
||||
public String getPersonName() {
|
||||
return personName;
|
||||
}
|
||||
|
||||
public void setPersonName(String personName) {
|
||||
this.personName = personName;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.exceptions;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class NumberFormat {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(NumberFormat.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
String str1 = "100ABCD";
|
||||
|
||||
try {
|
||||
int x = Integer.parseInt(str1); // Converting string with inappropriate format
|
||||
int y = Integer.valueOf(str1);
|
||||
} catch (NumberFormatException e) {
|
||||
LOGGER.error("NumberFormatException caught!");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.exceptions;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class ParseExceptionExample {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(ParseExceptionExample.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
DateFormat format = new SimpleDateFormat("MM, dd, yyyy");
|
||||
|
||||
try {
|
||||
format.parse("01, , 2010");
|
||||
} catch (ParseException e) {
|
||||
LOGGER.error("ParseException caught!");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.exceptions;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class StringIndexOutOfBounds {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(StringIndexOutOfBounds.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
String str = "Hello World";
|
||||
|
||||
try {
|
||||
char charAtNegativeIndex = str.charAt(-1); // Trying to access at negative index
|
||||
char charAtLengthIndex = str.charAt(11); // Trying to access at index equal to size of the string
|
||||
} catch (StringIndexOutOfBoundsException e) {
|
||||
LOGGER.error("StringIndexOutOfBoundsException caught");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,69 @@
|
|||
package com.baeldung.gregorian.calendar;
|
||||
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Calendar;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.HashSet;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import javax.xml.datatype.DatatypeConfigurationException;
|
||||
import javax.xml.datatype.DatatypeFactory;
|
||||
import javax.xml.datatype.XMLGregorianCalendar;
|
||||
|
||||
public class GregorianCalendarExample {
|
||||
|
||||
|
||||
public Date setMonth(GregorianCalendar calendar, int amount) {
|
||||
calendar.set(Calendar.MONTH, amount);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
|
||||
public Date rollAdd(GregorianCalendar calendar, int amount) {
|
||||
calendar.roll(GregorianCalendar.MONTH, amount);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public boolean isLeapYearExample(int year) {
|
||||
GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
|
||||
return cal.isLeapYear(year);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public Date subtractDays(GregorianCalendar calendar, int daysToSubtract) {
|
||||
GregorianCalendar cal = calendar;
|
||||
cal.add(Calendar.DATE, -daysToSubtract);
|
||||
return cal.getTime();
|
||||
}
|
||||
|
||||
public Date addDays(GregorianCalendar calendar, int daysToAdd) {
|
||||
GregorianCalendar cal = calendar;
|
||||
cal.add(Calendar.DATE, daysToAdd);
|
||||
return cal.getTime();
|
||||
}
|
||||
|
||||
public XMLGregorianCalendar toXMLGregorianCalendar(GregorianCalendar calendar) throws DatatypeConfigurationException {
|
||||
DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
|
||||
return datatypeFactory.newXMLGregorianCalendar(calendar);
|
||||
}
|
||||
|
||||
public Date toDate(XMLGregorianCalendar calendar) {
|
||||
return calendar.toGregorianCalendar()
|
||||
.getTime();
|
||||
}
|
||||
|
||||
public int compareDates(GregorianCalendar firstDate, GregorianCalendar secondDate) {
|
||||
return firstDate.compareTo(secondDate);
|
||||
}
|
||||
|
||||
public String formatDate(GregorianCalendar calendar) {
|
||||
return calendar.toZonedDateTime()
|
||||
.format(DateTimeFormatter.ofPattern("d MMM uuuu"));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.customexception;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class IncorrectFileExtensionExceptionUnitTest {
|
||||
|
||||
@Test
|
||||
public void testWhenCorrectFileExtensionGiven_ReceivesNoException() throws IncorrectFileNameException {
|
||||
assertThat(FileManager.getFirstLine("correctFileNameWithProperExtension.txt")).isEqualTo("Default First Line");
|
||||
}
|
||||
|
||||
@Test(expected = IncorrectFileExtensionException.class)
|
||||
public void testWhenCorrectFileNameExceptionThrown_ReceivesNoException() throws IncorrectFileNameException {
|
||||
StringBuffer sBuffer = new StringBuffer();
|
||||
sBuffer.append("src");
|
||||
sBuffer.append(File.separator);
|
||||
sBuffer.append("test");
|
||||
sBuffer.append(File.separator);
|
||||
sBuffer.append("resources");
|
||||
sBuffer.append(File.separator);
|
||||
sBuffer.append("correctFileNameWithoutProperExtension");
|
||||
FileManager.getFirstLine(sBuffer.toString());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.customexception;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class IncorrectFileNameExceptionUnitTest {
|
||||
|
||||
@Test(expected = IncorrectFileNameException.class)
|
||||
public void testWhenIncorrectFileNameExceptionThrown_ReceivesIncorrectFileNameException() throws IncorrectFileNameException {
|
||||
FileManager.getFirstLine("wrongFileName.txt");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWhenCorrectFileNameExceptionThrown_ReceivesNoException() throws IncorrectFileNameException {
|
||||
assertThat(FileManager.getFirstLine("correctFileName.txt")).isEqualTo("Default First Line");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.encrypt;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.NoSuchPaddingException;
|
||||
import javax.crypto.SecretKey;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.security.InvalidAlgorithmParameterException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class FileEncrypterDecrypterIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenStringAndFilename_whenEncryptingIntoFile_andDecryptingFileAgain_thenOriginalStringIsReturned() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, InvalidAlgorithmParameterException {
|
||||
String originalContent = "foobar";
|
||||
SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
|
||||
|
||||
FileEncrypterDecrypter fileEncrypterDecrypter = new FileEncrypterDecrypter(secretKey, "AES/CBC/PKCS5Padding");
|
||||
fileEncrypterDecrypter.encrypt(originalContent, "baz.enc");
|
||||
|
||||
String decryptedContent = fileEncrypterDecrypter.decrypt("baz.enc");
|
||||
assertThat(decryptedContent, is(originalContent));
|
||||
|
||||
new File("baz.enc").delete(); // cleanup
|
||||
}
|
||||
}
|
|
@ -0,0 +1,64 @@
|
|||
package com.baeldung.exceptions;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Captor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import ch.qos.logback.classic.Level;
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.classic.spi.LoggingEvent;
|
||||
import ch.qos.logback.core.Appender;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class GlobalExceptionHandlerUnitTest {
|
||||
|
||||
@Mock
|
||||
private Appender<ILoggingEvent> mockAppender;
|
||||
|
||||
@Captor
|
||||
private ArgumentCaptor<LoggingEvent> captorLoggingEvent;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
|
||||
logger.addAppender(mockAppender);
|
||||
|
||||
Handler globalExceptionHandler = new Handler();
|
||||
Thread.setDefaultUncaughtExceptionHandler(globalExceptionHandler);
|
||||
}
|
||||
|
||||
@After
|
||||
public void teardown() {
|
||||
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
|
||||
logger.detachAppender(mockAppender);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenArithmeticException_thenUseUncaughtExceptionHandler() throws InterruptedException {
|
||||
|
||||
Thread globalExceptionHandlerThread = new Thread() {
|
||||
public void run() {
|
||||
GlobalExceptionHandler globalExceptionHandlerObj = new GlobalExceptionHandler();
|
||||
globalExceptionHandlerObj.performArithmeticOperation(99, 0);
|
||||
}
|
||||
};
|
||||
|
||||
globalExceptionHandlerThread.start();
|
||||
globalExceptionHandlerThread.join();
|
||||
|
||||
verify(mockAppender).doAppend(captorLoggingEvent.capture());
|
||||
LoggingEvent loggingEvent = captorLoggingEvent.getValue();
|
||||
|
||||
assertThat(loggingEvent.getLevel()).isEqualTo(Level.INFO);
|
||||
assertThat(loggingEvent.getFormattedMessage()).isEqualTo("Unhandled exception caught!");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,228 @@
|
|||
package com.baeldung.gregorian.calendar;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import javax.xml.datatype.DatatypeConfigurationException;
|
||||
import javax.xml.datatype.DatatypeFactory;
|
||||
import javax.xml.datatype.XMLGregorianCalendar;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.gregorian.calendar.GregorianCalendarExample;
|
||||
|
||||
public class GregorianCalendarTester {
|
||||
|
||||
@Test
|
||||
public void test_Calendar_Return_Type_Valid() {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
assert ("gregory".equals(calendar.getCalendarType()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_Calendar_Return_Type_InValid() {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
assertNotEquals("gregorys", calendar.getCalendarType());
|
||||
}
|
||||
|
||||
@Test(expected = ClassCastException.class)
|
||||
public void test_Class_Cast_Exception() {
|
||||
TimeZone tz = TimeZone.getTimeZone("GMT+9:00");
|
||||
Locale loc = new Locale("ja", "JP", "JP");
|
||||
Calendar calendar = Calendar.getInstance(loc);
|
||||
GregorianCalendar gc = (GregorianCalendar) calendar;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_Getting_Calendar_information() {
|
||||
GregorianCalendar calendar = new GregorianCalendar(2018, 5, 28);
|
||||
assertTrue(false == calendar.isLeapYear(calendar.YEAR));
|
||||
assertTrue(52 == calendar.getWeeksInWeekYear());
|
||||
assertTrue(2018 == calendar.getWeekYear());
|
||||
assertTrue(30 == calendar.getActualMaximum(calendar.DAY_OF_MONTH));
|
||||
assertTrue(1 == calendar.getActualMinimum(calendar.DAY_OF_MONTH));
|
||||
assertTrue(1 == calendar.getGreatestMinimum(calendar.DAY_OF_MONTH));
|
||||
assertTrue(28 == calendar.getLeastMaximum(calendar.DAY_OF_MONTH));
|
||||
assertTrue(31 == calendar.getMaximum(calendar.DAY_OF_MONTH));
|
||||
assertTrue(1 == calendar.getMinimum(calendar.DAY_OF_MONTH));
|
||||
assertTrue(52 == calendar.getWeeksInWeekYear());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_Compare_Date_FirstDate_Greater_SecondDate() {
|
||||
GregorianCalendar firstDate = new GregorianCalendar(2018, 6, 28);
|
||||
GregorianCalendar secondDate = new GregorianCalendar(2018, 5, 28);
|
||||
assertTrue(1 == firstDate.compareTo(secondDate));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void test_Compare_Date_FirstDate_Smaller_SecondDate() {
|
||||
GregorianCalendar firstDate = new GregorianCalendar(2018, 5, 28);
|
||||
GregorianCalendar secondDate = new GregorianCalendar(2018, 6, 28);
|
||||
assertTrue(-1 == firstDate.compareTo(secondDate));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_Compare_Date_Both_Dates_Equal() {
|
||||
GregorianCalendar firstDate = new GregorianCalendar(2018, 6, 28);
|
||||
GregorianCalendar secondDate = new GregorianCalendar(2018, 6, 28);
|
||||
assertTrue(0 == firstDate.compareTo(secondDate));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_date_format() {
|
||||
GregorianCalendarExample calendarDemo = new GregorianCalendarExample();
|
||||
GregorianCalendar calendar = new GregorianCalendar(2018, 6, 28);
|
||||
assertEquals("28 Jul 2018", calendarDemo.formatDate(calendar));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_dateFormatdMMMuuuu() {
|
||||
String expectedDate = new GregorianCalendar(2018, 6, 28).toZonedDateTime()
|
||||
.format(DateTimeFormatter.ofPattern("d MMM uuuu"));
|
||||
assertEquals("28 Jul 2018", expectedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_addDays() {
|
||||
GregorianCalendarExample calendarDemo = new GregorianCalendarExample();
|
||||
GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28);
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28);
|
||||
calendarExpected.add(Calendar.DATE, 1);
|
||||
Date expectedDate = calendarExpected.getTime();
|
||||
assertEquals(expectedDate, calendarDemo.addDays(calendarActual, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_whenAddOneDay_thenMonthIsChanged() {
|
||||
final int finalDay1 = 1;
|
||||
final int finalMonthJul = 6;
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 5, 30);
|
||||
calendarExpected.add(Calendar.DATE, 1);
|
||||
System.out.println(calendarExpected.getTime());
|
||||
assertEquals(calendarExpected.get(Calendar.DATE), finalDay1);
|
||||
assertEquals(calendarExpected.get(Calendar.MONTH), finalMonthJul);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_whenSubtractOneDay_thenMonthIsChanged() {
|
||||
final int finalDay31 = 31;
|
||||
final int finalMonthMay = 4;
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 5, 1);
|
||||
calendarExpected.add(Calendar.DATE, -1);
|
||||
assertEquals(calendarExpected.get(Calendar.DATE), finalDay31);
|
||||
assertEquals(calendarExpected.get(Calendar.MONTH), finalMonthMay);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_subDays() {
|
||||
GregorianCalendarExample calendarDemo = new GregorianCalendarExample();
|
||||
GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28);
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28);
|
||||
calendarExpected.add(Calendar.DATE, -1);
|
||||
Date expectedDate = calendarExpected.getTime();
|
||||
assertEquals(expectedDate, calendarDemo.subtractDays(calendarActual, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_rollAdd() {
|
||||
GregorianCalendarExample calendarDemo = new GregorianCalendarExample();
|
||||
GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28);
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28);
|
||||
calendarExpected.roll(Calendar.MONTH, 8);
|
||||
Date expectedDate = calendarExpected.getTime();
|
||||
assertEquals(expectedDate, calendarDemo.rollAdd(calendarActual, 8));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_whenRollUpOneMonth_thenYearIsUnchanged() {
|
||||
final int rolledUpMonthJuly = 7, orginalYear2018 = 2018;
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28);
|
||||
calendarExpected.roll(Calendar.MONTH, 1);
|
||||
assertEquals(calendarExpected.get(Calendar.MONTH), rolledUpMonthJuly);
|
||||
assertEquals(calendarExpected.get(Calendar.YEAR), orginalYear2018);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_whenRollDownOneMonth_thenYearIsUnchanged() {
|
||||
final int rolledDownMonthJune = 5, orginalYear2018 = 2018;
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28);
|
||||
calendarExpected.roll(Calendar.MONTH, -1);
|
||||
assertEquals(calendarExpected.get(Calendar.MONTH), rolledDownMonthJune);
|
||||
assertEquals(calendarExpected.get(Calendar.YEAR), orginalYear2018);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_rollSubtract() {
|
||||
GregorianCalendarExample calendarDemo = new GregorianCalendarExample();
|
||||
GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28);
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28);
|
||||
calendarExpected.roll(Calendar.MONTH, -8);
|
||||
Date expectedDate = calendarExpected.getTime();
|
||||
assertEquals(expectedDate, calendarDemo.rollAdd(calendarActual, -8));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_setMonth() {
|
||||
GregorianCalendarExample calendarDemo = new GregorianCalendarExample();
|
||||
GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28);
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28);
|
||||
calendarExpected.set(Calendar.MONTH, 3);
|
||||
Date expectedDate = calendarExpected.getTime();
|
||||
assertEquals(expectedDate, calendarDemo.setMonth(calendarActual, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_setMonthApril() {
|
||||
final int setMonthApril = 3, orginalYear2018 = 2018, originalDate28 = 28;
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28);
|
||||
calendarExpected.set(Calendar.MONTH, 3);
|
||||
assertEquals(calendarExpected.get(Calendar.MONTH), setMonthApril);
|
||||
assertEquals(calendarExpected.get(Calendar.YEAR), orginalYear2018);
|
||||
assertEquals(calendarExpected.get(Calendar.DATE), originalDate28);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_toXMLGregorianCalendar() throws DatatypeConfigurationException {
|
||||
GregorianCalendarExample calendarDemo = new GregorianCalendarExample();
|
||||
DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
|
||||
GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28);
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28);
|
||||
XMLGregorianCalendar expectedXMLGregorianCalendar = datatypeFactory
|
||||
.newXMLGregorianCalendar(calendarExpected);
|
||||
assertEquals(expectedXMLGregorianCalendar,
|
||||
calendarDemo.toXMLGregorianCalendar(calendarActual));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_isLeapYear_True() {
|
||||
GregorianCalendarExample calendarDemo = new GregorianCalendarExample();
|
||||
assertEquals(true, calendarDemo.isLeapYearExample(2016));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_isLeapYear_False() {
|
||||
GregorianCalendarExample calendarDemo = new GregorianCalendarExample();
|
||||
assertEquals(false, calendarDemo.isLeapYearExample(2018));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_toDate() throws DatatypeConfigurationException {
|
||||
GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28);
|
||||
DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
|
||||
XMLGregorianCalendar expectedXMLGregorianCalendar = datatypeFactory
|
||||
.newXMLGregorianCalendar(calendarActual);
|
||||
expectedXMLGregorianCalendar.toGregorianCalendar().getTime();
|
||||
assertEquals(calendarActual.getTime(),
|
||||
expectedXMLGregorianCalendar.toGregorianCalendar().getTime() );
|
||||
}
|
||||
}
|
|
@ -0,0 +1,95 @@
|
|||
package com.baeldung.thread.join;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Demonstrates Thread.join behavior.
|
||||
*
|
||||
*/
|
||||
public class ThreadJoinUnitTest {
|
||||
|
||||
final static Logger LOGGER = Logger.getLogger(ThreadJoinUnitTest.class.getName());
|
||||
|
||||
class SampleThread extends Thread {
|
||||
public int processingCount = 0;
|
||||
|
||||
SampleThread(int processingCount) {
|
||||
this.processingCount = processingCount;
|
||||
LOGGER.info("Thread " + this.getName() + " created");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
LOGGER.info("Thread " + this.getName() + " started");
|
||||
while (processingCount > 0) {
|
||||
try {
|
||||
Thread.sleep(1000); // Simulate some work being done by thread
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.info("Thread " + this.getName() + " interrupted.");
|
||||
}
|
||||
processingCount--;
|
||||
LOGGER.info("Inside Thread " + this.getName() + ", processingCount = " + processingCount);
|
||||
}
|
||||
LOGGER.info("Thread " + this.getName() + " exiting");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNewThread_whenJoinCalled_returnsImmediately() throws InterruptedException {
|
||||
Thread t1 = new SampleThread(0);
|
||||
LOGGER.info("Invoking join.");
|
||||
t1.join();
|
||||
LOGGER.info("Returned from join");
|
||||
LOGGER.info("Thread state is" + t1.getState());
|
||||
assertFalse(t1.isAlive());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStartedThread_whenJoinCalled_waitsTillCompletion()
|
||||
throws InterruptedException {
|
||||
Thread t2 = new SampleThread(1);
|
||||
t2.start();
|
||||
LOGGER.info("Invoking join.");
|
||||
t2.join();
|
||||
LOGGER.info("Returned from join");
|
||||
assertFalse(t2.isAlive());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStartedThread_whenTimedJoinCalled_waitsUntilTimedout()
|
||||
throws InterruptedException {
|
||||
Thread t3 = new SampleThread(10);
|
||||
t3.start();
|
||||
t3.join(1000);
|
||||
assertTrue(t3.isAlive());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
public void givenThreadTerminated_checkForEffect_notGuaranteed()
|
||||
throws InterruptedException {
|
||||
SampleThread t4 = new SampleThread(10);
|
||||
t4.start();
|
||||
//not guaranteed to stop even if t4 finishes.
|
||||
do {
|
||||
|
||||
} while (t4.processingCount > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJoinWithTerminatedThread_checkForEffect_guaranteed()
|
||||
throws InterruptedException {
|
||||
SampleThread t4 = new SampleThread(10);
|
||||
t4.start();
|
||||
do {
|
||||
t4.join(100);
|
||||
} while (t4.processingCount > 0);
|
||||
}
|
||||
|
||||
}
|
|
@ -1 +1,14 @@
|
|||
/bin/
|
||||
|
||||
#ignore gradle
|
||||
.gradle/
|
||||
|
||||
|
||||
#ignore build and generated files
|
||||
build/
|
||||
node/
|
||||
out/
|
||||
|
||||
#ignore installed node modules and package lock file
|
||||
node_modules/
|
||||
package-lock.json
|
||||
|
|
|
@ -30,3 +30,6 @@
|
|||
- [Lambda Expressions in Kotlin](http://www.baeldung.com/kotlin-lambda-expressions)
|
||||
- [Writing Specifications with Kotlin and Spek](http://www.baeldung.com/kotlin-spek)
|
||||
- [Processing JSON with Kotlin and Klaxson](http://www.baeldung.com/kotlin-json-klaxson)
|
||||
- [Kotlin String Templates](http://www.baeldung.com/kotlin-string-template)
|
||||
- [Java EE 8 Security API](http://www.baeldung.com/java-ee-8-security)
|
||||
- [Kotlin with Ktor](http://www.baeldung.com/kotlin-ktor)
|
||||
|
|
|
@ -0,0 +1,57 @@
|
|||
|
||||
|
||||
group 'com.baeldung.ktor'
|
||||
version '1.0-SNAPSHOT'
|
||||
|
||||
|
||||
buildscript {
|
||||
ext.kotlin_version = '1.2.41'
|
||||
ext.ktor_version = '0.9.2'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
|
||||
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
|
||||
}
|
||||
}
|
||||
|
||||
apply plugin: 'java'
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName = 'APIServer.kt'
|
||||
|
||||
sourceCompatibility = 1.8
|
||||
compileKotlin { kotlinOptions.jvmTarget = "1.8" }
|
||||
compileTestKotlin { kotlinOptions.jvmTarget = "1.8" }
|
||||
|
||||
kotlin { experimental { coroutines "enable" } }
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
jcenter()
|
||||
maven { url "https://dl.bintray.com/kotlin/ktor" }
|
||||
}
|
||||
sourceSets {
|
||||
main{
|
||||
kotlin{
|
||||
srcDirs 'com/baeldung/ktor'
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile "io.ktor:ktor-server-netty:$ktor_version"
|
||||
compile "ch.qos.logback:logback-classic:1.2.1"
|
||||
compile "io.ktor:ktor-gson:$ktor_version"
|
||||
testCompile group: 'junit', name: 'junit', version: '4.12'
|
||||
implementation 'com.beust:klaxon:3.0.1'
|
||||
|
||||
}
|
||||
task runServer(type: JavaExec) {
|
||||
main = 'APIServer'
|
||||
classpath = sourceSets.main.runtimeClasspath
|
||||
}
|
|
@ -5,7 +5,7 @@ version '1.0-SNAPSHOT'
|
|||
|
||||
|
||||
buildscript {
|
||||
ext.kotlin_version = '1.2.40'
|
||||
ext.kotlin_version = '1.2.41'
|
||||
ext.ktor_version = '0.9.2'
|
||||
|
||||
repositories {
|
Binary file not shown.
|
@ -0,0 +1,5 @@
|
|||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip
|
|
@ -0,0 +1,172 @@
|
|||
#!/usr/bin/env sh
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS=""
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
}
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
NONSTOP* )
|
||||
nonstop=true
|
||||
;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=$((i+1))
|
||||
done
|
||||
case $i in
|
||||
(0) set -- ;;
|
||||
(1) set -- "$args0" ;;
|
||||
(2) set -- "$args0" "$args1" ;;
|
||||
(3) set -- "$args0" "$args1" "$args2" ;;
|
||||
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# Escape application args
|
||||
save () {
|
||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
||||
echo " "
|
||||
}
|
||||
APP_ARGS=$(save "$@")
|
||||
|
||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
||||
|
||||
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
|
||||
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
|
||||
cd "$(dirname "$0")"
|
||||
fi
|
||||
|
||||
exec "$JAVACMD" "$@"
|
|
@ -0,0 +1,84 @@
|
|||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS=
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:init
|
||||
@rem Get command-line arguments, handling Windows variants
|
||||
|
||||
if not "%OS%" == "Windows_NT" goto win9xME_args
|
||||
|
||||
:win9xME_args
|
||||
@rem Slurp the command line arguments.
|
||||
set CMD_LINE_ARGS=
|
||||
set _SKIP=2
|
||||
|
||||
:win9xME_args_slurp
|
||||
if "x%~1" == "x" goto execute
|
||||
|
||||
set CMD_LINE_ARGS=%*
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
|
@ -1,26 +1,26 @@
|
|||
@file:JvmName("APIServer")
|
||||
|
||||
|
||||
|
||||
import io.ktor.application.call
|
||||
import io.ktor.application.install
|
||||
import io.ktor.features.CallLogging
|
||||
import io.ktor.features.ContentNegotiation
|
||||
import io.ktor.features.DefaultHeaders
|
||||
import io.ktor.gson.gson
|
||||
import io.ktor.http.ContentType
|
||||
import io.ktor.request.path
|
||||
import io.ktor.request.receive
|
||||
import io.ktor.response.respond
|
||||
import io.ktor.response.respondText
|
||||
import io.ktor.routing.get
|
||||
import io.ktor.routing.routing
|
||||
import io.ktor.routing.*
|
||||
import io.ktor.server.engine.embeddedServer
|
||||
import io.ktor.server.netty.Netty
|
||||
import org.slf4j.event.Level
|
||||
|
||||
data class Author(val name: String, val website: String)
|
||||
data class ToDo(var id: Int, val name: String, val description: String, val completed: Boolean)
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
|
||||
val toDoList = ArrayList<ToDo>();
|
||||
val jsonResponse = """{
|
||||
"id": 1,
|
||||
"task": "Pay waterbill",
|
||||
|
@ -33,7 +33,7 @@ fun main(args: Array<String>) {
|
|||
header("X-Developer", "Baeldung")
|
||||
}
|
||||
install(CallLogging) {
|
||||
level = Level.INFO
|
||||
level = Level.DEBUG
|
||||
filter { call -> call.request.path().startsWith("/todo") }
|
||||
filter { call -> call.request.path().startsWith("/author") }
|
||||
}
|
||||
|
@ -42,15 +42,31 @@ fun main(args: Array<String>) {
|
|||
setPrettyPrinting()
|
||||
}
|
||||
}
|
||||
routing {
|
||||
get("/todo") {
|
||||
call.respondText(jsonResponse, ContentType.Application.Json)
|
||||
}
|
||||
get("/author") {
|
||||
val author = Author("baeldung", "baeldung.com")
|
||||
call.respond(author)
|
||||
routing() {
|
||||
route("/todo") {
|
||||
post {
|
||||
var toDo = call.receive<ToDo>();
|
||||
toDo.id = toDoList.size;
|
||||
toDoList.add(toDo);
|
||||
call.respond("Added")
|
||||
|
||||
}
|
||||
delete("/{id}") {
|
||||
call.respond(toDoList.removeAt(call.parameters["id"]!!.toInt()));
|
||||
}
|
||||
get("/{id}") {
|
||||
|
||||
call.respond(toDoList[call.parameters["id"]!!.toInt()]);
|
||||
}
|
||||
get {
|
||||
call.respond(toDoList);
|
||||
}
|
||||
}
|
||||
get("/author"){
|
||||
call.respond(Author("Baeldung","baeldung.com"));
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}.start(wait = true)
|
|
@ -0,0 +1,11 @@
|
|||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT"/>
|
||||
</root>
|
||||
</configuration>
|
|
@ -0,0 +1,2 @@
|
|||
rootProject.name = 'KtorWithKotlin'
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
@file:JvmName("APIServer")
|
||||
|
||||
|
||||
import io.ktor.application.call
|
||||
import io.ktor.application.install
|
||||
import io.ktor.features.CallLogging
|
||||
import io.ktor.features.ContentNegotiation
|
||||
import io.ktor.features.DefaultHeaders
|
||||
import io.ktor.gson.gson
|
||||
import io.ktor.request.path
|
||||
import io.ktor.request.receive
|
||||
import io.ktor.response.respond
|
||||
import io.ktor.routing.*
|
||||
import io.ktor.server.engine.embeddedServer
|
||||
import io.ktor.server.netty.Netty
|
||||
import org.slf4j.event.Level
|
||||
|
||||
data class Author(val name: String, val website: String)
|
||||
data class ToDo(var id: Int, val name: String, val description: String, val completed: Boolean)
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
|
||||
val toDoList = ArrayList<ToDo>();
|
||||
val jsonResponse = """{
|
||||
"id": 1,
|
||||
"task": "Pay waterbill",
|
||||
"description": "Pay water bill today",
|
||||
}"""
|
||||
|
||||
|
||||
embeddedServer(Netty, 8080) {
|
||||
install(DefaultHeaders) {
|
||||
header("X-Developer", "Baeldung")
|
||||
}
|
||||
install(CallLogging) {
|
||||
level = Level.DEBUG
|
||||
filter { call -> call.request.path().startsWith("/todo") }
|
||||
filter { call -> call.request.path().startsWith("/author") }
|
||||
}
|
||||
install(ContentNegotiation) {
|
||||
gson {
|
||||
setPrettyPrinting()
|
||||
}
|
||||
}
|
||||
routing() {
|
||||
route("/todo") {
|
||||
post {
|
||||
var toDo = call.receive<ToDo>();
|
||||
toDo.id = toDoList.size;
|
||||
toDoList.add(toDo);
|
||||
call.respond("Added")
|
||||
|
||||
}
|
||||
delete("/{id}") {
|
||||
call.respond(toDoList.removeAt(call.parameters["id"]!!.toInt()));
|
||||
}
|
||||
get("/{id}") {
|
||||
|
||||
call.respond(toDoList[call.parameters["id"]!!.toInt()]);
|
||||
}
|
||||
get {
|
||||
call.respond(toDoList);
|
||||
}
|
||||
}
|
||||
get("/author"){
|
||||
call.respond(Author("Baeldung","baeldung.com"));
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}.start(wait = true)
|
||||
}
|
|
@ -1,13 +1,13 @@
|
|||
package com.baeldung.trie;
|
||||
|
||||
public class Trie {
|
||||
class Trie {
|
||||
private TrieNode root;
|
||||
|
||||
Trie() {
|
||||
root = new TrieNode();
|
||||
}
|
||||
|
||||
public void insert(String word) {
|
||||
void insert(String word) {
|
||||
TrieNode current = root;
|
||||
|
||||
for (int i = 0; i < word.length(); i++) {
|
||||
|
@ -16,11 +16,11 @@ public class Trie {
|
|||
current.setEndOfWord(true);
|
||||
}
|
||||
|
||||
public boolean delete(String word) {
|
||||
boolean delete(String word) {
|
||||
return delete(root, word, 0);
|
||||
}
|
||||
|
||||
public boolean containsNode(String word) {
|
||||
boolean containsNode(String word) {
|
||||
TrieNode current = root;
|
||||
|
||||
for (int i = 0; i < word.length(); i++) {
|
||||
|
@ -34,7 +34,7 @@ public class Trie {
|
|||
return current.isEndOfWord();
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
boolean isEmpty() {
|
||||
return root == null;
|
||||
}
|
||||
|
||||
|
@ -51,7 +51,7 @@ public class Trie {
|
|||
if (node == null) {
|
||||
return false;
|
||||
}
|
||||
boolean shouldDeleteCurrentNode = delete(node, word, index + 1);
|
||||
boolean shouldDeleteCurrentNode = delete(node, word, index + 1) && !node.isEndOfWord();
|
||||
|
||||
if (shouldDeleteCurrentNode) {
|
||||
current.getChildren().remove(ch);
|
||||
|
|
|
@ -4,28 +4,18 @@ import java.util.HashMap;
|
|||
import java.util.Map;
|
||||
|
||||
class TrieNode {
|
||||
private Map<Character, TrieNode> children;
|
||||
private final Map<Character, TrieNode> children = new HashMap<>();
|
||||
private boolean endOfWord;
|
||||
|
||||
public TrieNode() {
|
||||
children = new HashMap<>();
|
||||
endOfWord = false;
|
||||
}
|
||||
|
||||
public Map<Character, TrieNode> getChildren() {
|
||||
Map<Character, TrieNode> getChildren() {
|
||||
return children;
|
||||
}
|
||||
|
||||
public void setChildren(Map<Character, TrieNode> children) {
|
||||
this.children = children;
|
||||
}
|
||||
|
||||
public boolean isEndOfWord() {
|
||||
boolean isEndOfWord() {
|
||||
return endOfWord;
|
||||
}
|
||||
|
||||
public void setEndOfWord(boolean endOfWord) {
|
||||
void setEndOfWord(boolean endOfWord) {
|
||||
this.endOfWord = endOfWord;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,6 +1,7 @@
|
|||
package com.baeldung.trie;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
@ -53,6 +54,19 @@ public class TrieTest {
|
|||
assertFalse(trie.containsNode("Programming"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenATrie_whenDeletingOverlappingElements_thenDontDeleteSubElement() {
|
||||
|
||||
Trie trie1 = new Trie();
|
||||
|
||||
trie1.insert("pie");
|
||||
trie1.insert("pies");
|
||||
|
||||
trie1.delete("pies");
|
||||
|
||||
Assertions.assertTrue(trie1.containsNode("pie"));
|
||||
}
|
||||
|
||||
private Trie createExampleTrie() {
|
||||
Trie trie = new Trie();
|
||||
|
||||
|
|
|
@ -1 +1,3 @@
|
|||
## Relevant articles:
|
||||
|
||||
- [A Guide to DeltaSpike Data Module](http://www.baeldung.com/deltaspike-data-module)
|
||||
|
|
|
@ -0,0 +1,21 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>widlfly-mdb</artifactId>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.wildfly</groupId>
|
||||
<artifactId>wildfly-example</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- Dependency for java ee -->
|
||||
<dependency>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-api</artifactId>
|
||||
<version>${javaee-api.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.wildfly.mdb;
|
||||
|
||||
import javax.ejb.ActivationConfigProperty;
|
||||
import javax.ejb.MessageDriven;
|
||||
import javax.jms.JMSException;
|
||||
import javax.jms.Message;
|
||||
import javax.jms.MessageListener;
|
||||
import javax.jms.TextMessage;
|
||||
|
||||
/**
|
||||
* Message-Driven Bean implementation class for: ReadMessageMDB
|
||||
*/
|
||||
@MessageDriven(
|
||||
activationConfig = {
|
||||
@ActivationConfigProperty(propertyName = "destination", propertyValue = "tutorialQueue"),
|
||||
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
|
||||
})
|
||||
public class ReadMessageMDB implements MessageListener {
|
||||
|
||||
public void onMessage(Message message) {
|
||||
TextMessage textMessage = (TextMessage) message;
|
||||
try {
|
||||
System.out.println("Message received: " + textMessage.getText());
|
||||
} catch (JMSException e) {
|
||||
System.out.println("Error while trying to consume messages: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package baeldung.com.example.servlet;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.jms.Connection;
|
||||
import javax.jms.ConnectionFactory;
|
||||
import javax.jms.JMSException;
|
||||
import javax.jms.MessageProducer;
|
||||
import javax.jms.Queue;
|
||||
import javax.jms.Session;
|
||||
import javax.jms.TextMessage;
|
||||
import javax.naming.Context;
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
|
||||
@WebServlet("/SendMessageServlet")
|
||||
public class SendMessageServlet extends HttpServlet {
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
|
||||
String text = req.getParameter("text") != null ? req.getParameter("text") : "Hello World";
|
||||
|
||||
try (
|
||||
Context ic = new InitialContext();
|
||||
|
||||
ConnectionFactory cf = (ConnectionFactory) ic.lookup("/ConnectionFactory");
|
||||
Queue queue = (Queue) ic.lookup("queue/tutorialQueue");
|
||||
|
||||
Connection connection = cf.createConnection();
|
||||
) {
|
||||
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
|
||||
MessageProducer publisher = session.createProducer(queue);
|
||||
|
||||
connection.start();
|
||||
|
||||
TextMessage message = session.createTextMessage(text);
|
||||
publisher.send(message);
|
||||
|
||||
} catch (NamingException | JMSException e) {
|
||||
res.getWriter().println("Error while trying to send <" + text + "> message: " + e.getMessage());
|
||||
}
|
||||
|
||||
res.getWriter().println("Message sent: " + text);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
## EthereumJ
|
||||
## Ethereum
|
||||
|
||||
### Relevant Articles:
|
||||
- [Introduction to EthereumJ](http://www.baeldung.com/ethereumj)
|
|
@ -0,0 +1,229 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.ethereum</groupId>
|
||||
<artifactId>ethereum</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>ethereum</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-spring-5</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-spring-5</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!-- Spring Boot Dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<version>${spring.boot.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<version>${spring.boot.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-tomcat</artifactId>
|
||||
<version>${spring.boot.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring Dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<version>${springframework.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Ethereum -->
|
||||
<dependency>
|
||||
<groupId>org.ethereum</groupId>
|
||||
<artifactId>ethereumj-core</artifactId>
|
||||
<version>${ethereumj-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.web3j</groupId>
|
||||
<artifactId>core</artifactId>
|
||||
<version>${web3j.core.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Jackson Dependencies -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-core</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-annotations</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Servlet -->
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jstl</artifactId>
|
||||
<version>${jstl.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>${javax-servlet.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet.jsp.jstl</groupId>
|
||||
<artifactId>jstl-api</artifactId>
|
||||
<version>${jstl.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet.jsp</groupId>
|
||||
<artifactId>javax.servlet.jsp-api</artifactId>
|
||||
<version>${javax-jsp.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Logging -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring Testing -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
<version>${spring.boot.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${springframework.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Testing -->
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.jsonpath</groupId>
|
||||
<artifactId>json-path</artifactId>
|
||||
<version>${jsonpath.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>ethereum</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>3.0.0</version>
|
||||
<configuration>
|
||||
<warSourceDirectory>src/main/webapp</warSourceDirectory>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>Ethereum</id>
|
||||
<name>Ethereum</name>
|
||||
<url>https://dl.bintray.com/ethereum/maven/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<tomcat.version>8.5.4</tomcat.version>
|
||||
<ethereumj-core.version>1.5.0-RELEASE</ethereumj-core.version>
|
||||
<web3j.core.version>3.3.1</web3j.core.version>
|
||||
<springframework.version>5.0.5.RELEASE</springframework.version>
|
||||
<spring.boot.version>1.5.6.RELEASE</spring.boot.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
<jackson-databind.version>2.5.0</jackson-databind.version>
|
||||
<hamcrest.version>1.3</hamcrest.version>
|
||||
<jackson.version>2.9.3</jackson.version>
|
||||
<javax-jsp.version>2.3.1</javax-jsp.version>
|
||||
<javax-servlet.version>3.1.0</javax-servlet.version>
|
||||
<jsonpath.version>2.4.0</jsonpath.version>
|
||||
<jstl.version>1.2</jstl.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<logback.version>1.2.3</logback.version>
|
||||
<slf4j.version>1.7.25</slf4j.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,68 @@
|
|||
package com.baeldung.web3j.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.springframework.web.servlet.resource.PathResourceResolver;
|
||||
import org.springframework.web.servlet.view.JstlView;
|
||||
import org.springframework.web.servlet.view.UrlBasedViewResolver;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@EnableAsync
|
||||
@ComponentScan("com.baeldung.web3j")
|
||||
public class AppConfig implements WebMvcConfigurer {
|
||||
|
||||
public void addViewControllers(ViewControllerRegistry registry) {
|
||||
registry.addViewController("/").setViewName("index");
|
||||
}
|
||||
|
||||
/**
|
||||
* Static resource locations including themes
|
||||
*/
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/resources/**/*")
|
||||
.addResourceLocations("/", "/resources/")
|
||||
.setCachePeriod(3600)
|
||||
.resourceChain(true)
|
||||
.addResolver(new PathResourceResolver());
|
||||
}
|
||||
|
||||
/**
|
||||
* View resolver for JSP
|
||||
*/
|
||||
@Bean
|
||||
public UrlBasedViewResolver viewResolver() {
|
||||
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
|
||||
resolver.setPrefix("/WEB-INF/jsp/");
|
||||
resolver.setSuffix(".jsp");
|
||||
resolver.setViewClass(JstlView.class);
|
||||
return resolver;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for async thread bean
|
||||
*
|
||||
* More: https://docs.spring.io/autorepo/docs/spring-framework/5.0.3.RELEASE/javadoc-api/org/springframework/scheduling/SchedulingTaskExecutor.html
|
||||
*/
|
||||
@Bean
|
||||
public Executor asyncExecutor() {
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
executor.setCorePoolSize(2);
|
||||
executor.setMaxPoolSize(2);
|
||||
executor.setQueueCapacity(500);
|
||||
executor.setThreadNamePrefix("CsvThread");
|
||||
executor.initialize();
|
||||
return executor;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.web3j.config;
|
||||
|
||||
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
|
||||
|
||||
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
|
||||
|
||||
//AbstractDispatcherServletInitializer override DEFAULT_SERVLET_NAME
|
||||
@Override
|
||||
protected String getServletName() {
|
||||
return "dispatcher";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getRootConfigClasses() {
|
||||
return new Class[]{};
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getServletConfigClasses() {
|
||||
return new Class[]{AppConfig.class};
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String[] getServletMappings() {
|
||||
return new String[]{"/"};
|
||||
}
|
||||
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue