Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
528a945426
|
@ -42,3 +42,9 @@ spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties
|
|||
*.springBeans
|
||||
|
||||
20171220-JMeter.csv
|
||||
|
||||
.factorypath
|
||||
dependency-reduced-pom.xml
|
||||
*.so
|
||||
*.dylib
|
||||
*.dll
|
||||
|
|
|
@ -1,10 +1,8 @@
|
|||
package com.baeldung.linkedlist;
|
||||
package com.baeldung.algorithms.middleelementlookup;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.Optional;
|
||||
|
||||
import com.baeldung.linkedlist.Node;
|
||||
|
||||
public class MiddleElementLookup {
|
||||
|
||||
public static Optional<String> findMiddleElementLinkedList(LinkedList<String> linkedList) {
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.linkedlist;
|
||||
package com.baeldung.algorithms.middleelementlookup;
|
||||
|
||||
public class Node {
|
||||
private Node next;
|
|
@ -1,11 +1,13 @@
|
|||
package com.baeldung.linkedlist;
|
||||
package algorithms;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import com.baeldung.algorithms.middleelementlookup.MiddleElementLookup;
|
||||
import com.baeldung.algorithms.middleelementlookup.Node;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.LinkedList;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
public class MiddleElementLookupUnitTest {
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
<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/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>antlr</artifactId>
|
||||
<name>antlr</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.antlr</groupId>
|
||||
<artifactId>antlr4-maven-plugin</artifactId>
|
||||
<version>${antlr.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>antlr4</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>build-helper-maven-plugin</artifactId>
|
||||
<version>${mojo.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>generate-sources</phase>
|
||||
<goals>
|
||||
<goal>add-source</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>${basedir}/target/generated-sources/antlr4</source>
|
||||
</sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.antlr</groupId>
|
||||
<artifactId>antlr4-runtime</artifactId>
|
||||
<version>${antlr.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
<antlr.version>4.7.1</antlr.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mojo.version>3.0.0</mojo.version>
|
||||
</properties>
|
||||
</project>
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,16 @@
|
|||
grammar Log;
|
||||
|
||||
log : entry+;
|
||||
entry : timestamp ' ' level ' ' message CRLF;
|
||||
timestamp : DATE ' ' TIME;
|
||||
level : 'ERROR' | 'INFO' | 'DEBUG';
|
||||
message : (TEXT | ' ')+;
|
||||
|
||||
fragment DIGIT : [0-9];
|
||||
fragment TWODIGIT : DIGIT DIGIT;
|
||||
fragment LETTER : [A-Za-z];
|
||||
|
||||
DATE : TWODIGIT TWODIGIT '-' LETTER LETTER LETTER '-' TWODIGIT;
|
||||
TIME : TWODIGIT ':' TWODIGIT ':' TWODIGIT;
|
||||
TEXT : LETTER+;
|
||||
CRLF : '\r'? '\n' | '\r';
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.antlr.java;
|
||||
|
||||
import com.baeldung.antlr.Java8BaseListener;
|
||||
import com.baeldung.antlr.Java8Parser;
|
||||
import org.antlr.v4.runtime.tree.TerminalNode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class UppercaseMethodListener extends Java8BaseListener {
|
||||
|
||||
private List<String> errors = new ArrayList<String>();
|
||||
|
||||
@Override
|
||||
public void enterMethodDeclarator(Java8Parser.MethodDeclaratorContext ctx) {
|
||||
TerminalNode node = ctx.Identifier();
|
||||
String methodName = node.getText();
|
||||
|
||||
if (Character.isUpperCase(methodName.charAt(0))){
|
||||
errors.add(String.format("Method %s is uppercased!", methodName));
|
||||
}
|
||||
}
|
||||
|
||||
public List<String> getErrors(){
|
||||
return Collections.unmodifiableList(errors);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
package com.baeldung.antlr.log;
|
||||
|
||||
import com.baeldung.antlr.LogBaseListener;
|
||||
import com.baeldung.antlr.LogParser;
|
||||
import com.baeldung.antlr.log.model.LogLevel;
|
||||
import com.baeldung.antlr.log.model.LogEntry;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
public class LogListener extends LogBaseListener {
|
||||
|
||||
private static final DateTimeFormatter DEFAULT_DATETIME_FORMATTER
|
||||
= DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss", Locale.ENGLISH);
|
||||
|
||||
private List<LogEntry> entries = new ArrayList<>();
|
||||
private LogEntry currentLogEntry;
|
||||
|
||||
@Override
|
||||
public void enterEntry(LogParser.EntryContext ctx) {
|
||||
this.currentLogEntry = new LogEntry();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void exitEntry(LogParser.EntryContext ctx) {
|
||||
entries.add(currentLogEntry);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enterTimestamp(LogParser.TimestampContext ctx) {
|
||||
currentLogEntry.setTimestamp(LocalDateTime.parse(ctx.getText(), DEFAULT_DATETIME_FORMATTER));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enterMessage(LogParser.MessageContext ctx) {
|
||||
currentLogEntry.setMessage(ctx.getText());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enterLevel(LogParser.LevelContext ctx) {
|
||||
currentLogEntry.setLevel(LogLevel.valueOf(ctx.getText()));
|
||||
}
|
||||
|
||||
public List<LogEntry> getEntries() {
|
||||
return Collections.unmodifiableList(entries);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package com.baeldung.antlr.log.model;
|
||||
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class LogEntry {
|
||||
|
||||
private LogLevel level;
|
||||
private String message;
|
||||
private LocalDateTime timestamp;
|
||||
|
||||
public LogLevel getLevel() {
|
||||
return level;
|
||||
}
|
||||
|
||||
public void setLevel(LogLevel level) {
|
||||
this.level = level;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public LocalDateTime getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public void setTimestamp(LocalDateTime timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.antlr.log.model;
|
||||
|
||||
public enum LogLevel {
|
||||
DEBUG, INFO, ERROR
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.antlr;
|
||||
|
||||
import com.baeldung.antlr.java.UppercaseMethodListener;
|
||||
import org.antlr.v4.runtime.CharStreams;
|
||||
import org.antlr.v4.runtime.CommonTokenStream;
|
||||
import org.antlr.v4.runtime.tree.ParseTree;
|
||||
import org.antlr.v4.runtime.tree.ParseTreeWalker;
|
||||
import org.junit.Test;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
|
||||
public class JavaParserUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenOneMethodStartsWithUpperCase_thenOneErrorReturned() throws Exception{
|
||||
|
||||
String javaClassContent = "public class SampleClass { void DoSomething(){} }";
|
||||
Java8Lexer java8Lexer = new Java8Lexer(CharStreams.fromString(javaClassContent));
|
||||
CommonTokenStream tokens = new CommonTokenStream(java8Lexer);
|
||||
Java8Parser java8Parser = new Java8Parser(tokens);
|
||||
ParseTree tree = java8Parser.compilationUnit();
|
||||
ParseTreeWalker walker = new ParseTreeWalker();
|
||||
UppercaseMethodListener uppercaseMethodListener = new UppercaseMethodListener();
|
||||
walker.walk(uppercaseMethodListener, tree);
|
||||
|
||||
assertThat(uppercaseMethodListener.getErrors().size(), is(1));
|
||||
assertThat(uppercaseMethodListener.getErrors().get(0),
|
||||
is("Method DoSomething is uppercased!"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.antlr;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
|
||||
import com.baeldung.antlr.log.LogListener;
|
||||
import com.baeldung.antlr.log.model.LogLevel;
|
||||
import com.baeldung.antlr.log.model.LogEntry;
|
||||
import org.antlr.v4.runtime.CharStreams;
|
||||
import org.antlr.v4.runtime.CommonTokenStream;
|
||||
import org.antlr.v4.runtime.tree.ParseTreeWalker;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
|
||||
public class LogParserUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenLogContainsOneErrorLogEntry_thenOneErrorIsReturned() throws Exception {
|
||||
String logLines = "2018-May-05 14:20:21 DEBUG entering awesome method\r\n" +
|
||||
"2018-May-05 14:20:24 ERROR Bad thing happened\r\n";
|
||||
LogLexer serverLogLexer = new LogLexer(CharStreams.fromString(logLines));
|
||||
CommonTokenStream tokens = new CommonTokenStream( serverLogLexer );
|
||||
LogParser logParser = new LogParser(tokens);
|
||||
ParseTreeWalker walker = new ParseTreeWalker();
|
||||
LogListener logWalker = new LogListener();
|
||||
walker.walk(logWalker, logParser.log());
|
||||
|
||||
assertThat(logWalker.getEntries().size(), is(2));
|
||||
LogEntry error = logWalker.getEntries().get(1);
|
||||
assertThat(error.getLevel(), is(LogLevel.ERROR));
|
||||
assertThat(error.getMessage(), is("Bad thing happened"));
|
||||
assertThat(error.getTimestamp(), is(LocalDateTime.of(2018,5,5,14,20,24)));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,99 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>aws-lambda</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>aws-lambda</name>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-java-sdk-dynamodb</artifactId>
|
||||
<version>1.11.241</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-java-sdk-core</artifactId>
|
||||
<version>1.11.241</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-lambda-java-core</artifactId>
|
||||
<version>${aws-lambda-java-core.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-lambda-java-events</artifactId>
|
||||
<version>${aws-lambda-java-events.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>${gson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.googlecode.json-simple</groupId>
|
||||
<artifactId>json-simple</artifactId>
|
||||
<version>${json-simple.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>${maven-shade-plugin.version}</version>
|
||||
<configuration>
|
||||
<createDependencyReducedPom>false</createDependencyReducedPom>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<properties>
|
||||
<json-simple.version>1.1.1</json-simple.version>
|
||||
<org.json.version>20180130</org.json.version>
|
||||
<commons-io.version>2.5</commons-io.version>
|
||||
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
|
||||
<aws-lambda-java-core.version>1.2.0</aws-lambda-java-core.version>
|
||||
<gson.version>2.8.2</gson.version>
|
||||
<aws-java-sdk-core.version>1.11.241</aws-java-sdk-core.version>
|
||||
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
|
||||
<maven-dependency-plugin.version>2.10</maven-dependency-plugin.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,166 @@
|
|||
package com.baeldung.lambda.apigateway;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
|
||||
import com.amazonaws.services.dynamodbv2.document.*;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.PutItemSpec;
|
||||
import com.amazonaws.services.lambda.runtime.Context;
|
||||
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
|
||||
import com.baeldung.lambda.apigateway.model.Person;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
import org.json.simple.parser.ParseException;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
public class APIDemoHandler implements RequestStreamHandler {
|
||||
|
||||
private JSONParser parser = new JSONParser();
|
||||
private static final String DYNAMODB_TABLE_NAME = System.getenv("TABLE_NAME");
|
||||
|
||||
@Override
|
||||
public void handleRequest(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);
|
||||
|
||||
try {
|
||||
JSONObject event = (JSONObject) parser.parse(reader);
|
||||
|
||||
if (event.get("body") != null) {
|
||||
|
||||
Person person = new Person((String) event.get("body"));
|
||||
|
||||
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())));
|
||||
}
|
||||
|
||||
JSONObject responseBody = new JSONObject();
|
||||
responseBody.put("message", "New item created");
|
||||
|
||||
JSONObject headerJson = new JSONObject();
|
||||
headerJson.put("x-custom-header", "my custom header value");
|
||||
|
||||
responseJson.put("statusCode", 200);
|
||||
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 handleGetByPathParam(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("pathParameters") != null) {
|
||||
|
||||
JSONObject pps = (JSONObject) event.get("pathParameters");
|
||||
if (pps.get("id") != null) {
|
||||
|
||||
int id = Integer.parseInt((String) pps.get("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) {
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,68 @@
|
|||
package com.baeldung.lambda.apigateway.model;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
|
||||
public class Person {
|
||||
|
||||
private int id;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private int age;
|
||||
private String address;
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
final Gson gson = new GsonBuilder().setPrettyPrinting().create();
|
||||
return gson.toJson(this);
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
20
cdi/pom.xml
20
cdi/pom.xml
|
@ -14,6 +14,24 @@
|
|||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<version>1.3</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.10.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
|
@ -42,4 +60,4 @@
|
|||
<weld-se-core.version>2.4.1.Final</weld-se-core.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.dependencyinjection.application;
|
||||
|
||||
import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor;
|
||||
import org.jboss.weld.environment.se.Weld;
|
||||
import org.jboss.weld.environment.se.WeldContainer;
|
||||
|
||||
public class FileApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Weld weld = new Weld();
|
||||
WeldContainer container = weld.initialize();
|
||||
ImageFileProcessor imageFileProcessor = container.select(ImageFileProcessor.class).get();
|
||||
System.out.println(imageFileProcessor.openFile("file1.png"));
|
||||
System.out.println(imageFileProcessor.writeFile("file1.png"));
|
||||
System.out.println(imageFileProcessor.saveFile("file1.png"));
|
||||
container.shutdown();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.dependencyinjection.factories;
|
||||
|
||||
import com.baeldung.dependencyinjection.loggers.TimeLogger;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import javax.enterprise.inject.Produces;
|
||||
|
||||
public class TimeLoggerFactory {
|
||||
|
||||
@Produces
|
||||
public TimeLogger getTimeLogger() {
|
||||
return new TimeLogger(new SimpleDateFormat("HH:mm"), Calendar.getInstance());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.dependencyinjection.imagefileeditors;
|
||||
|
||||
import com.baeldung.dependencyinjection.qualifiers.GifFileEditorQualifier;
|
||||
|
||||
@GifFileEditorQualifier
|
||||
public class GifFileEditor implements ImageFileEditor {
|
||||
|
||||
@Override
|
||||
public String openFile(String fileName) {
|
||||
return "Opening GIF file " + fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String editFile(String fileName) {
|
||||
return "Editing GIF file " + fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String writeFile(String fileName) {
|
||||
return "Writing GIF file " + fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String saveFile(String fileName) {
|
||||
return "Saving GIF file " + fileName;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.dependencyinjection.imagefileeditors;
|
||||
|
||||
public interface ImageFileEditor {
|
||||
|
||||
String openFile(String fileName);
|
||||
|
||||
String editFile(String fileName);
|
||||
|
||||
String writeFile(String fileName);
|
||||
|
||||
String saveFile(String fileName);
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.dependencyinjection.imagefileeditors;
|
||||
|
||||
import com.baeldung.dependencyinjection.qualifiers.JpgFileEditorQualifier;
|
||||
|
||||
@JpgFileEditorQualifier
|
||||
public class JpgFileEditor implements ImageFileEditor {
|
||||
|
||||
@Override
|
||||
public String openFile(String fileName) {
|
||||
return "Opening JPG file " + fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String editFile(String fileName) {
|
||||
return "Editing JPG file " + fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String writeFile(String fileName) {
|
||||
return "Writing JPG file " + fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String saveFile(String fileName) {
|
||||
return "Saving JPG file " + fileName;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.dependencyinjection.imagefileeditors;
|
||||
|
||||
import com.baeldung.dependencyinjection.qualifiers.PngFileEditorQualifier;
|
||||
|
||||
@PngFileEditorQualifier
|
||||
public class PngFileEditor implements ImageFileEditor {
|
||||
|
||||
@Override
|
||||
public String openFile(String fileName) {
|
||||
return "Opening PNG file " + fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String editFile(String fileName) {
|
||||
return "Editing PNG file " + fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String writeFile(String fileName) {
|
||||
return "Writing PNG file " + fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String saveFile(String fileName) {
|
||||
return "Saving PNG file " + fileName;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.dependencyinjection.imageprocessors;
|
||||
|
||||
import com.baeldung.dependencyinjection.loggers.TimeLogger;
|
||||
import com.baeldung.dependencyinjection.qualifiers.PngFileEditorQualifier;
|
||||
import javax.inject.Inject;
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.ImageFileEditor;
|
||||
|
||||
public class ImageFileProcessor {
|
||||
|
||||
private final ImageFileEditor imageFileEditor;
|
||||
private final TimeLogger timeLogger;
|
||||
|
||||
@Inject
|
||||
public ImageFileProcessor(@PngFileEditorQualifier ImageFileEditor imageFileEditor, TimeLogger timeLogger) {
|
||||
this.imageFileEditor = imageFileEditor;
|
||||
this.timeLogger = timeLogger;
|
||||
}
|
||||
|
||||
public ImageFileEditor getImageFileditor() {
|
||||
return imageFileEditor;
|
||||
}
|
||||
|
||||
public TimeLogger getTimeLogger() {
|
||||
return timeLogger;
|
||||
}
|
||||
|
||||
public String openFile(String fileName) {
|
||||
return imageFileEditor.openFile(fileName) + " at: " + timeLogger.getTime();
|
||||
}
|
||||
|
||||
public String editFile(String fileName) {
|
||||
return imageFileEditor.editFile(fileName) + " at: " + timeLogger.getTime();
|
||||
}
|
||||
|
||||
public String writeFile(String fileName) {
|
||||
return imageFileEditor.writeFile(fileName) + " at: " + timeLogger.getTime();
|
||||
}
|
||||
|
||||
public String saveFile(String fileName) {
|
||||
return imageFileEditor.saveFile(fileName)+ " at: " + timeLogger.getTime();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.dependencyinjection.loggers;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
|
||||
public class TimeLogger {
|
||||
|
||||
private final SimpleDateFormat dateFormat;
|
||||
private final Calendar calendar;
|
||||
|
||||
public TimeLogger(SimpleDateFormat dateFormat, Calendar calendar) {
|
||||
this.dateFormat = dateFormat;
|
||||
this.calendar = calendar;
|
||||
}
|
||||
|
||||
public String getTime() {
|
||||
return dateFormat.format(calendar.getTime());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.dependencyinjection.qualifiers;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import javax.inject.Qualifier;
|
||||
|
||||
@Qualifier
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
|
||||
public @interface GifFileEditorQualifier {}
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.dependencyinjection.qualifiers;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import javax.inject.Qualifier;
|
||||
|
||||
@Qualifier
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
|
||||
public @interface JpgFileEditorQualifier {}
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.dependencyinjection.qualifiers;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import javax.inject.Qualifier;
|
||||
|
||||
@Qualifier
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
|
||||
public @interface PngFileEditorQualifier {}
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.test.dependencyinjection;
|
||||
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.GifFileEditor;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GifFileEditorUnitTest {
|
||||
|
||||
private static GifFileEditor gifFileEditor;
|
||||
|
||||
|
||||
@BeforeClass
|
||||
public static void setGifFileEditorInstance() {
|
||||
gifFileEditor = new GifFileEditor();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGifFileEditorlInstance_whenCalledopenFile_thenOneAssertion() {
|
||||
assertThat(gifFileEditor.openFile("file1.gif")).isEqualTo("Opening GIF file file1.gif");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGifFileEditorlInstance_whenCallededitFile_thenOneAssertion() {
|
||||
assertThat(gifFileEditor.editFile("file1.gif")).isEqualTo("Editing GIF file file1.gif");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGifFileEditorInstance_whenCalledwriteFile_thenOneAssertion() {
|
||||
assertThat(gifFileEditor.writeFile("file1.gif")).isEqualTo("Writing GIF file file1.gif");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGifFileEditorInstance_whenCalledsaveFile_thenOneAssertion() {
|
||||
assertThat(gifFileEditor.saveFile("file1.gif")).isEqualTo("Saving GIF file file1.gif");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,70 @@
|
|||
package com.baeldung.test.dependencyinjection;
|
||||
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.GifFileEditor;
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.JpgFileEditor;
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor;
|
||||
import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor;
|
||||
import com.baeldung.dependencyinjection.loggers.TimeLogger;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.jboss.weld.environment.se.Weld;
|
||||
import org.jboss.weld.environment.se.WeldContainer;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ImageProcessorUnitTest {
|
||||
|
||||
private static ImageFileProcessor imageFileProcessor;
|
||||
private static SimpleDateFormat dateFormat;
|
||||
private static Calendar calendar;
|
||||
|
||||
|
||||
@BeforeClass
|
||||
public static void setImageProcessorInstance() {
|
||||
Weld weld = new Weld();
|
||||
WeldContainer container = weld.initialize();
|
||||
imageFileProcessor = container.select(ImageFileProcessor.class).get();
|
||||
container.shutdown();
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setSimpleDateFormatInstance() {
|
||||
dateFormat = new SimpleDateFormat("HH:mm");
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setCalendarInstance() {
|
||||
calendar = Calendar.getInstance();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenInjectedPngFileEditorandTimeLoggerInstances_thenTwoAssertions() {
|
||||
assertThat(imageFileProcessor.getImageFileditor()).isInstanceOf(PngFileEditor.class);
|
||||
assertThat(imageFileProcessor.getTimeLogger()).isInstanceOf(TimeLogger.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() {
|
||||
String currentTime = dateFormat.format(calendar.getTime());
|
||||
assertThat(imageFileProcessor.openFile("file1.png")).isEqualTo("Opening PNG file file1.png at: " + currentTime);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() {
|
||||
String currentTime = dateFormat.format(calendar.getTime());
|
||||
assertThat(imageFileProcessor.editFile("file1.png")).isEqualTo("Editing PNG file file1.png at: " + currentTime);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() {
|
||||
String currentTime = dateFormat.format(calendar.getTime());
|
||||
assertThat(imageFileProcessor.writeFile("file1.png")).isEqualTo("Writing PNG file file1.png at: " + currentTime);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() {
|
||||
String currentTime = dateFormat.format(calendar.getTime());
|
||||
assertThat(imageFileProcessor.saveFile("file1.png")).isEqualTo("Saving PNG file file1.png at: " + currentTime);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.test.dependencyinjection;
|
||||
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.JpgFileEditor;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class JpgFileEditorUnitTest {
|
||||
|
||||
private static JpgFileEditor jpgFileUtil;
|
||||
|
||||
|
||||
@BeforeClass
|
||||
public static void setJpgFileEditorInstance() {
|
||||
jpgFileUtil = new JpgFileEditor();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJpgFileEditorInstance_whenCalledopenFile_thenOneAssertion() {
|
||||
assertThat(jpgFileUtil.openFile("file1.jpg")).isEqualTo("Opening JPG file file1.jpg");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJpgFileEditorlInstance_whenCallededitFile_thenOneAssertion() {
|
||||
assertThat(jpgFileUtil.editFile("file1.gif")).isEqualTo("Editing JPG file file1.gif");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJpgFileEditorInstance_whenCalledwriteFile_thenOneAssertion() {
|
||||
assertThat(jpgFileUtil.writeFile("file1.jpg")).isEqualTo("Writing JPG file file1.jpg");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJpgFileEditorInstance_whenCalledsaveFile_thenOneAssertion() {
|
||||
assertThat(jpgFileUtil.saveFile("file1.jpg")).isEqualTo("Saving JPG file file1.jpg");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.test.dependencyinjection;
|
||||
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor;
|
||||
import com.baeldung.dependencyinjection.qualifiers.PngFileEditorQualifier;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
@PngFileEditorQualifier
|
||||
public class PngFileEditorUnitTest {
|
||||
|
||||
private static PngFileEditor pngFileEditor;
|
||||
|
||||
|
||||
@BeforeClass
|
||||
public static void setPngFileEditorInstance() {
|
||||
pngFileEditor = new PngFileEditor();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPngFileEditorInstance_whenCalledopenFile_thenOneAssertion() {
|
||||
assertThat(pngFileEditor.openFile("file1.png")).isEqualTo("Opening PNG file file1.png");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPngFileEditorInstance_whenCallededitFile_thenOneAssertion() {
|
||||
assertThat(pngFileEditor.editFile("file1.png")).isEqualTo("Editing PNG file file1.png");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPngFileEditorInstance_whenCalledwriteFile_thenOneAssertion() {
|
||||
assertThat(pngFileEditor.writeFile("file1.png")).isEqualTo("Writing PNG file file1.png");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPngFileEditorInstance_whenCalledsaveFile_thenOneAssertion() {
|
||||
assertThat(pngFileEditor.saveFile("file1.png")).isEqualTo("Saving PNG file file1.png");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.test.dependencyinjection;
|
||||
|
||||
import com.baeldung.dependencyinjection.factories.TimeLoggerFactory;
|
||||
import com.baeldung.dependencyinjection.loggers.TimeLogger;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TimeLoggerFactoryUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTimeLoggerFactory_whenCalledgetTimeLogger_thenOneAssertion() {
|
||||
TimeLoggerFactory timeLoggerFactory = new TimeLoggerFactory();
|
||||
assertThat(timeLoggerFactory.getTimeLogger()).isInstanceOf(TimeLogger.class);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.test.dependencyinjection;
|
||||
|
||||
import com.baeldung.dependencyinjection.loggers.TimeLogger;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TimeLoggerUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void givenTimeLoggerInstance_whenCalledgetLogTime_thenOneAssertion() {
|
||||
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
TimeLogger timeLogger = new TimeLogger(dateFormat, calendar);
|
||||
String currentTime = dateFormat.format(calendar.getTime());
|
||||
assertThat(timeLogger.getTime()).isEqualTo(currentTime);
|
||||
}
|
||||
}
|
|
@ -53,3 +53,4 @@
|
|||
- [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get)
|
||||
- [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)
|
||||
|
|
|
@ -3,6 +3,7 @@ package com.baeldung.datetime;
|
|||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
|
||||
|
@ -43,4 +44,30 @@ class UseLocalDate {
|
|||
LocalDateTime startofDay = localDate.atStartOfDay();
|
||||
return startofDay;
|
||||
}
|
||||
|
||||
LocalDateTime getStartOfDayOfLocalDate(LocalDate localDate) {
|
||||
LocalDateTime startofDay = LocalDateTime.of(localDate, LocalTime.MIDNIGHT);
|
||||
return startofDay;
|
||||
}
|
||||
|
||||
LocalDateTime getStartOfDayAtMinTime(LocalDate localDate) {
|
||||
LocalDateTime startofDay = localDate.atTime(LocalTime.MIN);
|
||||
return startofDay;
|
||||
}
|
||||
|
||||
LocalDateTime getStartOfDayAtMidnightTime(LocalDate localDate) {
|
||||
LocalDateTime startofDay = localDate.atTime(LocalTime.MIDNIGHT);
|
||||
return startofDay;
|
||||
}
|
||||
|
||||
LocalDateTime getEndOfDay(LocalDate localDate) {
|
||||
LocalDateTime endOfDay = localDate.atTime(LocalTime.MAX);
|
||||
return endOfDay;
|
||||
}
|
||||
|
||||
LocalDateTime getEndOfDayFromLocalTime(LocalDate localDate) {
|
||||
LocalDateTime endOfDate = LocalTime.MAX.atDate(localDate);
|
||||
return endOfDate;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,6 +1,8 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.temporal.ChronoField;
|
||||
|
||||
public class UseLocalDateTime {
|
||||
|
||||
|
@ -8,4 +10,15 @@ public class UseLocalDateTime {
|
|||
return LocalDateTime.parse(representation);
|
||||
}
|
||||
|
||||
LocalDateTime getEndOfDayFromLocalDateTimeDirectly(LocalDateTime localDateTime) {
|
||||
LocalDateTime endOfDate = localDateTime.with(ChronoField.NANO_OF_DAY, LocalTime.MAX.toNanoOfDay());
|
||||
return endOfDate;
|
||||
}
|
||||
|
||||
LocalDateTime getEndOfDayFromLocalDateTime(LocalDateTime localDateTime) {
|
||||
LocalDateTime endOfDate = localDateTime.toLocalDate()
|
||||
.atTime(LocalTime.MAX);
|
||||
return endOfDate;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,12 +1,42 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.temporal.ChronoField;
|
||||
|
||||
class UseZonedDateTime {
|
||||
|
||||
ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
|
||||
return ZonedDateTime.of(localDateTime, zoneId);
|
||||
}
|
||||
|
||||
ZonedDateTime getStartOfDay(LocalDate localDate, ZoneId zone) {
|
||||
ZonedDateTime startofDay = localDate.atStartOfDay()
|
||||
.atZone(zone);
|
||||
return startofDay;
|
||||
}
|
||||
|
||||
ZonedDateTime getStartOfDayShorthand(LocalDate localDate, ZoneId zone) {
|
||||
ZonedDateTime startofDay = localDate.atStartOfDay(zone);
|
||||
return startofDay;
|
||||
}
|
||||
|
||||
ZonedDateTime getStartOfDayFromZonedDateTime(ZonedDateTime zonedDateTime) {
|
||||
ZonedDateTime startofDay = zonedDateTime.toLocalDateTime()
|
||||
.toLocalDate()
|
||||
.atStartOfDay(zonedDateTime.getZone());
|
||||
return startofDay;
|
||||
}
|
||||
|
||||
ZonedDateTime getStartOfDayAtMinTime(ZonedDateTime zonedDateTime) {
|
||||
ZonedDateTime startofDay = zonedDateTime.with(ChronoField.HOUR_OF_DAY, 0);
|
||||
return startofDay;
|
||||
}
|
||||
|
||||
ZonedDateTime getStartOfDayAtMidnightTime(ZonedDateTime zonedDateTime) {
|
||||
ZonedDateTime startofDay = zonedDateTime.with(ChronoField.NANO_OF_DAY, 0);
|
||||
return startofDay;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,13 +1,15 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.Month;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class UseLocalDateTimeUnitTest {
|
||||
|
||||
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
|
||||
|
@ -19,4 +21,16 @@ public class UseLocalDateTimeUnitTest {
|
|||
assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30")
|
||||
.toLocalTime());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDateTime_whenSettingEndOfDay_thenReturnLastMomentOfDay() {
|
||||
LocalDateTime givenTimed = LocalDateTime.parse("2018-06-23T05:55:55");
|
||||
|
||||
LocalDateTime endOfDayFromGivenDirectly = useLocalDateTime.getEndOfDayFromLocalDateTimeDirectly(givenTimed);
|
||||
LocalDateTime endOfDayFromGiven = useLocalDateTime.getEndOfDayFromLocalDateTime(givenTimed);
|
||||
|
||||
assertThat(endOfDayFromGivenDirectly).isEqualTo(endOfDayFromGiven);
|
||||
assertThat(endOfDayFromGivenDirectly.toLocalTime()).isEqualTo(LocalTime.MAX);
|
||||
assertThat(endOfDayFromGivenDirectly.toString()).isEqualTo("2018-06-23T23:59:59.999999999");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,13 +1,15 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class UseLocalDateUnitTest {
|
||||
|
||||
UseLocalDate useLocalDate = new UseLocalDate();
|
||||
|
@ -57,4 +59,33 @@ public class UseLocalDateUnitTest {
|
|||
assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDate_whenSettingStartOfDay_thenReturnMidnightInAllCases() {
|
||||
LocalDate given = LocalDate.parse("2018-06-23");
|
||||
|
||||
LocalDateTime startOfDayWithMethod = useLocalDate.getStartOfDay(given);
|
||||
LocalDateTime startOfDayOfLocalDate = useLocalDate.getStartOfDayOfLocalDate(given);
|
||||
LocalDateTime startOfDayWithMin = useLocalDate.getStartOfDayAtMinTime(given);
|
||||
LocalDateTime startOfDayWithMidnight = useLocalDate.getStartOfDayAtMidnightTime(given);
|
||||
|
||||
assertThat(startOfDayWithMethod).isEqualTo(startOfDayWithMin)
|
||||
.isEqualTo(startOfDayWithMidnight)
|
||||
.isEqualTo(startOfDayOfLocalDate)
|
||||
.isEqualTo(LocalDateTime.parse("2018-06-23T00:00:00"));
|
||||
assertThat(startOfDayWithMin.toLocalTime()).isEqualTo(LocalTime.MIDNIGHT);
|
||||
assertThat(startOfDayWithMin.toString()).isEqualTo("2018-06-23T00:00");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDate_whenSettingEndOfDay_thenReturnLastMomentOfDay() {
|
||||
LocalDate given = LocalDate.parse("2018-06-23");
|
||||
|
||||
LocalDateTime endOfDayWithMax = useLocalDate.getEndOfDay(given);
|
||||
LocalDateTime endOfDayFromLocalTime = useLocalDate.getEndOfDayFromLocalTime(given);
|
||||
|
||||
assertThat(endOfDayWithMax).isEqualTo(endOfDayFromLocalTime);
|
||||
assertThat(endOfDayWithMax.toLocalTime()).isEqualTo(LocalTime.MAX);
|
||||
assertThat(endOfDayWithMax.toString()).isEqualTo("2018-06-23T23:59:59.999999999");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,6 +1,10 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
|
@ -17,4 +21,25 @@ public class UseZonedDateTimeUnitTest {
|
|||
ZonedDateTime zonedDatetime = zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId);
|
||||
Assert.assertEquals(zoneId, ZoneId.from(zonedDatetime));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDateOrZoned_whenSettingStartOfDay_thenReturnMidnightInAllCases() {
|
||||
LocalDate given = LocalDate.parse("2018-06-23");
|
||||
ZoneId zone = ZoneId.of("Europe/Paris");
|
||||
ZonedDateTime zonedGiven = ZonedDateTime.of(given, LocalTime.NOON, zone);
|
||||
|
||||
ZonedDateTime startOfOfDayWithMethod = zonedDateTime.getStartOfDay(given, zone);
|
||||
ZonedDateTime startOfOfDayWithShorthandMethod = zonedDateTime.getStartOfDayShorthand(given, zone);
|
||||
ZonedDateTime startOfOfDayFromZonedDateTime = zonedDateTime.getStartOfDayFromZonedDateTime(zonedGiven);
|
||||
ZonedDateTime startOfOfDayAtMinTime = zonedDateTime.getStartOfDayAtMinTime(zonedGiven);
|
||||
ZonedDateTime startOfOfDayAtMidnightTime = zonedDateTime.getStartOfDayAtMidnightTime(zonedGiven);
|
||||
|
||||
assertThat(startOfOfDayWithMethod).isEqualTo(startOfOfDayWithShorthandMethod)
|
||||
.isEqualTo(startOfOfDayFromZonedDateTime)
|
||||
.isEqualTo(startOfOfDayAtMinTime)
|
||||
.isEqualTo(startOfOfDayAtMidnightTime);
|
||||
assertThat(startOfOfDayWithMethod.toLocalTime()).isEqualTo(LocalTime.MIDNIGHT);
|
||||
assertThat(startOfOfDayWithMethod.toLocalTime()
|
||||
.toString()).isEqualTo("00:00");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -220,6 +220,7 @@
|
|||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*IntTest.java</exclude>
|
||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
|
@ -289,6 +290,7 @@
|
|||
</excludes>
|
||||
<includes>
|
||||
<include>**/*IntegrationTest.java</include>
|
||||
<include>**/*IntTest.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
|
|
|
@ -353,6 +353,7 @@
|
|||
</excludes>
|
||||
<includes>
|
||||
<include>**/*IntegrationTest.java</include>
|
||||
<include>**/*IntTest.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
|
|
|
@ -203,6 +203,11 @@
|
|||
<artifactId>mail</artifactId>
|
||||
<version>1.5.0-b01</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.ibm.icu</groupId>
|
||||
<artifactId>icu4j</artifactId>
|
||||
<version>${icu4j.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -222,6 +227,7 @@
|
|||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*IntTest.java</exclude>
|
||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
|
@ -387,6 +393,7 @@
|
|||
</excludes>
|
||||
<includes>
|
||||
<include>**/*IntegrationTest.java</include>
|
||||
<include>**/*IntTest.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
|
@ -471,6 +478,7 @@
|
|||
<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>
|
||||
<icu4j.version>61.1</icu4j.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.date;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public class DateWithoutTime {
|
||||
|
||||
public static Date getDateWithoutTimeUsingCalendar() {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.set(Calendar.HOUR_OF_DAY, 0);
|
||||
calendar.set(Calendar.MINUTE, 0);
|
||||
calendar.set(Calendar.SECOND, 0);
|
||||
calendar.set(Calendar.MILLISECOND, 0);
|
||||
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date getDateWithoutTimeUsingFormat() throws ParseException {
|
||||
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
|
||||
return formatter.parse(formatter.format(new Date()));
|
||||
}
|
||||
|
||||
public static LocalDate getLocalDate() {
|
||||
return LocalDate.now();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public class DateExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(Date date) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
return calendar.get(Calendar.YEAR);
|
||||
}
|
||||
|
||||
int getMonth(Date date) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
return calendar.get(Calendar.MONTH);
|
||||
}
|
||||
|
||||
int getDay(Date date) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
return calendar.get(Calendar.DAY_OF_MONTH);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
public class LocalDateExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(LocalDate localDate) {
|
||||
return localDate.getYear();
|
||||
}
|
||||
|
||||
int getMonth(LocalDate localDate) {
|
||||
return localDate.getMonthValue();
|
||||
}
|
||||
|
||||
int getDay(LocalDate localDate) {
|
||||
return localDate.getDayOfMonth();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class LocalDateTimeExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(LocalDateTime localDateTime) {
|
||||
return localDateTime.getYear();
|
||||
}
|
||||
|
||||
int getMonth(LocalDateTime localDateTime) {
|
||||
return localDateTime.getMonthValue();
|
||||
}
|
||||
|
||||
int getDay(LocalDateTime localDateTime) {
|
||||
return localDateTime.getDayOfMonth();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
public class OffsetDateTimeExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(OffsetDateTime offsetDateTime) {
|
||||
return offsetDateTime.getYear();
|
||||
}
|
||||
|
||||
int getMonth(OffsetDateTime offsetDateTime) {
|
||||
return offsetDateTime.getMonthValue();
|
||||
}
|
||||
|
||||
int getDay(OffsetDateTime offsetDateTime) {
|
||||
return offsetDateTime.getDayOfMonth();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
public class ZonedDateTimeExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(ZonedDateTime zonedDateTime) {
|
||||
return zonedDateTime.getYear();
|
||||
}
|
||||
|
||||
int getMonth(ZonedDateTime zonedDateTime) {
|
||||
return zonedDateTime.getMonthValue();
|
||||
}
|
||||
|
||||
int getDay(ZonedDateTime zonedDateTime) {
|
||||
return zonedDateTime.getDayOfMonth();
|
||||
}
|
||||
}
|
|
@ -3,18 +3,18 @@ package com.baeldung.extension;
|
|||
import com.google.common.io.Files;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class Extension {
|
||||
//Instead of file name we can also specify full path of a file eg. /baeldung/com/demo/abc.java
|
||||
public String getExtensionByApacheCommonLib(String filename) {
|
||||
return FilenameUtils.getExtension(filename);
|
||||
}
|
||||
|
||||
public String getExtensionByStringHandling(String filename) {
|
||||
String fileExtension = "";
|
||||
if (filename.contains(".") && filename.lastIndexOf(".") != 0) {
|
||||
fileExtension = filename.substring(filename.lastIndexOf(".") + 1);
|
||||
}
|
||||
return fileExtension;
|
||||
public Optional<String> getExtensionByStringHandling(String filename) {
|
||||
return Optional.ofNullable(filename)
|
||||
.filter(f -> f.contains("."))
|
||||
.map(f -> f.substring(filename.lastIndexOf(".") + 1));
|
||||
}
|
||||
|
||||
public String getExtensionByGuava(String filename) {
|
||||
|
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.immutableobjects;
|
||||
|
||||
public final class Currency {
|
||||
|
||||
private final String value;
|
||||
|
||||
private Currency(String currencyValue) {
|
||||
value = currencyValue;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public static Currency of(String value) {
|
||||
return new Currency(value);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.immutableobjects;
|
||||
|
||||
// 4. Immutability in Java
|
||||
public final class Money {
|
||||
private final double amount;
|
||||
private final Currency currency;
|
||||
|
||||
public Money(double amount, Currency currency) {
|
||||
this.amount = amount;
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
public Currency getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
public double getAmount() {
|
||||
return amount;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.manifest;
|
||||
|
||||
public class AppExample {
|
||||
|
||||
public static void main(String[] args){
|
||||
System.out.println("AppExample executed!");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
package com.baeldung.manifest;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
public class ExecuteJarFile {
|
||||
|
||||
private static final String DELIMITER = " ";
|
||||
private static final String WORK_PATH = "src/main/java/com/baeldung/manifest";
|
||||
private static final String MANIFEST_MF_PATH = WORK_PATH + "/MANIFEST.MF";
|
||||
private static final String MAIN_MANIFEST_ATTRIBUTE = "Main-Class: com.baeldung.manifest.AppExample";
|
||||
|
||||
private static final String COMPILE_COMMAND = "javac -d . AppExample.java";
|
||||
private static final String CREATE_JAR_WITHOUT_MF_ATT_COMMAND = "jar cvf example.jar com/baeldung/manifest/AppExample.class";
|
||||
private static final String CREATE_JAR_WITH_MF_ATT_COMMAND = "jar cvmf MANIFEST.MF example.jar com/baeldung/manifest/AppExample.class";
|
||||
private static final String EXECUTE_JAR_COMMAND = "java -jar example.jar";
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(executeJarWithoutManifestAttribute());
|
||||
System.out.println(executeJarWithManifestAttribute());
|
||||
}
|
||||
|
||||
public static String executeJarWithoutManifestAttribute() {
|
||||
return executeJar(CREATE_JAR_WITHOUT_MF_ATT_COMMAND);
|
||||
}
|
||||
|
||||
public static String executeJarWithManifestAttribute() {
|
||||
createManifestFile();
|
||||
return executeJar(CREATE_JAR_WITH_MF_ATT_COMMAND);
|
||||
}
|
||||
|
||||
private static void createManifestFile() {
|
||||
BufferedWriter writer;
|
||||
try {
|
||||
writer = new BufferedWriter(new FileWriter(MANIFEST_MF_PATH));
|
||||
writer.write(MAIN_MANIFEST_ATTRIBUTE);
|
||||
writer.newLine();
|
||||
writer.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static String executeJar(String createJarCommand) {
|
||||
executeCommand(COMPILE_COMMAND);
|
||||
executeCommand(createJarCommand);
|
||||
return executeCommand(EXECUTE_JAR_COMMAND);
|
||||
}
|
||||
|
||||
private static String executeCommand(String command) {
|
||||
String output = null;
|
||||
try {
|
||||
output = collectOutput(runProcess(command));
|
||||
} catch (Exception ex) {
|
||||
System.out.println(ex);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
private static String collectOutput(Process process) throws IOException {
|
||||
StringBuffer output = new StringBuffer();
|
||||
BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
||||
String line = "";
|
||||
while ((line = outputReader.readLine()) != null) {
|
||||
output.append(line + "\n");
|
||||
}
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
private static Process runProcess(String command) throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder(command.split(DELIMITER));
|
||||
builder.directory(new File(WORK_PATH).getAbsoluteFile());
|
||||
builder.redirectErrorStream(true);
|
||||
Process process = builder.start();
|
||||
process.waitFor();
|
||||
return process;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,68 @@
|
|||
package com.baeldung.string;
|
||||
|
||||
import com.ibm.icu.lang.UCharacter;
|
||||
import com.ibm.icu.text.BreakIterator;
|
||||
import org.apache.commons.lang.WordUtils;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class TitleCaseConverter {
|
||||
|
||||
private static final String WORD_SEPARATOR = " ";
|
||||
|
||||
public static String convertToTitleCaseIteratingChars(String text) {
|
||||
if (text == null || text.isEmpty()) {
|
||||
return text;
|
||||
}
|
||||
|
||||
StringBuilder converted = new StringBuilder();
|
||||
|
||||
boolean convertNext = true;
|
||||
for (char ch : text.toCharArray()) {
|
||||
if (Character.isSpaceChar(ch)) {
|
||||
convertNext = true;
|
||||
} else if (convertNext) {
|
||||
ch = Character.toTitleCase(ch);
|
||||
convertNext = false;
|
||||
} else {
|
||||
ch = Character.toLowerCase(ch);
|
||||
}
|
||||
converted.append(ch);
|
||||
}
|
||||
|
||||
return converted.toString();
|
||||
}
|
||||
|
||||
public static String convertToTitleCaseSplitting(String text) {
|
||||
if (text == null || text.isEmpty()) {
|
||||
return text;
|
||||
}
|
||||
|
||||
return Arrays
|
||||
.stream(text.split(WORD_SEPARATOR))
|
||||
.map(word -> word.isEmpty()
|
||||
? word
|
||||
: Character.toTitleCase(word.charAt(0)) + word
|
||||
.substring(1)
|
||||
.toLowerCase())
|
||||
.collect(Collectors.joining(WORD_SEPARATOR));
|
||||
}
|
||||
|
||||
public static String convertToTitleCaseIcu4j(String text) {
|
||||
if (text == null || text.isEmpty()) {
|
||||
return text;
|
||||
}
|
||||
|
||||
return UCharacter.toTitleCase(text, BreakIterator.getTitleInstance());
|
||||
}
|
||||
|
||||
public static String convertToTileCaseWordUtilsFull(String text) {
|
||||
return WordUtils.capitalizeFully(text);
|
||||
}
|
||||
|
||||
public static String convertToTileCaseWordUtils(String text) {
|
||||
return WordUtils.capitalize(text);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,92 @@
|
|||
package com.baeldung.date;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
|
||||
public class DateWithoutTimeUnitTest {
|
||||
|
||||
private static final long MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
@Test
|
||||
public void whenGettingDateWithoutTimeUsingCalendar_thenReturnDateWithoutTime() {
|
||||
Date dateWithoutTime = DateWithoutTime.getDateWithoutTimeUsingCalendar();
|
||||
|
||||
// first check the time is set to 0
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(dateWithoutTime);
|
||||
|
||||
assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY));
|
||||
assertEquals(0, calendar.get(Calendar.MINUTE));
|
||||
assertEquals(0, calendar.get(Calendar.SECOND));
|
||||
assertEquals(0, calendar.get(Calendar.MILLISECOND));
|
||||
|
||||
// we get the day of the date
|
||||
int day = calendar.get(Calendar.DAY_OF_MONTH);
|
||||
|
||||
// if we add the mills of one day minus 1 we should get the same day
|
||||
calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY - 1);
|
||||
assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH));
|
||||
|
||||
// if we add one full day in millis we should get a different day
|
||||
calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY);
|
||||
assertNotEquals(day, calendar.get(Calendar.DAY_OF_MONTH));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGettingDateWithoutTimeUsingFormat_thenReturnDateWithoutTime() throws ParseException {
|
||||
Date dateWithoutTime = DateWithoutTime.getDateWithoutTimeUsingFormat();
|
||||
|
||||
// first check the time is set to 0
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(dateWithoutTime);
|
||||
|
||||
assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY));
|
||||
assertEquals(0, calendar.get(Calendar.MINUTE));
|
||||
assertEquals(0, calendar.get(Calendar.SECOND));
|
||||
assertEquals(0, calendar.get(Calendar.MILLISECOND));
|
||||
|
||||
// we get the day of the date
|
||||
int day = calendar.get(Calendar.DAY_OF_MONTH);
|
||||
|
||||
// if we add the mills of one day minus 1 we should get the same day
|
||||
calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY - 1);
|
||||
assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH));
|
||||
|
||||
// if we add one full day in millis we should get a different day
|
||||
calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY);
|
||||
assertNotEquals(day, calendar.get(Calendar.DAY_OF_MONTH));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGettingLocalDate_thenReturnDateWithoutTime() {
|
||||
// get the local date
|
||||
LocalDate localDate = DateWithoutTime.getLocalDate();
|
||||
|
||||
// get the millis of our LocalDate
|
||||
long millisLocalDate = localDate
|
||||
.atStartOfDay()
|
||||
.toInstant(OffsetDateTime
|
||||
.now()
|
||||
.getOffset())
|
||||
.toEpochMilli();
|
||||
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
// if we add the millis of one day minus 1 we should get the same day
|
||||
calendar.setTimeInMillis(millisLocalDate + MILLISECONDS_PER_DAY - 1);
|
||||
assertEquals(localDate.getDayOfMonth(), calendar.get(Calendar.DAY_OF_MONTH));
|
||||
|
||||
// if we add one full day in millis we should get a different day
|
||||
calendar.setTimeInMillis(millisLocalDate + MILLISECONDS_PER_DAY);
|
||||
assertNotEquals(localDate.getDayOfMonth(), calendar.get(Calendar.DAY_OF_MONTH));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DateExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
DateExtractYearMonthDayIntegerValues extractYearMonthDateIntegerValues = new DateExtractYearMonthDayIntegerValues();
|
||||
|
||||
Date date;
|
||||
|
||||
@Before
|
||||
public void setup() throws ParseException
|
||||
{
|
||||
date=new SimpleDateFormat("dd-MM-yyyy").parse("01-03-2018");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=extractYearMonthDateIntegerValues.getYear(date);
|
||||
assertThat(actualYear,is(2018));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=extractYearMonthDateIntegerValues.getMonth(date);
|
||||
assertThat(actualMonth,is(02));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=extractYearMonthDateIntegerValues.getDay(date);
|
||||
assertThat(actualDayOfMonth,is(01));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class LocalDateExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
LocalDateExtractYearMonthDayIntegerValues localDateExtractYearMonthDayIntegerValues=new LocalDateExtractYearMonthDayIntegerValues();
|
||||
|
||||
LocalDate localDate=LocalDate.parse("2007-12-03");
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=localDateExtractYearMonthDayIntegerValues.getYear(localDate);
|
||||
assertThat(actualYear,is(2007));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=localDateExtractYearMonthDayIntegerValues.getMonth(localDate);
|
||||
assertThat(actualMonth,is(12));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=localDateExtractYearMonthDayIntegerValues.getDay(localDate);
|
||||
assertThat(actualDayOfMonth,is(03));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
LocalDateTimeExtractYearMonthDayIntegerValues localDateTimeExtractYearMonthDayIntegerValues = new LocalDateTimeExtractYearMonthDayIntegerValues();
|
||||
|
||||
LocalDateTime localDateTime=LocalDateTime.parse("2007-12-03T10:15:30");
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=localDateTimeExtractYearMonthDayIntegerValues.getYear(localDateTime);
|
||||
assertThat(actualYear,is(2007));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=localDateTimeExtractYearMonthDayIntegerValues.getMonth(localDateTime);
|
||||
assertThat(actualMonth,is(12));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=localDateTimeExtractYearMonthDayIntegerValues.getDay(localDateTime);
|
||||
assertThat(actualDayOfMonth,is(03));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
OffsetDateTimeExtractYearMonthDayIntegerValues offsetDateTimeExtractYearMonthDayIntegerValues = new OffsetDateTimeExtractYearMonthDayIntegerValues();
|
||||
|
||||
OffsetDateTime offsetDateTime=OffsetDateTime.parse("2007-12-03T10:15:30+01:00");
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=offsetDateTimeExtractYearMonthDayIntegerValues.getYear(offsetDateTime);
|
||||
assertThat(actualYear,is(2007));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getMonth(offsetDateTime);
|
||||
assertThat(actualMonth,is(12));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getDay(offsetDateTime);
|
||||
assertThat(actualDayOfMonth,is(03));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
ZonedDateTimeExtractYearMonthDayIntegerValues zonedDateTimeExtractYearMonthDayIntegerValues = new ZonedDateTimeExtractYearMonthDayIntegerValues();
|
||||
|
||||
ZonedDateTime zonedDateTime=ZonedDateTime.parse("2007-12-03T10:15:30+01:00");
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=zonedDateTimeExtractYearMonthDayIntegerValues.getYear(zonedDateTime);
|
||||
assertThat(actualYear,is(2007));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getMonth(zonedDateTime);
|
||||
assertThat(actualMonth,is(12));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getDay(zonedDateTime);
|
||||
assertThat(actualDayOfMonth,is(03));
|
||||
}
|
||||
}
|
|
@ -3,6 +3,8 @@ package com.baeldung.extension;
|
|||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class ExtensionUnitTest {
|
||||
private Extension extension = new Extension();
|
||||
|
||||
|
@ -16,8 +18,8 @@ public class ExtensionUnitTest {
|
|||
@Test
|
||||
public void getExtension_whenStringHandle_thenExtensionIsTrue() {
|
||||
String expectedExtension = "java";
|
||||
String actualExtension = extension.getExtensionByStringHandling("Demo.java");
|
||||
Assert.assertEquals(expectedExtension, actualExtension);
|
||||
Optional<String> actualExtension = extension.getExtensionByStringHandling("Demo.java");
|
||||
Assert.assertEquals(expectedExtension, actualExtension.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.immutableobjects;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ImmutableObjectsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCallingStringReplace_thenStringDoesNotMutate() {
|
||||
// 2. What's an Immutable Object?
|
||||
final String name = "baeldung";
|
||||
final String newName = name.replace("dung", "----");
|
||||
|
||||
assertEquals("baeldung", name);
|
||||
assertEquals("bael----", newName);
|
||||
}
|
||||
|
||||
public void whenReassignFinalValue_thenCompilerError() {
|
||||
// 3. The final Keyword in Java (1)
|
||||
final String name = "baeldung";
|
||||
// name = "bael...";
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddingElementToList_thenSizeChange() {
|
||||
// 3. The final Keyword in Java (2)
|
||||
final List<String> strings = new ArrayList<>();
|
||||
assertEquals(0, strings.size());
|
||||
strings.add("baeldung");
|
||||
assertEquals(1, strings.size());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.manifest;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ExecuteJarFileUnitTest {
|
||||
|
||||
private static final String ERROR_MESSAGE = "no main manifest attribute, in example.jar\n";
|
||||
private static final String SUCCESS_MESSAGE = "AppExample executed!\n";
|
||||
|
||||
@Test
|
||||
public final void givenDefaultManifest_whenManifestAttributeIsNotPresent_thenGetErrorMessage() {
|
||||
String output = ExecuteJarFile.executeJarWithoutManifestAttribute();
|
||||
assertEquals(ERROR_MESSAGE, output);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenCustomManifest_whenManifestAttributeIsPresent_thenGetSuccessMessage() {
|
||||
String output = ExecuteJarFile.executeJarWithManifestAttribute();
|
||||
assertEquals(SUCCESS_MESSAGE, output);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,21 +1,29 @@
|
|||
package com.baeldung.socket;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class EchoIntegrationTest {
|
||||
private static final Integer PORT = 4444;
|
||||
private static int port;
|
||||
|
||||
@BeforeClass
|
||||
public static void start() throws InterruptedException {
|
||||
public static void start() throws InterruptedException, IOException {
|
||||
|
||||
// Take an available port
|
||||
ServerSocket s = new ServerSocket(0);
|
||||
port = s.getLocalPort();
|
||||
s.close();
|
||||
|
||||
Executors.newSingleThreadExecutor()
|
||||
.submit(() -> new EchoServer().start(PORT));
|
||||
.submit(() -> new EchoServer().start(port));
|
||||
Thread.sleep(500);
|
||||
}
|
||||
|
||||
|
@ -23,7 +31,7 @@ public class EchoIntegrationTest {
|
|||
|
||||
@Before
|
||||
public void init() {
|
||||
client.startConnection("127.0.0.1", PORT);
|
||||
client.startConnection("127.0.0.1", port);
|
||||
}
|
||||
|
||||
@After
|
||||
|
|
|
@ -1,31 +1,39 @@
|
|||
package com.baeldung.socket;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class GreetServerIntegrationTest {
|
||||
|
||||
private GreetClient client;
|
||||
|
||||
private static final Integer PORT = 6666;
|
||||
private static int port;
|
||||
|
||||
@BeforeClass
|
||||
public static void start() throws InterruptedException {
|
||||
public static void start() throws InterruptedException, IOException {
|
||||
|
||||
// Take an available port
|
||||
ServerSocket s = new ServerSocket(0);
|
||||
port = s.getLocalPort();
|
||||
s.close();
|
||||
|
||||
Executors.newSingleThreadExecutor()
|
||||
.submit(() -> new GreetServer().start(PORT));
|
||||
.submit(() -> new GreetServer().start(port));
|
||||
Thread.sleep(500);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
client = new GreetClient();
|
||||
client.startConnection("127.0.0.1", PORT);
|
||||
client.startConnection("127.0.0.1", port);
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -1,26 +1,35 @@
|
|||
package com.baeldung.socket;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class SocketEchoMultiIntegrationTest {
|
||||
|
||||
private static final Integer PORT = 5555;
|
||||
private static int port;
|
||||
|
||||
@BeforeClass
|
||||
public static void start() throws InterruptedException {
|
||||
Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(PORT));
|
||||
public static void start() throws InterruptedException, IOException {
|
||||
|
||||
// Take an available port
|
||||
ServerSocket s = new ServerSocket(0);
|
||||
port = s.getLocalPort();
|
||||
s.close();
|
||||
|
||||
Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(port));
|
||||
Thread.sleep(500);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClient1_whenServerResponds_thenCorrect() {
|
||||
EchoClient client = new EchoClient();
|
||||
client.startConnection("127.0.0.1", PORT);
|
||||
client.startConnection("127.0.0.1", port);
|
||||
String msg1 = client.sendMessage("hello");
|
||||
String msg2 = client.sendMessage("world");
|
||||
String terminate = client.sendMessage(".");
|
||||
|
@ -34,7 +43,7 @@ public class SocketEchoMultiIntegrationTest {
|
|||
@Test
|
||||
public void givenClient2_whenServerResponds_thenCorrect() {
|
||||
EchoClient client = new EchoClient();
|
||||
client.startConnection("127.0.0.1", PORT);
|
||||
client.startConnection("127.0.0.1", port);
|
||||
String msg1 = client.sendMessage("hello");
|
||||
String msg2 = client.sendMessage("world");
|
||||
String terminate = client.sendMessage(".");
|
||||
|
@ -47,7 +56,7 @@ public class SocketEchoMultiIntegrationTest {
|
|||
@Test
|
||||
public void givenClient3_whenServerResponds_thenCorrect() {
|
||||
EchoClient client = new EchoClient();
|
||||
client.startConnection("127.0.0.1", PORT);
|
||||
client.startConnection("127.0.0.1", port);
|
||||
String msg1 = client.sendMessage("hello");
|
||||
String msg2 = client.sendMessage("world");
|
||||
String terminate = client.sendMessage(".");
|
||||
|
|
|
@ -0,0 +1,70 @@
|
|||
package com.baeldung.string;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class TitleCaseConverterUnitTest {
|
||||
|
||||
private static final String TEXT = "tHis IS a tiTLe";
|
||||
private static final String TEXT_EXPECTED = "This Is A Title";
|
||||
private static final String TEXT_EXPECTED_NOT_FULL = "THis IS A TiTLe";
|
||||
|
||||
private static final String TEXT_OTHER_DELIMITERS = "tHis, IS a tiTLe";
|
||||
private static final String TEXT_EXPECTED_OTHER_DELIMITERS = "This, Is A Title";
|
||||
private static final String TEXT_EXPECTED_OTHER_DELIMITERS_NOT_FULL = "THis, IS A TiTLe";
|
||||
|
||||
@Test
|
||||
public void whenConvertingToTitleCaseIterating_thenStringConverted() {
|
||||
assertEquals(TEXT_EXPECTED, TitleCaseConverter.convertToTitleCaseIteratingChars(TEXT));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertingToTitleCaseSplitting_thenStringConverted() {
|
||||
assertEquals(TEXT_EXPECTED, TitleCaseConverter.convertToTitleCaseSplitting(TEXT));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertingToTitleCaseUsingWordUtilsFull_thenStringConverted() {
|
||||
assertEquals(TEXT_EXPECTED, TitleCaseConverter.convertToTileCaseWordUtilsFull(TEXT));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertingToTitleCaseUsingWordUtils_thenStringConvertedOnlyFirstCharacter() {
|
||||
assertEquals(TEXT_EXPECTED_NOT_FULL, TitleCaseConverter.convertToTileCaseWordUtils(TEXT));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertingToTitleCaseUsingIcu4j_thenStringConverted() {
|
||||
assertEquals(TEXT_EXPECTED, TitleCaseConverter.convertToTitleCaseIcu4j(TEXT));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertingToTitleCaseWithDifferentDelimiters_thenDelimitersKept() {
|
||||
assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS, TitleCaseConverter.convertToTitleCaseIteratingChars(TEXT_OTHER_DELIMITERS));
|
||||
assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS, TitleCaseConverter.convertToTitleCaseSplitting(TEXT_OTHER_DELIMITERS));
|
||||
assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS, TitleCaseConverter.convertToTileCaseWordUtilsFull(TEXT_OTHER_DELIMITERS));
|
||||
assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS_NOT_FULL, TitleCaseConverter.convertToTileCaseWordUtils(TEXT_OTHER_DELIMITERS));
|
||||
assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS, TitleCaseConverter.convertToTitleCaseIcu4j(TEXT_OTHER_DELIMITERS));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNull_whenConvertingToTileCase_thenReturnNull() {
|
||||
assertEquals(null, TitleCaseConverter.convertToTitleCaseIteratingChars(null));
|
||||
assertEquals(null, TitleCaseConverter.convertToTitleCaseSplitting(null));
|
||||
assertEquals(null, TitleCaseConverter.convertToTileCaseWordUtilsFull(null));
|
||||
assertEquals(null, TitleCaseConverter.convertToTileCaseWordUtils(null));
|
||||
assertEquals(null, TitleCaseConverter.convertToTitleCaseIcu4j(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyString_whenConvertingToTileCase_thenReturnEmptyString() {
|
||||
assertEquals("", TitleCaseConverter.convertToTitleCaseIteratingChars(""));
|
||||
assertEquals("", TitleCaseConverter.convertToTitleCaseSplitting(""));
|
||||
assertEquals("", TitleCaseConverter.convertToTileCaseWordUtilsFull(""));
|
||||
assertEquals("", TitleCaseConverter.convertToTileCaseWordUtils(""));
|
||||
assertEquals("", TitleCaseConverter.convertToTitleCaseIcu4j(""));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,115 @@
|
|||
package com.baeldung.stringtemplates
|
||||
|
||||
/**
|
||||
* Example of a useful function defined in Kotlin String class
|
||||
*/
|
||||
fun padExample(): String {
|
||||
return "Hello".padEnd(10, '!')
|
||||
}
|
||||
|
||||
/**
|
||||
* Example of a simple string template usage
|
||||
*/
|
||||
fun simpleTemplate(n: Int): String {
|
||||
val message = "n = $n"
|
||||
return message
|
||||
}
|
||||
|
||||
/**
|
||||
* Example of a string template with a simple expression
|
||||
*/
|
||||
fun templateWithExpression(n: Int): String {
|
||||
val message = "n + 1 = ${n + 1}"
|
||||
return message
|
||||
}
|
||||
|
||||
/**
|
||||
* Example of a string template with expression containing some logic
|
||||
*/
|
||||
fun templateWithLogic(n: Int): String {
|
||||
val message = "$n is ${if (n > 0) "positive" else "not positive"}"
|
||||
return message
|
||||
}
|
||||
|
||||
/**
|
||||
* Example of nested string templates
|
||||
*/
|
||||
fun nestedTemplates(n: Int): String {
|
||||
val message = "$n is ${if (n > 0) "positive" else if (n < 0) "negative and ${if (n % 2 == 0) "even" else "odd"}" else "zero"}"
|
||||
return message
|
||||
}
|
||||
|
||||
/**
|
||||
* Example of joining array's element into a string with a default separator
|
||||
*/
|
||||
fun templateJoinArray(): String {
|
||||
val numbers = listOf(1, 1, 2, 3, 5, 8)
|
||||
val message = "first Fibonacci numbers: ${numbers.joinToString()}"
|
||||
return message
|
||||
}
|
||||
|
||||
/**
|
||||
* Example of escaping the dollar sign
|
||||
*/
|
||||
fun notAStringTemplate(): String {
|
||||
val message = "n = \$n"
|
||||
return message
|
||||
}
|
||||
|
||||
/**
|
||||
* Example of a simple triple quoted string
|
||||
*/
|
||||
fun showFilePath(): String {
|
||||
val path = """C:\Repository\read.me"""
|
||||
return path
|
||||
}
|
||||
|
||||
/**
|
||||
* Example of a multiline string
|
||||
*/
|
||||
fun showMultiline(): String {
|
||||
val receipt = """Item 1: $1.00
|
||||
Item 2: $0.50"""
|
||||
return receipt
|
||||
}
|
||||
|
||||
/**
|
||||
* Example of a multiline string with indentation
|
||||
*/
|
||||
fun showMultilineIndent(): String {
|
||||
val receipt = """Item 1: $1.00
|
||||
>Item 2: $0.50""".trimMargin(">")
|
||||
return receipt
|
||||
}
|
||||
|
||||
/**
|
||||
* Example of a triple quoted string with a not-working escape sequence
|
||||
*/
|
||||
fun showTripleQuotedWrongEscape(): String {
|
||||
val receipt = """Item 1: $1.00\nItem 2: $0.50"""
|
||||
return receipt
|
||||
}
|
||||
|
||||
/**
|
||||
* Example of a triple quoted string with a correctly working escape sequence
|
||||
*/
|
||||
|
||||
fun showTripleQuotedCorrectEscape(): String {
|
||||
val receipt = """Item 1: $1.00${"\n"}Item 2: $0.50"""
|
||||
return receipt
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
println(padExample())
|
||||
println(simpleTemplate(10))
|
||||
println(templateWithExpression(5))
|
||||
println(templateWithLogic(7))
|
||||
println(nestedTemplates(-5))
|
||||
println(templateJoinArray())
|
||||
println(notAStringTemplate())
|
||||
println(showFilePath())
|
||||
println(showMultiline())
|
||||
println(showMultilineIndent())
|
||||
println(showTripleQuotedWrongEscape())
|
||||
println(showTripleQuotedCorrectEscape())
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.kotlin.reflection
|
||||
|
||||
import org.junit.Ignore
|
||||
import org.junit.Test
|
||||
import org.slf4j.LoggerFactory
|
||||
|
||||
@Ignore
|
||||
class JavaReflectionTest {
|
||||
private val LOG = LoggerFactory.getLogger(KClassTest::class.java)
|
||||
|
||||
@Test
|
||||
fun listJavaClassMethods() {
|
||||
Exception::class.java.methods
|
||||
.forEach { method -> LOG.info("Method: {}", method) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun listKotlinClassMethods() {
|
||||
JavaReflectionTest::class.java.methods
|
||||
.forEach { method -> LOG.info("Method: {}", method) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun listKotlinDataClassMethods() {
|
||||
data class ExampleDataClass(val name: String, var enabled: Boolean)
|
||||
|
||||
ExampleDataClass::class.java.methods
|
||||
.forEach { method -> LOG.info("Method: {}", method) }
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,69 @@
|
|||
package com.baeldung.kotlin.reflection
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Ignore
|
||||
import org.junit.Test
|
||||
import org.slf4j.LoggerFactory
|
||||
import java.math.BigDecimal
|
||||
import kotlin.reflect.full.*
|
||||
|
||||
class KClassTest {
|
||||
private val LOG = LoggerFactory.getLogger(KClassTest::class.java)
|
||||
|
||||
@Test
|
||||
fun testKClassDetails() {
|
||||
val stringClass = String::class
|
||||
Assert.assertEquals("kotlin.String", stringClass.qualifiedName)
|
||||
Assert.assertFalse(stringClass.isData)
|
||||
Assert.assertFalse(stringClass.isCompanion)
|
||||
Assert.assertFalse(stringClass.isAbstract)
|
||||
Assert.assertTrue(stringClass.isFinal)
|
||||
Assert.assertFalse(stringClass.isSealed)
|
||||
|
||||
val listClass = List::class
|
||||
Assert.assertEquals("kotlin.collections.List", listClass.qualifiedName)
|
||||
Assert.assertFalse(listClass.isData)
|
||||
Assert.assertFalse(listClass.isCompanion)
|
||||
Assert.assertTrue(listClass.isAbstract)
|
||||
Assert.assertFalse(listClass.isFinal)
|
||||
Assert.assertFalse(listClass.isSealed)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetRelated() {
|
||||
LOG.info("Companion Object: {}", TestSubject::class.companionObject)
|
||||
LOG.info("Companion Object Instance: {}", TestSubject::class.companionObjectInstance)
|
||||
LOG.info("Object Instance: {}", TestObject::class.objectInstance)
|
||||
|
||||
Assert.assertSame(TestObject, TestObject::class.objectInstance)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testNewInstance() {
|
||||
val listClass = ArrayList::class
|
||||
|
||||
val list = listClass.createInstance()
|
||||
Assert.assertTrue(list is ArrayList)
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
fun testMembers() {
|
||||
val bigDecimalClass = BigDecimal::class
|
||||
|
||||
LOG.info("Constructors: {}", bigDecimalClass.constructors)
|
||||
LOG.info("Functions: {}", bigDecimalClass.functions)
|
||||
LOG.info("Properties: {}", bigDecimalClass.memberProperties)
|
||||
LOG.info("Extension Functions: {}", bigDecimalClass.memberExtensionFunctions)
|
||||
}
|
||||
}
|
||||
|
||||
class TestSubject {
|
||||
companion object {
|
||||
val name = "TestSubject"
|
||||
}
|
||||
}
|
||||
|
||||
object TestObject {
|
||||
val answer = 42
|
||||
}
|
|
@ -0,0 +1,88 @@
|
|||
package com.baeldung.kotlin.reflection
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.nio.charset.Charset
|
||||
import kotlin.reflect.KMutableProperty
|
||||
import kotlin.reflect.full.starProjectedType
|
||||
|
||||
class KMethodTest {
|
||||
|
||||
@Test
|
||||
fun testCallMethod() {
|
||||
val str = "Hello"
|
||||
val lengthMethod = str::length
|
||||
|
||||
Assert.assertEquals(5, lengthMethod())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testReturnType() {
|
||||
val str = "Hello"
|
||||
val method = str::byteInputStream
|
||||
|
||||
Assert.assertEquals(ByteArrayInputStream::class.starProjectedType, method.returnType)
|
||||
Assert.assertFalse(method.returnType.isMarkedNullable)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testParams() {
|
||||
val str = "Hello"
|
||||
val method = str::byteInputStream
|
||||
|
||||
method.isSuspend
|
||||
Assert.assertEquals(1, method.parameters.size)
|
||||
Assert.assertTrue(method.parameters[0].isOptional)
|
||||
Assert.assertFalse(method.parameters[0].isVararg)
|
||||
Assert.assertEquals(Charset::class.starProjectedType, method.parameters[0].type)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMethodDetails() {
|
||||
val codePoints = String::codePoints
|
||||
Assert.assertEquals("codePoints", codePoints.name)
|
||||
Assert.assertFalse(codePoints.isSuspend)
|
||||
Assert.assertFalse(codePoints.isExternal)
|
||||
Assert.assertFalse(codePoints.isInline)
|
||||
Assert.assertFalse(codePoints.isOperator)
|
||||
|
||||
val byteInputStream = String::byteInputStream
|
||||
Assert.assertEquals("byteInputStream", byteInputStream.name)
|
||||
Assert.assertFalse(byteInputStream.isSuspend)
|
||||
Assert.assertFalse(byteInputStream.isExternal)
|
||||
Assert.assertTrue(byteInputStream.isInline)
|
||||
Assert.assertFalse(byteInputStream.isOperator)
|
||||
}
|
||||
|
||||
val readOnlyProperty: Int = 42
|
||||
lateinit var mutableProperty: String
|
||||
|
||||
@Test
|
||||
fun testPropertyDetails() {
|
||||
val roProperty = this::readOnlyProperty
|
||||
Assert.assertEquals("readOnlyProperty", roProperty.name)
|
||||
Assert.assertFalse(roProperty.isLateinit)
|
||||
Assert.assertFalse(roProperty.isConst)
|
||||
Assert.assertFalse(roProperty is KMutableProperty<*>)
|
||||
|
||||
val mProperty = this::mutableProperty
|
||||
Assert.assertEquals("mutableProperty", mProperty.name)
|
||||
Assert.assertTrue(mProperty.isLateinit)
|
||||
Assert.assertFalse(mProperty.isConst)
|
||||
Assert.assertTrue(mProperty is KMutableProperty<*>)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testProperty() {
|
||||
val prop = this::mutableProperty
|
||||
|
||||
Assert.assertEquals(String::class.starProjectedType, prop.getter.returnType)
|
||||
|
||||
prop.set("Hello")
|
||||
Assert.assertEquals("Hello", prop.get())
|
||||
|
||||
prop.setter("World")
|
||||
Assert.assertEquals("World", prop.getter())
|
||||
}
|
||||
}
|
Binary file not shown.
|
@ -11,6 +11,7 @@ public class UnitTestNamingConventionRule extends AbstractJavaRule {
|
|||
|
||||
private static List<String> allowedEndings = Arrays.asList(
|
||||
"IntegrationTest",
|
||||
"IntTest",
|
||||
"ManualTest",
|
||||
"JdbcTest",
|
||||
"LiveTest",
|
||||
|
|
|
@ -37,7 +37,7 @@ import java.util.logging.Logger;
|
|||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
@RunWith(Arquillian.class)
|
||||
public class MemberRegistrationIntegrationTest {
|
||||
public class MemberRegistrationLiveTest {
|
||||
@Deployment
|
||||
public static Archive<?> createTestArchive() {
|
||||
File[] files = Maven
|
|
@ -1,40 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
|
||||
xmlns:mvc="http://www.springframework.org/schema/mvc"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
|
||||
http://www.springframework.org/schema/mvc
|
||||
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"
|
||||
>
|
||||
<http use-expressions="true">
|
||||
<intercept-url pattern="/login*" access="permitAll"/>
|
||||
<intercept-url pattern="/logout*" access="permitAll"/>
|
||||
<intercept-url pattern="/home*" access="permitAll"/>
|
||||
<intercept-url pattern="/files/**" access="permitAll"/>
|
||||
<intercept-url pattern="/resources/**" access="permitAll"/>
|
||||
<intercept-url pattern="/js/**" access="permitAll"/>
|
||||
<intercept-url pattern="/other-files/**" access="permitAll"/>
|
||||
<intercept-url pattern="/invalidSession*" access="isAnonymous()"/>
|
||||
<intercept-url pattern="/**" access="isAuthenticated()"/>
|
||||
|
||||
<form-login login-page='/login.html' authentication-failure-url="/login.html?error=true" authentication-success-handler-ref="myAuthenticationSuccessHandler"
|
||||
default-target-url="home.html"/>
|
||||
<session-management invalid-session-url="/invalidSession.html" session-fixation-protection="none"/>
|
||||
<logout invalidate-session="false" logout-success-url="/logout.html?logSucc=true" delete-cookies="JSESSIONID"/>
|
||||
|
||||
</http>
|
||||
|
||||
<!-- for XML static resource confguration- comment out for java based config -->
|
||||
<!-- -<mvc:resources mapping="/resources/**" location="/resources/" /> -->
|
||||
|
||||
<beans:bean id="myAuthenticationSuccessHandler" class="org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler"/>
|
||||
<authentication-manager>
|
||||
<authentication-provider>
|
||||
<user-service>
|
||||
<user name="user1" password="user1Pass" authorities="ROLE_USER"/>
|
||||
<user name="admin1" password="admin1Pass" authorities="ROLE_ADMIN"/>
|
||||
</user-service>
|
||||
</authentication-provider>
|
||||
</authentication-manager>
|
||||
</beans:beans>
|
|
@ -1,7 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
|
||||
xmlns:mvc="http://www.springframework.org/schema/mvc"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
|
||||
|
||||
</beans>
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.servlets;
|
||||
|
||||
import javax.servlet.annotation.*;
|
||||
import javax.servlet.http.*;
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
|
||||
import static javax.servlet.RequestDispatcher.*;
|
||||
|
||||
@WebServlet(urlPatterns = "/errorHandler")
|
||||
public class ErrorHandlerServlet extends HttpServlet {
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
|
||||
throws IOException {
|
||||
resp.setContentType("text/html; charset=utf-8");
|
||||
try (PrintWriter writer = resp.getWriter()) {
|
||||
writer.write("<html><head><title>Error description</title></head><body>");
|
||||
writer.write("<h2>Error description</h2>");
|
||||
writer.write("<ul>");
|
||||
Arrays.asList(ERROR_STATUS_CODE, ERROR_EXCEPTION_TYPE, ERROR_MESSAGE)
|
||||
.forEach(e ->
|
||||
writer.write("<li>" + e + ":" + req.getAttribute(e) + " </li>")
|
||||
);
|
||||
writer.write("</ul>");
|
||||
writer.write("</html></body>");
|
||||
}
|
||||
|
||||
Exception exception = (Exception) req.getAttribute(ERROR_EXCEPTION);
|
||||
if (IllegalArgumentException.class.isInstance(exception)) {
|
||||
getServletContext().log("Error on an application argument", exception);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.servlets;
|
||||
|
||||
import javax.servlet.annotation.*;
|
||||
import javax.servlet.http.*;
|
||||
|
||||
@WebServlet(urlPatterns = "/randomError")
|
||||
public class RandomErrorServlet extends HttpServlet {
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest req, final HttpServletResponse resp) {
|
||||
throw new IllegalStateException("Random error");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://java.sun.com/xml/ns/javaee"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
|
||||
http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
|
||||
version="3.1">
|
||||
|
||||
<error-page>
|
||||
<error-code>404</error-code>
|
||||
<location>/error-404.html</location> <!-- /src/main/webapp/error-404.html-->
|
||||
</error-page>
|
||||
|
||||
<error-page>
|
||||
<exception-type>java.lang.Exception</exception-type>
|
||||
<location>/errorHandler</location>
|
||||
</error-page>
|
||||
</web-app>
|
|
@ -0,0 +1,14 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Error page</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<h2>Error: Page not found</h2>
|
||||
|
||||
<a href="./">Go back home</a>
|
||||
|
||||
</body>
|
||||
</html>
|
|
@ -1,48 +1,48 @@
|
|||
|
||||
package com.baeldung.jaxb.gen;
|
||||
|
||||
import javax.xml.bind.annotation.XmlRegistry;
|
||||
|
||||
|
||||
/**
|
||||
* This object contains factory methods for each
|
||||
* Java content interface and Java element interface
|
||||
* generated in the com.baeldung.jaxb.gen package.
|
||||
* <p>An ObjectFactory allows you to programatically
|
||||
* construct new instances of the Java representation
|
||||
* for XML content. The Java representation of XML
|
||||
* content can consist of schema derived interfaces
|
||||
* and classes representing the binding of schema
|
||||
* type definitions, element declarations and model
|
||||
* groups. Factory methods for each of these are
|
||||
* provided in this class.
|
||||
*
|
||||
*/
|
||||
@XmlRegistry
|
||||
public class ObjectFactory {
|
||||
|
||||
|
||||
/**
|
||||
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.baeldung.jaxb.gen
|
||||
*
|
||||
*/
|
||||
public ObjectFactory() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link UserRequest }
|
||||
*
|
||||
*/
|
||||
public UserRequest createUserRequest() {
|
||||
return new UserRequest();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link UserResponse }
|
||||
*
|
||||
*/
|
||||
public UserResponse createUserResponse() {
|
||||
return new UserResponse();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
package com.baeldung.jaxb.gen;
|
||||
|
||||
import javax.xml.bind.annotation.XmlRegistry;
|
||||
|
||||
|
||||
/**
|
||||
* This object contains factory methods for each
|
||||
* Java content interface and Java element interface
|
||||
* generated in the com.baeldung.jaxb.gen package.
|
||||
* <p>An ObjectFactory allows you to programatically
|
||||
* construct new instances of the Java representation
|
||||
* for XML content. The Java representation of XML
|
||||
* content can consist of schema derived interfaces
|
||||
* and classes representing the binding of schema
|
||||
* type definitions, element declarations and model
|
||||
* groups. Factory methods for each of these are
|
||||
* provided in this class.
|
||||
*
|
||||
*/
|
||||
@XmlRegistry
|
||||
public class ObjectFactory {
|
||||
|
||||
|
||||
/**
|
||||
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.baeldung.jaxb.gen
|
||||
*
|
||||
*/
|
||||
public ObjectFactory() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link UserRequest }
|
||||
*
|
||||
*/
|
||||
public UserRequest createUserRequest() {
|
||||
return new UserRequest();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link UserResponse }
|
||||
*
|
||||
*/
|
||||
public UserResponse createUserResponse() {
|
||||
return new UserResponse();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,87 +1,87 @@
|
|||
|
||||
package com.baeldung.jaxb.gen;
|
||||
|
||||
import java.io.Serializable;
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
|
||||
|
||||
/**
|
||||
* <p>Java class for UserRequest complex type.
|
||||
*
|
||||
* <p>The following schema fragment specifies the expected content contained within this class.
|
||||
*
|
||||
* <pre>
|
||||
* <complexType name="UserRequest">
|
||||
* <complexContent>
|
||||
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
|
||||
* <sequence>
|
||||
* <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
|
||||
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* </sequence>
|
||||
* </restriction>
|
||||
* </complexContent>
|
||||
* </complexType>
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
*/
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
@XmlType(name = "UserRequest", propOrder = {
|
||||
"id",
|
||||
"name"
|
||||
})
|
||||
@XmlRootElement(name = "userRequest")
|
||||
public class UserRequest
|
||||
implements Serializable
|
||||
{
|
||||
|
||||
private final static long serialVersionUID = -1L;
|
||||
protected int id;
|
||||
@XmlElement(required = true)
|
||||
protected String name;
|
||||
|
||||
/**
|
||||
* Gets the value of the id property.
|
||||
*
|
||||
*/
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the id property.
|
||||
*
|
||||
*/
|
||||
public void setId(int value) {
|
||||
this.id = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the name property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the name property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setName(String value) {
|
||||
this.name = value;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
package com.baeldung.jaxb.gen;
|
||||
|
||||
import java.io.Serializable;
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
|
||||
|
||||
/**
|
||||
* <p>Java class for UserRequest complex type.
|
||||
*
|
||||
* <p>The following schema fragment specifies the expected content contained within this class.
|
||||
*
|
||||
* <pre>
|
||||
* <complexType name="UserRequest">
|
||||
* <complexContent>
|
||||
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
|
||||
* <sequence>
|
||||
* <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
|
||||
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* </sequence>
|
||||
* </restriction>
|
||||
* </complexContent>
|
||||
* </complexType>
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
*/
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
@XmlType(name = "UserRequest", propOrder = {
|
||||
"id",
|
||||
"name"
|
||||
})
|
||||
@XmlRootElement(name = "userRequest")
|
||||
public class UserRequest
|
||||
implements Serializable
|
||||
{
|
||||
|
||||
private final static long serialVersionUID = -1L;
|
||||
protected int id;
|
||||
@XmlElement(required = true)
|
||||
protected String name;
|
||||
|
||||
/**
|
||||
* Gets the value of the id property.
|
||||
*
|
||||
*/
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the id property.
|
||||
*
|
||||
*/
|
||||
public void setId(int value) {
|
||||
this.id = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the name property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the name property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setName(String value) {
|
||||
this.name = value;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,149 +1,149 @@
|
|||
|
||||
package com.baeldung.jaxb.gen;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Calendar;
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import javax.xml.bind.annotation.XmlSchemaType;
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
|
||||
import org.w3._2001.xmlschema.Adapter1;
|
||||
|
||||
|
||||
/**
|
||||
* <p>Java class for UserResponse complex type.
|
||||
*
|
||||
* <p>The following schema fragment specifies the expected content contained within this class.
|
||||
*
|
||||
* <pre>
|
||||
* <complexType name="UserResponse">
|
||||
* <complexContent>
|
||||
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
|
||||
* <sequence>
|
||||
* <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
|
||||
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="gender" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="created" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
|
||||
* </sequence>
|
||||
* </restriction>
|
||||
* </complexContent>
|
||||
* </complexType>
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
*/
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
@XmlType(name = "UserResponse", propOrder = {
|
||||
"id",
|
||||
"name",
|
||||
"gender",
|
||||
"created"
|
||||
})
|
||||
@XmlRootElement(name = "userResponse")
|
||||
public class UserResponse
|
||||
implements Serializable
|
||||
{
|
||||
|
||||
private final static long serialVersionUID = -1L;
|
||||
protected int id;
|
||||
@XmlElement(required = true)
|
||||
protected String name;
|
||||
@XmlElement(required = true)
|
||||
protected String gender;
|
||||
@XmlElement(required = true, type = String.class)
|
||||
@XmlJavaTypeAdapter(Adapter1 .class)
|
||||
@XmlSchemaType(name = "dateTime")
|
||||
protected Calendar created;
|
||||
|
||||
/**
|
||||
* Gets the value of the id property.
|
||||
*
|
||||
*/
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the id property.
|
||||
*
|
||||
*/
|
||||
public void setId(int value) {
|
||||
this.id = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the name property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the name property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setName(String value) {
|
||||
this.name = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the gender property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getGender() {
|
||||
return gender;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the gender property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setGender(String value) {
|
||||
this.gender = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the created property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public Calendar getCreated() {
|
||||
return created;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the created property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setCreated(Calendar value) {
|
||||
this.created = value;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
package com.baeldung.jaxb.gen;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Calendar;
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import javax.xml.bind.annotation.XmlSchemaType;
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
|
||||
import org.w3._2001.xmlschema.Adapter1;
|
||||
|
||||
|
||||
/**
|
||||
* <p>Java class for UserResponse complex type.
|
||||
*
|
||||
* <p>The following schema fragment specifies the expected content contained within this class.
|
||||
*
|
||||
* <pre>
|
||||
* <complexType name="UserResponse">
|
||||
* <complexContent>
|
||||
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
|
||||
* <sequence>
|
||||
* <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
|
||||
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="gender" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="created" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
|
||||
* </sequence>
|
||||
* </restriction>
|
||||
* </complexContent>
|
||||
* </complexType>
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
*/
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
@XmlType(name = "UserResponse", propOrder = {
|
||||
"id",
|
||||
"name",
|
||||
"gender",
|
||||
"created"
|
||||
})
|
||||
@XmlRootElement(name = "userResponse")
|
||||
public class UserResponse
|
||||
implements Serializable
|
||||
{
|
||||
|
||||
private final static long serialVersionUID = -1L;
|
||||
protected int id;
|
||||
@XmlElement(required = true)
|
||||
protected String name;
|
||||
@XmlElement(required = true)
|
||||
protected String gender;
|
||||
@XmlElement(required = true, type = String.class)
|
||||
@XmlJavaTypeAdapter(Adapter1 .class)
|
||||
@XmlSchemaType(name = "dateTime")
|
||||
protected Calendar created;
|
||||
|
||||
/**
|
||||
* Gets the value of the id property.
|
||||
*
|
||||
*/
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the id property.
|
||||
*
|
||||
*/
|
||||
public void setId(int value) {
|
||||
this.id = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the name property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the name property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setName(String value) {
|
||||
this.name = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the gender property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getGender() {
|
||||
return gender;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the gender property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setGender(String value) {
|
||||
this.gender = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the created property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public Calendar getCreated() {
|
||||
return created;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the created property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setCreated(Calendar value) {
|
||||
this.created = value;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,2 +1,2 @@
|
|||
@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/jaxb/gen", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
|
||||
package com.baeldung.jaxb.gen;
|
||||
@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/jaxb/gen", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
|
||||
package com.baeldung.jaxb.gen;
|
||||
|
|
|
@ -1,23 +1,23 @@
|
|||
|
||||
package org.w3._2001.xmlschema;
|
||||
|
||||
import java.util.Calendar;
|
||||
import javax.xml.bind.annotation.adapters.XmlAdapter;
|
||||
|
||||
public class Adapter1
|
||||
extends XmlAdapter<String, Calendar>
|
||||
{
|
||||
|
||||
|
||||
public Calendar unmarshal(String value) {
|
||||
return (javax.xml.bind.DatatypeConverter.parseDateTime(value));
|
||||
}
|
||||
|
||||
public String marshal(Calendar value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
return (javax.xml.bind.DatatypeConverter.printDateTime(value));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
package org.w3._2001.xmlschema;
|
||||
|
||||
import java.util.Calendar;
|
||||
import javax.xml.bind.annotation.adapters.XmlAdapter;
|
||||
|
||||
public class Adapter1
|
||||
extends XmlAdapter<String, Calendar>
|
||||
{
|
||||
|
||||
|
||||
public Calendar unmarshal(String value) {
|
||||
return (javax.xml.bind.DatatypeConverter.parseDateTime(value));
|
||||
}
|
||||
|
||||
public String marshal(Calendar value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
return (javax.xml.bind.DatatypeConverter.printDateTime(value));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,23 @@
|
|||
{
|
||||
"items":{
|
||||
"book":[
|
||||
{
|
||||
"author":"Arthur Conan Doyle",
|
||||
"title":"Sherlock Holmes",
|
||||
"price":8.99
|
||||
},
|
||||
{
|
||||
"author":"J. R. R. Tolkien",
|
||||
"title":"The Lord of the Rings",
|
||||
"isbn":"0-395-19395-8",
|
||||
"price":22.99
|
||||
}
|
||||
],
|
||||
"bicycle":{
|
||||
"color":"red",
|
||||
"price":19.95
|
||||
}
|
||||
},
|
||||
"url":"mystore.com",
|
||||
"owner":"baeldung"
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.jsonpath.introduction;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
|
||||
import net.minidev.json.JSONArray;
|
||||
|
||||
public class JsonPathUnitTest {
|
||||
|
||||
private static String json;
|
||||
private static File jsonFile = new File("src/main/resources/online_store.json");
|
||||
|
||||
private static String readFile(File file, Charset charset) throws IOException {
|
||||
return new String(Files.readAllBytes(file.toPath()), charset);
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void init() throws IOException {
|
||||
json = readFile(jsonFile, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldMatchCountOfObjects() {
|
||||
Map<String, String> objectMap = JsonPath.read(json, "$");
|
||||
assertEquals(3, objectMap.keySet()
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldMatchCountOfArrays() {
|
||||
JSONArray jsonArray = JsonPath.read(json, "$.items.book[*]");
|
||||
assertEquals(2, jsonArray.size());
|
||||
}
|
||||
|
||||
}
|
|
@ -1,17 +1,18 @@
|
|||
package com.baeldung.jdo;
|
||||
|
||||
import org.datanucleus.api.jdo.JDOPersistenceManagerFactory;
|
||||
import org.datanucleus.metadata.PersistenceUnitMetaData;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.jdo.PersistenceManager;
|
||||
import javax.jdo.PersistenceManagerFactory;
|
||||
import javax.jdo.Query;
|
||||
import javax.jdo.Transaction;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
import org.datanucleus.api.jdo.JDOPersistenceManagerFactory;
|
||||
import org.datanucleus.metadata.PersistenceUnitMetaData;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GuideToJDOIntegrationTest {
|
||||
@Test
|
||||
|
@ -24,6 +25,7 @@ public class GuideToJDOIntegrationTest {
|
|||
pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa");
|
||||
pumd.addProperty("javax.jdo.option.ConnectionPassword", "");
|
||||
pumd.addProperty("datanucleus.autoCreateSchema", "true");
|
||||
pumd.addProperty("datanucleus.schema.autoCreateTables", "true");
|
||||
|
||||
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
|
||||
PersistenceManager pm = pmf.getPersistenceManager();
|
||||
|
@ -58,6 +60,7 @@ public class GuideToJDOIntegrationTest {
|
|||
pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa");
|
||||
pumd.addProperty("javax.jdo.option.ConnectionPassword", "");
|
||||
pumd.addProperty("datanucleus.autoCreateSchema", "true");
|
||||
pumd.addProperty("datanucleus.schema.autoCreateTables", "true");
|
||||
|
||||
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
|
||||
PersistenceManager pm = pmf.getPersistenceManager();
|
||||
|
|
|
@ -0,0 +1,8 @@
|
|||
*.class
|
||||
|
||||
# Folders #
|
||||
/gensrc
|
||||
/target
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
|
@ -722,6 +722,17 @@
|
|||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.squareup</groupId>
|
||||
<artifactId>javapoet</artifactId>
|
||||
<version>${javapoet.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-all</artifactId>
|
||||
<version>${hamcrest-all.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
@ -939,6 +950,8 @@
|
|||
<xchart-version>3.5.2</xchart-version>
|
||||
<commons-net.version>3.6</commons-net.version>
|
||||
<mockftpserver.version>2.7.1</mockftpserver.version>
|
||||
<javapoet.version>1.10.0</javapoet.version>
|
||||
<hamcrest-all.version>1.3</hamcrest-all.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,183 @@
|
|||
package com.baeldung.javapoet;
|
||||
|
||||
import com.squareup.javapoet.ClassName;
|
||||
import com.squareup.javapoet.CodeBlock;
|
||||
import com.squareup.javapoet.FieldSpec;
|
||||
import com.squareup.javapoet.JavaFile;
|
||||
import com.squareup.javapoet.MethodSpec;
|
||||
import com.squareup.javapoet.ParameterSpec;
|
||||
import com.squareup.javapoet.ParameterizedTypeName;
|
||||
import com.squareup.javapoet.TypeName;
|
||||
import com.squareup.javapoet.TypeSpec;
|
||||
|
||||
import javax.lang.model.element.Modifier;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class PersonGenerator {
|
||||
|
||||
private static final String FOUR_WHITESPACES = " ";
|
||||
private static final String PERSON_PACKAGE_NAME = "com.baeldung.javapoet.test.person";
|
||||
|
||||
private File outputFile;
|
||||
|
||||
public PersonGenerator() {
|
||||
outputFile = new File(getOutputPath().toUri());
|
||||
}
|
||||
|
||||
public static String getPersonPackageName() {
|
||||
return PERSON_PACKAGE_NAME;
|
||||
}
|
||||
|
||||
public Path getOutputPath() {
|
||||
return Paths.get(new File(".").getAbsolutePath() + "/gensrc");
|
||||
}
|
||||
|
||||
public FieldSpec getDefaultNameField() {
|
||||
return FieldSpec
|
||||
.builder(String.class, "DEFAULT_NAME")
|
||||
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
|
||||
.initializer("$S", "Alice")
|
||||
.build();
|
||||
}
|
||||
|
||||
public MethodSpec getSortByLengthMethod() {
|
||||
return MethodSpec
|
||||
.methodBuilder("sortByLength")
|
||||
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
|
||||
.addParameter(ParameterSpec
|
||||
.builder(ParameterizedTypeName.get(ClassName.get(List.class), TypeName.get(String.class)), "strings")
|
||||
.build())
|
||||
.addStatement("$T.sort($N, $L)", Collections.class, "strings", getComparatorAnonymousClass())
|
||||
.build();
|
||||
}
|
||||
|
||||
public MethodSpec getPrintNameMultipleTimesMethod() {
|
||||
return MethodSpec
|
||||
.methodBuilder("printNameMultipleTimes")
|
||||
.addModifiers(Modifier.PUBLIC)
|
||||
.addCode(getPrintNameMultipleTimesLambdaImpl())
|
||||
.build();
|
||||
}
|
||||
|
||||
public CodeBlock getPrintNameMultipleTimesImpl() {
|
||||
return CodeBlock
|
||||
.builder()
|
||||
.beginControlFlow("for (int i = $L; i < $L; i++)")
|
||||
.addStatement("System.out.println(name)")
|
||||
.endControlFlow()
|
||||
.build();
|
||||
}
|
||||
|
||||
public CodeBlock getPrintNameMultipleTimesLambdaImpl() {
|
||||
return CodeBlock
|
||||
.builder()
|
||||
.addStatement("$T<$T> names = new $T<>()", List.class, String.class, ArrayList.class)
|
||||
.addStatement("$T.range($L, $L).forEach(i -> names.add(name))", IntStream.class, 0, 10)
|
||||
.addStatement("names.forEach(System.out::println)")
|
||||
.build();
|
||||
}
|
||||
|
||||
public TypeSpec getGenderEnum() {
|
||||
return TypeSpec
|
||||
.enumBuilder("Gender")
|
||||
.addModifiers(Modifier.PUBLIC)
|
||||
.addEnumConstant("MALE")
|
||||
.addEnumConstant("FEMALE")
|
||||
.addEnumConstant("UNSPECIFIED")
|
||||
.build();
|
||||
}
|
||||
|
||||
public TypeSpec getPersonInterface() {
|
||||
return TypeSpec
|
||||
.interfaceBuilder("Person")
|
||||
.addModifiers(Modifier.PUBLIC)
|
||||
.addField(getDefaultNameField())
|
||||
.addMethod(MethodSpec
|
||||
.methodBuilder("getName")
|
||||
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
|
||||
.returns(String.class)
|
||||
.build())
|
||||
.addMethod(MethodSpec
|
||||
.methodBuilder("getDefaultName")
|
||||
.addModifiers(Modifier.PUBLIC, Modifier.DEFAULT)
|
||||
.returns(String.class)
|
||||
.addCode(CodeBlock
|
||||
.builder()
|
||||
.addStatement("return DEFAULT_NAME")
|
||||
.build())
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
public TypeSpec getStudentClass() {
|
||||
return TypeSpec
|
||||
.classBuilder("Student")
|
||||
.addSuperinterface(ClassName.get(PERSON_PACKAGE_NAME, "Person"))
|
||||
.addModifiers(Modifier.PUBLIC)
|
||||
.addField(FieldSpec
|
||||
.builder(String.class, "name")
|
||||
.addModifiers(Modifier.PRIVATE)
|
||||
.build())
|
||||
.addMethod(MethodSpec
|
||||
.methodBuilder("getName")
|
||||
.addAnnotation(Override.class)
|
||||
.addModifiers(Modifier.PUBLIC)
|
||||
.returns(String.class)
|
||||
.addStatement("return this.name")
|
||||
.build())
|
||||
.addMethod(MethodSpec
|
||||
.methodBuilder("setName")
|
||||
.addParameter(String.class, "name")
|
||||
.addModifiers(Modifier.PUBLIC)
|
||||
.addStatement("this.name = name")
|
||||
.build())
|
||||
.addMethod(getPrintNameMultipleTimesMethod())
|
||||
.addMethod(getSortByLengthMethod())
|
||||
.build();
|
||||
}
|
||||
|
||||
public TypeSpec getComparatorAnonymousClass() {
|
||||
return TypeSpec
|
||||
.anonymousClassBuilder("")
|
||||
.addSuperinterface(ParameterizedTypeName.get(Comparator.class, String.class))
|
||||
.addMethod(MethodSpec
|
||||
.methodBuilder("compare")
|
||||
.addModifiers(Modifier.PUBLIC)
|
||||
.addAnnotation(Override.class)
|
||||
.addParameter(String.class, "a")
|
||||
.addParameter(String.class, "b")
|
||||
.returns(int.class)
|
||||
.addStatement("return a.length() - b.length()")
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
public void generateGenderEnum() throws IOException {
|
||||
writeToOutputFile(getPersonPackageName(), getGenderEnum());
|
||||
}
|
||||
|
||||
public void generatePersonInterface() throws IOException {
|
||||
writeToOutputFile(getPersonPackageName(), getPersonInterface());
|
||||
}
|
||||
|
||||
public void generateStudentClass() throws IOException {
|
||||
writeToOutputFile(getPersonPackageName(), getStudentClass());
|
||||
}
|
||||
|
||||
private void writeToOutputFile(String packageName, TypeSpec typeSpec) throws IOException {
|
||||
JavaFile javaFile = JavaFile
|
||||
.builder(packageName, typeSpec)
|
||||
.indent(FOUR_WHITESPACES)
|
||||
.build();
|
||||
javaFile.writeTo(outputFile);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,141 @@
|
|||
package com.baeldung.date;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.Locale;
|
||||
|
||||
import org.apache.commons.lang3.time.DateUtils;
|
||||
import org.joda.time.DateTime;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
|
||||
public class StringToDateUnitTest {
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
@Test
|
||||
public void givenDateString_whenConvertedToDate_thenWeGetCorrectLocalDate() {
|
||||
LocalDate expectedLocalDate = LocalDate.of(2018, 05, 05);
|
||||
|
||||
LocalDate date = LocalDate.parse("2018-05-05");
|
||||
|
||||
assertThat(date).isEqualTo(expectedLocalDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateString_whenConvertedToDate_thenWeGetCorrectLocalDateTime() {
|
||||
LocalDateTime expectedLocalDateTime = LocalDateTime.of(2018, 05, 05, 11, 50, 55);
|
||||
|
||||
LocalDateTime dateTime = LocalDateTime.parse("2018-05-05T11:50:55");
|
||||
|
||||
assertThat(dateTime).isEqualTo(expectedLocalDateTime);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateString_whenConvertedToDate_thenWeGetDateTimeParseException() {
|
||||
thrown.expect(DateTimeParseException.class);
|
||||
thrown.expectMessage("Text '2018-05-05' could not be parsed at index 10");
|
||||
|
||||
LocalDateTime.parse("2018-05-05");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateString_whenConvertedToDate_thenWeGetCorrectZonedDateTime() {
|
||||
LocalDateTime localDateTime = LocalDateTime.of(2015, 05, 05, 10, 15, 30);
|
||||
ZonedDateTime expectedZonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("Europe/Paris"));
|
||||
|
||||
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2015-05-05T10:15:30+01:00[Europe/Paris]");
|
||||
|
||||
assertThat(zonedDateTime).isEqualTo(expectedZonedDateTime);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateString_whenConvertedToDateUsingFormatter_thenWeGetCorrectLocalDate() {
|
||||
LocalDate expectedLocalDate = LocalDate.of(1959, 7, 9);
|
||||
|
||||
String dateInString = "19590709";
|
||||
LocalDate date = LocalDate.parse(dateInString, DateTimeFormatter.BASIC_ISO_DATE);
|
||||
|
||||
assertThat(date).isEqualTo(expectedLocalDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateString_whenConvertedToDateUsingCustomFormatter_thenWeGetCorrectLocalDate() {
|
||||
LocalDate expectedLocalDate = LocalDate.of(1980, 05, 05);
|
||||
|
||||
String dateInString = "Mon, 05 May 1980";
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, d MMM yyyy", Locale.ENGLISH);
|
||||
LocalDate dateTime = LocalDate.parse(dateInString, formatter);
|
||||
|
||||
assertThat(dateTime).isEqualTo(expectedLocalDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateString_whenConvertedToDate_thenWeGetCorrectDate() throws ParseException {
|
||||
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
|
||||
|
||||
String dateInString = "7-Jun-2013";
|
||||
Date date = formatter.parse(dateInString);
|
||||
|
||||
assertDateIsCorrect(date);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateString_whenConvertedToDate_thenWeGetParseException() throws ParseException {
|
||||
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
|
||||
|
||||
thrown.expect(ParseException.class);
|
||||
thrown.expectMessage("Unparseable date: \"07/06/2013\"");
|
||||
|
||||
String dateInString = "07/06/2013";
|
||||
formatter.parse(dateInString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateString_whenConvertedToDate_thenWeGetCorrectJodaDateTime() {
|
||||
org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
|
||||
|
||||
String dateInString = "07/06/2013 10:11:59";
|
||||
DateTime dateTime = DateTime.parse(dateInString, formatter);
|
||||
|
||||
assertEquals("Day of Month should be 7: ", 7, dateTime.getDayOfMonth());
|
||||
assertEquals("Month should be: ", 6, dateTime.getMonthOfYear());
|
||||
assertEquals("Year should be: ", 2013, dateTime.getYear());
|
||||
|
||||
assertEquals("Hour of day should be: ", 10, dateTime.getHourOfDay());
|
||||
assertEquals("Minutes of hour should be: ", 11, dateTime.getMinuteOfHour());
|
||||
assertEquals("Seconds of minute should be: ", 59, dateTime.getSecondOfMinute());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateString_whenConvertedToDate_thenWeGetCorrectDateTime() throws ParseException {
|
||||
String dateInString = "07/06-2013";
|
||||
Date date = DateUtils.parseDate(dateInString, new String[] { "yyyy-MM-dd HH:mm:ss", "dd/MM-yyyy" });
|
||||
|
||||
assertDateIsCorrect(date);
|
||||
}
|
||||
|
||||
private void assertDateIsCorrect(Date date) {
|
||||
Calendar calendar = new GregorianCalendar(Locale.ENGLISH);
|
||||
calendar.setTime(date);
|
||||
|
||||
assertEquals("Day of Month should be 7: ", 7, calendar.get(Calendar.DAY_OF_MONTH));
|
||||
assertEquals("Month should be: ", 5, calendar.get(Calendar.MONTH));
|
||||
assertEquals("Year should be: ", 2013, calendar.get(Calendar.YEAR));
|
||||
}
|
||||
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue