Merge remote-tracking branch 'upstream/master'
# Conflicts: # spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml # spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java # spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml # spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java
This commit is contained in:
commit
8f1ca08b46
|
@ -0,0 +1,3 @@
|
|||
## Relevant articles:
|
||||
|
||||
- [A Guide to JGit](http://www.baeldung.com/jgit)
|
|
@ -0,0 +1,4 @@
|
|||
## Relevant articles:
|
||||
|
||||
- [Dijkstra Algorithm in Java](http://www.baeldung.com/java-dijkstra)
|
||||
- [Introduction to Cobertura](http://www.baeldung.com/cobertura)
|
|
@ -41,4 +41,23 @@
|
|||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
</project>
|
||||
<reporting>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>cobertura-maven-plugin</artifactId>
|
||||
<version>2.7</version>
|
||||
<configuration>
|
||||
<instrumentation>
|
||||
<ignores>
|
||||
<ignore>com/baeldung/algorithms/dijkstra/*</ignore>
|
||||
</ignores>
|
||||
<excludes>
|
||||
<exclude>com/baeldung/algorithms/dijkstra/*</exclude>
|
||||
</excludes>
|
||||
</instrumentation>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</reporting>
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [Intro to Apache BVal](http://www.baeldung.com/apache-bval)
|
|
@ -0,0 +1,51 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>apache-bval</groupId>
|
||||
<artifactId>apache-bval</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.bval</groupId>
|
||||
<artifactId>bval-jsr</artifactId>
|
||||
<version>${bval.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
<version>1.1.0.Final</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.bval</groupId>
|
||||
<artifactId>bval-extras</artifactId>
|
||||
<version>${bval.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<properties>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<bval.version>1.1.2</bval.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,120 @@
|
|||
package com.baeldung.model;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
import org.apache.bval.constraints.Email;
|
||||
import org.apache.bval.constraints.NotEmpty;
|
||||
import org.apache.bval.extras.constraints.checkdigit.IBAN;
|
||||
import org.apache.bval.extras.constraints.creditcard.Visa;
|
||||
import org.apache.bval.extras.constraints.file.Directory;
|
||||
import org.apache.bval.extras.constraints.net.InetAddress;
|
||||
|
||||
import com.baeldung.validation.Password;
|
||||
|
||||
public class User {
|
||||
@NotNull
|
||||
@Email
|
||||
private String email;
|
||||
|
||||
@NotEmpty
|
||||
@Password
|
||||
private String password;
|
||||
|
||||
@Size(min = 1, max = 20)
|
||||
private String name;
|
||||
|
||||
@Min(18)
|
||||
private int age;
|
||||
|
||||
@Visa
|
||||
private String cardNumber = "";
|
||||
|
||||
@IBAN
|
||||
private String iban = "";
|
||||
|
||||
@InetAddress
|
||||
private String website = "";
|
||||
|
||||
@Directory
|
||||
private File mainDirectory=new File(".");
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String email, String password, String name, int age) {
|
||||
super();
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getCardNumber() {
|
||||
return cardNumber;
|
||||
}
|
||||
|
||||
public void setCardNumber(String cardNumber) {
|
||||
this.cardNumber = cardNumber;
|
||||
}
|
||||
|
||||
public String getIban() {
|
||||
return iban;
|
||||
}
|
||||
|
||||
public void setIban(String iban) {
|
||||
this.iban = iban;
|
||||
}
|
||||
|
||||
public String getWebsite() {
|
||||
return website;
|
||||
}
|
||||
|
||||
public void setWebsite(String website) {
|
||||
this.website = website;
|
||||
}
|
||||
|
||||
public File getMainDirectory() {
|
||||
return mainDirectory;
|
||||
}
|
||||
|
||||
public void setMainDirectory(File mainDirectory) {
|
||||
this.mainDirectory = mainDirectory;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.validation;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import javax.validation.Constraint;
|
||||
import javax.validation.Payload;
|
||||
|
||||
import static java.lang.annotation.ElementType.*;
|
||||
|
||||
@Constraint(validatedBy = { PasswordValidator.class })
|
||||
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface Password {
|
||||
String message() default "Invalid password";
|
||||
|
||||
Class<?>[] groups() default {};
|
||||
|
||||
Class<? extends Payload>[] payload() default {};
|
||||
|
||||
int length() default 6;
|
||||
|
||||
int nonAlpha() default 1;
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package com.baeldung.validation;
|
||||
|
||||
import javax.validation.ConstraintValidator;
|
||||
import javax.validation.ConstraintValidatorContext;
|
||||
|
||||
public class PasswordValidator implements ConstraintValidator<Password, String> {
|
||||
|
||||
private int length;
|
||||
private int nonAlpha;
|
||||
|
||||
@Override
|
||||
public void initialize(Password password) {
|
||||
this.length = password.length();
|
||||
this.nonAlpha = password.nonAlpha();
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(String value, ConstraintValidatorContext context) {
|
||||
if (value.length() < length) {
|
||||
return false;
|
||||
}
|
||||
int nonAlphaNr = 0;
|
||||
for (int i = 0; i < value.length(); i++) {
|
||||
if (!Character.isLetterOrDigit(value.charAt(i))) {
|
||||
nonAlphaNr++;
|
||||
}
|
||||
}
|
||||
if (nonAlphaNr < nonAlpha) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,97 @@
|
|||
package com.baeldung.validation;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import javax.validation.ValidatorFactory;
|
||||
|
||||
import org.apache.bval.jsr.ApacheValidationProvider;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import com.baeldung.model.User;
|
||||
|
||||
public class ValidationTest {
|
||||
private static ValidatorFactory validatorFactory;
|
||||
private static Validator validator;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
validatorFactory = Validation.byProvider(ApacheValidationProvider.class)
|
||||
.configure()
|
||||
.buildValidatorFactory();
|
||||
validator = validatorFactory.getValidator();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUser_whenValidate_thenValidationViolations() {
|
||||
User user = new User("ana@yahoo.com", "pass", "nameTooLong_______________", 15);
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validate(user);
|
||||
assertTrue("no violations", violations.size() > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidAge_whenValidateProperty_thenConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "pass", "Ana", 12);
|
||||
|
||||
Set<ConstraintViolation<User>> propertyViolations = validator.validateProperty(user, "age");
|
||||
assertEquals("size is not 1", 1, propertyViolations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidAge_whenValidateValue_thenNoConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "pass", "Ana", 18);
|
||||
|
||||
Set<ConstraintViolation<User>> valueViolations = validator.validateValue(User.class, "age", 20);
|
||||
assertEquals("size is not 0", 0, valueViolations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidateNonJSR_thenCorrect() {
|
||||
User user = new User("ana@yahoo.com", "pass", "Ana", 20);
|
||||
user.setCardNumber("1234");
|
||||
user.setIban("1234");
|
||||
user.setWebsite("10.0.2.50");
|
||||
user.setMainDirectory(new File("."));
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validateProperty(user, "iban");
|
||||
assertEquals("size is not 1", 1, violations.size());
|
||||
|
||||
violations = validator.validateProperty(user, "website");
|
||||
assertEquals("size is not 0", 0, violations.size());
|
||||
|
||||
violations = validator.validateProperty(user, "mainDirectory");
|
||||
assertEquals("size is not 0", 0, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidPassword_whenValidatePassword_thenConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "password", "Ana", 20);
|
||||
Set<ConstraintViolation<User>> violations = validator.validateProperty(user, "password");
|
||||
assertEquals("message incorrect", "Invalid password", violations.iterator()
|
||||
.next()
|
||||
.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidPassword_whenValidatePassword_thenNoConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "password#", "Ana", 20);
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validateProperty(user, "password");
|
||||
assertEquals("size is not 0", 0, violations.size());
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void close() {
|
||||
if (validatorFactory != null) {
|
||||
validatorFactory.close();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-solrj</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>apache-solrj</name>
|
||||
|
||||
<properties>
|
||||
<junit.version>4.12</junit.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.solr</groupId>
|
||||
<artifactId>solr-solrj</artifactId>
|
||||
<version>6.4.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>2.3.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.solrjava;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.solr.client.solrj.SolrServerException;
|
||||
import org.apache.solr.client.solrj.impl.HttpSolrClient;
|
||||
import org.apache.solr.client.solrj.impl.XMLResponseParser;
|
||||
import org.apache.solr.common.SolrInputDocument;
|
||||
|
||||
public class SolrJavaIntegration {
|
||||
|
||||
private HttpSolrClient solrClient;
|
||||
|
||||
public SolrJavaIntegration(String clientUrl) {
|
||||
|
||||
solrClient = new HttpSolrClient.Builder(clientUrl).build();
|
||||
solrClient.setParser(new XMLResponseParser());
|
||||
}
|
||||
|
||||
public void addSolrDocument(String documentId, String itemName, String itemPrice) throws SolrServerException, IOException {
|
||||
|
||||
SolrInputDocument document = new SolrInputDocument();
|
||||
document.addField("id", documentId);
|
||||
document.addField("name", itemName);
|
||||
document.addField("price", itemPrice);
|
||||
solrClient.add(document);
|
||||
solrClient.commit();
|
||||
}
|
||||
|
||||
public void deleteSolrDocument(String documentId) throws SolrServerException, IOException {
|
||||
|
||||
solrClient.deleteById(documentId);
|
||||
solrClient.commit();
|
||||
}
|
||||
|
||||
protected HttpSolrClient getSolrClient() {
|
||||
return solrClient;
|
||||
}
|
||||
|
||||
protected void setSolrClient(HttpSolrClient solrClient) {
|
||||
this.solrClient = solrClient;
|
||||
}
|
||||
}
|
|
@ -6,42 +6,31 @@ import java.io.IOException;
|
|||
|
||||
import org.apache.solr.client.solrj.SolrQuery;
|
||||
import org.apache.solr.client.solrj.SolrServerException;
|
||||
import org.apache.solr.client.solrj.impl.HttpSolrClient;
|
||||
import org.apache.solr.client.solrj.impl.XMLResponseParser;
|
||||
import org.apache.solr.client.solrj.response.QueryResponse;
|
||||
import org.apache.solr.common.SolrDocument;
|
||||
import org.apache.solr.common.SolrDocumentList;
|
||||
import org.apache.solr.common.SolrInputDocument;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SolrJavaIntegrationTest {
|
||||
|
||||
private HttpSolrClient solr;
|
||||
private SolrJavaIntegration solrJavaIntegration;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
|
||||
solr = new HttpSolrClient("http://localhost:8983/solr/bigboxstore");
|
||||
solr.setParser(new XMLResponseParser());
|
||||
solrJavaIntegration = new SolrJavaIntegration("http://localhost:8983/solr/bigboxstore");
|
||||
solrJavaIntegration.addSolrDocument("123456", "Kenmore Dishwasher", "599.99");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAdd_thenVerifyAdded() throws SolrServerException, IOException {
|
||||
|
||||
SolrInputDocument document = new SolrInputDocument();
|
||||
document.addField("id", "123456");
|
||||
document.addField("name", "Kenmore Dishwasher");
|
||||
document.addField("price", "599.99");
|
||||
|
||||
solr.add(document);
|
||||
solr.commit();
|
||||
public void whenAdd_thenVerifyAdded() throws SolrServerException, IOException {
|
||||
|
||||
SolrQuery query = new SolrQuery();
|
||||
query.set("q", "id:123456");
|
||||
QueryResponse response = null;
|
||||
|
||||
response = solr.query(query);
|
||||
response = solrJavaIntegration.getSolrClient().query(query);
|
||||
|
||||
SolrDocumentList docList = response.getResults();
|
||||
assertEquals(docList.getNumFound(), 1);
|
||||
|
@ -53,16 +42,15 @@ public class SolrJavaIntegrationTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void givenDelete_thenVerifyDeleted() throws SolrServerException, IOException {
|
||||
public void whenDelete_thenVerifyDeleted() throws SolrServerException, IOException {
|
||||
|
||||
solr.deleteById("123456");
|
||||
solr.commit();
|
||||
solrJavaIntegration.deleteSolrDocument("123456");
|
||||
|
||||
SolrQuery query = new SolrQuery();
|
||||
query.set("q", "id:123456");
|
||||
QueryResponse response = null;
|
||||
|
||||
response = solr.query(query);
|
||||
response = solrJavaIntegration.getSolrClient().query(query);
|
||||
|
||||
SolrDocumentList docList = response.getResults();
|
||||
assertEquals(docList.getNumFound(), 0);
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant articles:
|
||||
|
||||
- [Working with Apache Thrift](http://www.baeldung.com/apache-thrift)
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant articles:
|
||||
|
||||
- [Introduction to Apache Velocity](http://www.baeldung.com/apache-velocity)
|
25
aws/pom.xml
25
aws/pom.xml
|
@ -7,17 +7,36 @@
|
|||
<packaging>jar</packaging>
|
||||
<name>aws</name>
|
||||
|
||||
<properties>
|
||||
<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.1.0</aws-lambda-java-core.version>
|
||||
<gson.version>2.8.0</gson.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-lambda-java-core</artifactId>
|
||||
<version>1.1.0</version>
|
||||
<version>${aws-lambda-java-core.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-lambda-java-events</artifactId>
|
||||
<version>${aws-lambda-java-events.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.5</version>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>${gson.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
@ -26,7 +45,7 @@
|
|||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>2.3</version>
|
||||
<version>3.0.0</version>
|
||||
<configuration>
|
||||
<createDependencyReducedPom>false</createDependencyReducedPom>
|
||||
</configuration>
|
||||
|
|
|
@ -0,0 +1,49 @@
|
|||
package com.baeldung.lambda.dynamodb;
|
||||
|
||||
import com.amazonaws.regions.Region;
|
||||
import com.amazonaws.regions.Regions;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.document.Item;
|
||||
import com.amazonaws.services.dynamodbv2.document.PutItemOutcome;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.PutItemSpec;
|
||||
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException;
|
||||
import com.amazonaws.services.lambda.runtime.Context;
|
||||
import com.amazonaws.services.lambda.runtime.RequestHandler;
|
||||
import com.baeldung.lambda.dynamodb.bean.PersonRequest;
|
||||
import com.baeldung.lambda.dynamodb.bean.PersonResponse;
|
||||
|
||||
public class SavePersonHandler implements RequestHandler<PersonRequest, PersonResponse> {
|
||||
|
||||
private DynamoDB dynamoDb;
|
||||
|
||||
private String DYNAMODB_TABLE_NAME = "Person";
|
||||
private Regions REGION = Regions.US_WEST_2;
|
||||
|
||||
public PersonResponse handleRequest(PersonRequest personRequest, Context context) {
|
||||
this.initDynamoDbClient();
|
||||
|
||||
persistData(personRequest);
|
||||
|
||||
PersonResponse personResponse = new PersonResponse();
|
||||
personResponse.setMessage("Saved Successfully!!!");
|
||||
return personResponse;
|
||||
}
|
||||
|
||||
private PutItemOutcome persistData(PersonRequest personRequest) throws ConditionalCheckFailedException {
|
||||
return this.dynamoDb.getTable(DYNAMODB_TABLE_NAME)
|
||||
.putItem(
|
||||
new PutItemSpec().withItem(new Item()
|
||||
.withNumber("id", personRequest.getId())
|
||||
.withString("firstName", personRequest.getFirstName())
|
||||
.withString("lastName", personRequest.getLastName())
|
||||
.withNumber("age", personRequest.getAge())
|
||||
.withString("address", personRequest.getAddress())));
|
||||
}
|
||||
|
||||
private void initDynamoDbClient() {
|
||||
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
|
||||
client.setRegion(Region.getRegion(REGION));
|
||||
this.dynamoDb = new DynamoDB(client);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
package com.baeldung.lambda.dynamodb.bean;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
|
||||
public class PersonRequest {
|
||||
private int id;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private int age;
|
||||
private String address;
|
||||
|
||||
public static void main(String[] args) {
|
||||
PersonRequest personRequest = new PersonRequest();
|
||||
personRequest.setId(1);
|
||||
personRequest.setFirstName("John");
|
||||
personRequest.setLastName("Doe");
|
||||
personRequest.setAge(30);
|
||||
personRequest.setAddress("United States");
|
||||
System.out.println(personRequest);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.lambda.dynamodb.bean;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
|
||||
public class PersonResponse {
|
||||
private String message;
|
||||
|
||||
public String toString() {
|
||||
final Gson gson = new Gson();
|
||||
return gson.toJson(this);
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
|
@ -6,3 +6,5 @@
|
|||
|
||||
### Relevant Articles:
|
||||
- [Java 9 Stream API Improvements](http://www.baeldung.com/java-9-stream-api)
|
||||
- [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods)
|
||||
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
|
||||
|
|
|
@ -21,6 +21,11 @@
|
|||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${ch.qos.logback.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
|
@ -76,9 +81,9 @@
|
|||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||
|
||||
<ch.qos.logback.version>1.2.1</ch.qos.logback.version>
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.6-jigsaw-SNAPSHOT</maven-compiler-plugin.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
|
||||
<!-- testing -->
|
||||
|
|
|
@ -0,0 +1,133 @@
|
|||
package com.baeldung.java9.process;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Created by sanaulla on 2/23/2017.
|
||||
*/
|
||||
|
||||
public class ProcessAPIEnhancementsTest {
|
||||
|
||||
Logger log = LoggerFactory.getLogger(ProcessAPIEnhancementsTest.class);
|
||||
|
||||
@Test
|
||||
public void givenCurrentProcess_whenInvokeGetInfo_thenSuccess() throws IOException {
|
||||
ProcessHandle processHandle = ProcessHandle.current();
|
||||
ProcessHandle.Info processInfo = processHandle.info();
|
||||
assertNotNull(processHandle.getPid());
|
||||
assertEquals(false, processInfo.arguments()
|
||||
.isPresent());
|
||||
assertEquals(true, processInfo.command()
|
||||
.isPresent());
|
||||
assertTrue(processInfo.command()
|
||||
.get()
|
||||
.contains("java"));
|
||||
|
||||
assertEquals(true, processInfo.startInstant()
|
||||
.isPresent());
|
||||
assertEquals(true, processInfo.totalCpuDuration()
|
||||
.isPresent());
|
||||
assertEquals(true, processInfo.user()
|
||||
.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSpawnProcess_whenInvokeGetInfo_thenSuccess() throws IOException {
|
||||
|
||||
String javaCmd = ProcessUtils.getJavaCmd()
|
||||
.getAbsolutePath();
|
||||
ProcessBuilder processBuilder = new ProcessBuilder(javaCmd, "-version");
|
||||
Process process = processBuilder.inheritIO()
|
||||
.start();
|
||||
ProcessHandle processHandle = process.toHandle();
|
||||
ProcessHandle.Info processInfo = processHandle.info();
|
||||
assertNotNull(processHandle.getPid());
|
||||
assertEquals(false, processInfo.arguments()
|
||||
.isPresent());
|
||||
assertEquals(true, processInfo.command()
|
||||
.isPresent());
|
||||
assertTrue(processInfo.command()
|
||||
.get()
|
||||
.contains("java"));
|
||||
assertEquals(true, processInfo.startInstant()
|
||||
.isPresent());
|
||||
assertEquals(true, processInfo.totalCpuDuration()
|
||||
.isPresent());
|
||||
assertEquals(true, processInfo.user()
|
||||
.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLiveProcesses_whenInvokeGetInfo_thenSuccess() {
|
||||
Stream<ProcessHandle> liveProcesses = ProcessHandle.allProcesses();
|
||||
liveProcesses.filter(ProcessHandle::isAlive)
|
||||
.forEach(ph -> {
|
||||
assertNotNull(ph.getPid());
|
||||
assertEquals(true, ph.info()
|
||||
.command()
|
||||
.isPresent());
|
||||
assertEquals(true, ph.info()
|
||||
.startInstant()
|
||||
.isPresent());
|
||||
assertEquals(true, ph.info()
|
||||
.totalCpuDuration()
|
||||
.isPresent());
|
||||
assertEquals(true, ph.info()
|
||||
.user()
|
||||
.isPresent());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenProcess_whenGetChildProcess_thenSuccess() throws IOException {
|
||||
int childProcessCount = 5;
|
||||
for (int i = 0; i < childProcessCount; i++) {
|
||||
String javaCmd = ProcessUtils.getJavaCmd()
|
||||
.getAbsolutePath();
|
||||
ProcessBuilder processBuilder
|
||||
= new ProcessBuilder(javaCmd, "-version");
|
||||
processBuilder.inheritIO().start();
|
||||
}
|
||||
|
||||
Stream<ProcessHandle> children = ProcessHandle.current()
|
||||
.children();
|
||||
children.filter(ProcessHandle::isAlive)
|
||||
.forEach(ph -> log.info("PID: {}, Cmd: {}", ph.getPid(), ph.info()
|
||||
.command()));
|
||||
Stream<ProcessHandle> descendants = ProcessHandle.current()
|
||||
.descendants();
|
||||
descendants.filter(ProcessHandle::isAlive)
|
||||
.forEach(ph -> log.info("PID: {}, Cmd: {}", ph.getPid(), ph.info()
|
||||
.command()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenProcess_whenAddExitCallback_thenSuccess() throws Exception {
|
||||
String javaCmd = ProcessUtils.getJavaCmd()
|
||||
.getAbsolutePath();
|
||||
ProcessBuilder processBuilder
|
||||
= new ProcessBuilder(javaCmd, "-version");
|
||||
Process process = processBuilder.inheritIO()
|
||||
.start();
|
||||
ProcessHandle processHandle = process.toHandle();
|
||||
|
||||
log.info("PID: {} has started", processHandle.getPid());
|
||||
CompletableFuture<ProcessHandle> onProcessExit = processHandle.onExit();
|
||||
onProcessExit.get();
|
||||
assertEquals(false, processHandle.isAlive());
|
||||
onProcessExit.thenAccept(ph -> {
|
||||
log.info("PID: {} has stopped", ph.getPid());
|
||||
});
|
||||
}
|
||||
|
||||
}
|
|
@ -58,3 +58,24 @@
|
|||
- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue)
|
||||
- [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch)
|
||||
- [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm)
|
||||
- [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map)
|
||||
- [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue)
|
||||
- [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector)
|
||||
- [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception)
|
||||
- [Guide to WeakHashMap in Java](http://www.baeldung.com/java-weakhashmap)
|
||||
- [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern)
|
||||
- [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams)
|
||||
- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool)
|
||||
- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings)
|
||||
- [Spring Security – Cache Control Headers](http://www.baeldung.com/spring-security-cache-control-headers)
|
||||
- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions)
|
||||
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
|
||||
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
|
||||
- [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions)
|
||||
- [Guide to the Guava BiMap](http://www.baeldung.com/guava-bimap)
|
||||
- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream)
|
||||
- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany)
|
||||
- [Chained Exceptions in Java](http://www.baeldung.com/java-chained-exceptions)
|
||||
- [The Java HashMap Under the Hood](http://www.baeldung.com/java-hashmap)
|
||||
- [A Guide to LinkedHashMap in Java](http://www.baeldung.com/java-linked-hashmap)
|
||||
- [A Guide to TreeMap in Java](http://www.baeldung.com/java-treemap)
|
||||
|
|
|
@ -2,7 +2,8 @@ package com.baeldung.algorithms;
|
|||
|
||||
import java.util.Scanner;
|
||||
|
||||
import com.baeldung.algorithms.annealing.SimulatedAnnealing;
|
||||
import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
|
||||
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
|
||||
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
|
||||
import com.baeldung.algorithms.slope_one.SlopeOne;
|
||||
|
||||
|
@ -14,6 +15,7 @@ public class RunAlgorithm {
|
|||
System.out.println("1 - Simulated Annealing");
|
||||
System.out.println("2 - Slope One");
|
||||
System.out.println("3 - Simple Genetic Algorithm");
|
||||
System.out.println("4 - Ant Colony");
|
||||
int decision = in.nextInt();
|
||||
switch (decision) {
|
||||
case 1:
|
||||
|
@ -27,6 +29,10 @@ public class RunAlgorithm {
|
|||
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
|
||||
ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
|
||||
break;
|
||||
case 4:
|
||||
AntColonyOptimization antColony = new AntColonyOptimization(21);
|
||||
antColony.startAntOptimization();
|
||||
break;
|
||||
default:
|
||||
System.out.println("Unknown option");
|
||||
break;
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.algorithms.annealing;
|
||||
package com.baeldung.algorithms.ga.annealing;
|
||||
|
||||
import lombok.Data;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.algorithms.annealing;
|
||||
package com.baeldung.algorithms.ga.annealing;
|
||||
|
||||
public class SimulatedAnnealing {
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.algorithms.annealing;
|
||||
package com.baeldung.algorithms.ga.annealing;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.algorithms.ga.ant_colony;
|
||||
|
||||
public class Ant {
|
||||
|
||||
protected int trailSize;
|
||||
protected int trail[];
|
||||
protected boolean visited[];
|
||||
|
||||
public Ant(int tourSize) {
|
||||
this.trailSize = tourSize;
|
||||
this.trail = new int[tourSize];
|
||||
this.visited = new boolean[tourSize];
|
||||
}
|
||||
|
||||
protected void visitCity(int currentIndex, int city) {
|
||||
trail[currentIndex + 1] = city;
|
||||
visited[city] = true;
|
||||
}
|
||||
|
||||
protected boolean visited(int i) {
|
||||
return visited[i];
|
||||
}
|
||||
|
||||
protected double trailLength(double graph[][]) {
|
||||
double length = graph[trail[trailSize - 1]][trail[0]];
|
||||
for (int i = 0; i < trailSize - 1; i++) {
|
||||
length += graph[trail[i]][trail[i + 1]];
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
protected void clear() {
|
||||
for (int i = 0; i < trailSize; i++)
|
||||
visited[i] = false;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,212 @@
|
|||
package com.baeldung.algorithms.ga.ant_colony;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
|
||||
public class AntColonyOptimization {
|
||||
|
||||
private double c = 1.0;
|
||||
private double alpha = 1;
|
||||
private double beta = 5;
|
||||
private double evaporation = 0.5;
|
||||
private double Q = 500;
|
||||
private double antFactor = 0.8;
|
||||
private double randomFactor = 0.01;
|
||||
|
||||
private int maxIterations = 1000;
|
||||
|
||||
public int numberOfCities;
|
||||
public int numberOfAnts;
|
||||
private double graph[][];
|
||||
private double trails[][];
|
||||
private Ant ants[];
|
||||
private Random random = new Random();
|
||||
private double probabilities[];
|
||||
|
||||
private int currentIndex;
|
||||
|
||||
public int[] bestTourOrder;
|
||||
public double bestTourLength;
|
||||
|
||||
public AntColonyOptimization(int noOfCities) {
|
||||
graph = generateRandomMatrix(noOfCities);
|
||||
numberOfCities = graph.length;
|
||||
numberOfAnts = (int) (numberOfCities * antFactor);
|
||||
|
||||
trails = new double[numberOfCities][numberOfCities];
|
||||
probabilities = new double[numberOfCities];
|
||||
ants = new Ant[numberOfAnts];
|
||||
for (int j = 0; j < numberOfAnts; j++) {
|
||||
ants[j] = new Ant(numberOfCities);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate initial solution
|
||||
* @param n
|
||||
* @return
|
||||
*/
|
||||
public double[][] generateRandomMatrix(int n) {
|
||||
double[][] randomMatrix = new double[n][n];
|
||||
random.setSeed(System.currentTimeMillis());
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = 0; j < n; j++) {
|
||||
Integer r = random.nextInt(100) + 1;
|
||||
randomMatrix[i][j] = Math.abs(r);
|
||||
}
|
||||
}
|
||||
return randomMatrix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform ant optimization
|
||||
* @return
|
||||
*/
|
||||
public int[] startAntOptimization() {
|
||||
int[] finalResult = null;
|
||||
for (int i = 1; i <= 3; i++) {
|
||||
System.out.println("Attempt #" + i);
|
||||
finalResult = solve();
|
||||
}
|
||||
return finalResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Use this method to run the main logic
|
||||
* @return
|
||||
*/
|
||||
private int[] solve() {
|
||||
setupAnts();
|
||||
clearTrails();
|
||||
int iteration = 0;
|
||||
while (iteration < maxIterations) {
|
||||
moveAnts();
|
||||
updateTrails();
|
||||
updateBest();
|
||||
iteration++;
|
||||
}
|
||||
System.out.println("Best tour length: " + (bestTourLength - numberOfCities));
|
||||
System.out.println("Best tour order: " + Arrays.toString(bestTourOrder));
|
||||
return bestTourOrder.clone();
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare ants for the simulation
|
||||
*/
|
||||
private void setupAnts() {
|
||||
currentIndex = -1;
|
||||
for (int i = 0; i < numberOfAnts; i++) {
|
||||
ants[i].clear();
|
||||
ants[i].visitCity(currentIndex, random.nextInt(numberOfCities));
|
||||
}
|
||||
currentIndex++;
|
||||
}
|
||||
|
||||
/**
|
||||
* At each iteration, move ants
|
||||
*/
|
||||
private void moveAnts() {
|
||||
while (currentIndex < numberOfCities - 1) {
|
||||
for (Ant a : ants)
|
||||
a.visitCity(currentIndex, selectNextCity(a));
|
||||
currentIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Select next city for each ant
|
||||
* @param ant
|
||||
* @return
|
||||
*/
|
||||
private int selectNextCity(Ant ant) {
|
||||
if (random.nextDouble() < randomFactor) {
|
||||
int t = random.nextInt(numberOfCities - currentIndex);
|
||||
int j = -1;
|
||||
for (int i = 0; i < numberOfCities; i++) {
|
||||
if (!ant.visited(i)) {
|
||||
j++;
|
||||
}
|
||||
if (j == t) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
calculateProbabilities(ant);
|
||||
double r = random.nextDouble();
|
||||
double total = 0;
|
||||
for (int i = 0; i < numberOfCities; i++) {
|
||||
total += probabilities[i];
|
||||
if (total >= r) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
throw new RuntimeException("There are no other cities");
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the next city picks probabilites
|
||||
* @param ant
|
||||
*/
|
||||
private void calculateProbabilities(Ant ant) {
|
||||
int i = ant.trail[currentIndex];
|
||||
double pheromone = 0.0;
|
||||
for (int l = 0; l < numberOfCities; l++) {
|
||||
if (!ant.visited(l)) {
|
||||
pheromone += Math.pow(trails[i][l], alpha) * Math.pow(1.0 / graph[i][l], beta);
|
||||
}
|
||||
}
|
||||
for (int j = 0; j < numberOfCities; j++) {
|
||||
if (ant.visited(j)) {
|
||||
probabilities[j] = 0.0;
|
||||
} else {
|
||||
double numerator = Math.pow(trails[i][j], alpha) * Math.pow(1.0 / graph[i][j], beta);
|
||||
probabilities[j] = numerator / pheromone;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update trails that ants used
|
||||
*/
|
||||
private void updateTrails() {
|
||||
for (int i = 0; i < numberOfCities; i++) {
|
||||
for (int j = 0; j < numberOfCities; j++) {
|
||||
trails[i][j] *= evaporation;
|
||||
}
|
||||
}
|
||||
for (Ant a : ants) {
|
||||
double contribution = Q / a.trailLength(graph);
|
||||
for (int i = 0; i < numberOfCities - 1; i++) {
|
||||
trails[a.trail[i]][a.trail[i + 1]] += contribution;
|
||||
}
|
||||
trails[a.trail[numberOfCities - 1]][a.trail[0]] += contribution;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the best solution
|
||||
*/
|
||||
private void updateBest() {
|
||||
if (bestTourOrder == null) {
|
||||
bestTourOrder = ants[0].trail;
|
||||
bestTourLength = ants[0].trailLength(graph);
|
||||
}
|
||||
for (Ant a : ants) {
|
||||
if (a.trailLength(graph) < bestTourLength) {
|
||||
bestTourLength = a.trailLength(graph);
|
||||
bestTourOrder = a.trail.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear trails after simulation
|
||||
*/
|
||||
private void clearTrails() {
|
||||
for (int i = 0; i < numberOfCities; i++)
|
||||
for (int j = 0; j < numberOfCities; j++)
|
||||
trails[i][j] = c;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
package com.baeldung.concurrent.locks;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.Stack;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.locks.Condition;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import static java.lang.Thread.sleep;
|
||||
|
||||
public class ReentrantLockWithCondition {
|
||||
|
||||
static Logger logger = LoggerFactory.getLogger(ReentrantLockWithCondition.class);
|
||||
|
||||
Stack<String> stack = new Stack<>();
|
||||
int CAPACITY = 5;
|
||||
|
||||
ReentrantLock lock = new ReentrantLock();
|
||||
Condition stackEmptyCondition = lock.newCondition();
|
||||
Condition stackFullCondition = lock.newCondition();
|
||||
|
||||
public void pushToStack(String item) throws InterruptedException {
|
||||
try {
|
||||
lock.lock();
|
||||
if (stack.size() == CAPACITY) {
|
||||
logger.info(Thread.currentThread().getName() + " wait on stack full");
|
||||
stackFullCondition.await();
|
||||
}
|
||||
logger.info("Pushing the item " + item);
|
||||
stack.push(item);
|
||||
stackEmptyCondition.signalAll();
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public String popFromStack() throws InterruptedException {
|
||||
try {
|
||||
lock.lock();
|
||||
if (stack.size() == 0) {
|
||||
logger.info(Thread.currentThread().getName() + " wait on stack empty");
|
||||
stackEmptyCondition.await();
|
||||
}
|
||||
return stack.pop();
|
||||
} finally {
|
||||
stackFullCondition.signalAll();
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
final int threadCount = 2;
|
||||
ReentrantLockWithCondition object = new ReentrantLockWithCondition();
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
service.execute(() -> {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
try {
|
||||
object.pushToStack("Item " + i);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
service.execute(() -> {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
try {
|
||||
logger.info("Item popped " + object.popFromStack());
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
service.shutdown();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,92 @@
|
|||
package com.baeldung.concurrent.locks;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import static java.lang.Thread.sleep;
|
||||
|
||||
public class SharedObjectWithLock {
|
||||
|
||||
Logger logger = LoggerFactory.getLogger(SharedObjectWithLock.class);
|
||||
|
||||
ReentrantLock lock = new ReentrantLock(true);
|
||||
|
||||
int counter = 0;
|
||||
|
||||
public void perform() {
|
||||
|
||||
lock.lock();
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
||||
try {
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
|
||||
counter++;
|
||||
} catch (Exception exception) {
|
||||
logger.error(" Interrupted Exception ", exception);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
||||
}
|
||||
}
|
||||
|
||||
public void performTryLock() {
|
||||
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock");
|
||||
try {
|
||||
boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS);
|
||||
if (isLockAcquired) {
|
||||
try {
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
||||
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
|
||||
sleep(1000);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
||||
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException exception) {
|
||||
logger.error(" Interrupted Exception ", exception);
|
||||
}
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock");
|
||||
}
|
||||
|
||||
public ReentrantLock getLock() {
|
||||
return lock;
|
||||
}
|
||||
|
||||
boolean isLocked() {
|
||||
return lock.isLocked();
|
||||
}
|
||||
|
||||
boolean hasQueuedThreads() {
|
||||
return lock.hasQueuedThreads();
|
||||
}
|
||||
|
||||
int getCounter() {
|
||||
return counter;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
final int threadCount = 2;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
|
||||
service.execute(() -> {
|
||||
object.perform();
|
||||
});
|
||||
service.execute(() -> {
|
||||
object.performTryLock();
|
||||
});
|
||||
|
||||
service.shutdown();
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,104 @@
|
|||
package com.baeldung.concurrent.locks;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.locks.StampedLock;
|
||||
|
||||
import static java.lang.Thread.sleep;
|
||||
|
||||
public class StampedLockDemo {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
Logger logger = LoggerFactory.getLogger(StampedLockDemo.class);
|
||||
|
||||
private final StampedLock lock = new StampedLock();
|
||||
|
||||
public void put(String key, String value) throws InterruptedException {
|
||||
long stamp = lock.writeLock();
|
||||
|
||||
try {
|
||||
logger.info(Thread.currentThread().getName() + " acquired the write lock with stamp " + stamp);
|
||||
map.put(key, value);
|
||||
} finally {
|
||||
lock.unlockWrite(stamp);
|
||||
logger.info(Thread.currentThread().getName() + " unlocked the write lock with stamp " + stamp);
|
||||
}
|
||||
}
|
||||
|
||||
public String get(String key) throws InterruptedException {
|
||||
long stamp = lock.readLock();
|
||||
logger.info(Thread.currentThread().getName() + " acquired the read lock with stamp " + stamp);
|
||||
try {
|
||||
sleep(5000);
|
||||
return map.get(key);
|
||||
|
||||
} finally {
|
||||
lock.unlockRead(stamp);
|
||||
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public String readWithOptimisticLock(String key) throws InterruptedException {
|
||||
long stamp = lock.tryOptimisticRead();
|
||||
String value = map.get(key);
|
||||
|
||||
if (!lock.validate(stamp)) {
|
||||
stamp = lock.readLock();
|
||||
try {
|
||||
sleep(5000);
|
||||
return map.get(key);
|
||||
|
||||
} finally {
|
||||
lock.unlock(stamp);
|
||||
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
|
||||
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
final int threadCount = 4;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
StampedLockDemo object = new StampedLockDemo();
|
||||
|
||||
Runnable writeTask = () -> {
|
||||
|
||||
try {
|
||||
object.put("key1", "value1");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
};
|
||||
Runnable readTask = () -> {
|
||||
|
||||
try {
|
||||
object.get("key1");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
};
|
||||
Runnable readOptimisticTask = () -> {
|
||||
|
||||
try {
|
||||
object.readWithOptimisticLock("key1");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
};
|
||||
service.submit(writeTask);
|
||||
service.submit(writeTask);
|
||||
service.submit(readTask);
|
||||
service.submit(readOptimisticTask);
|
||||
|
||||
service.shutdown();
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,120 @@
|
|||
package com.baeldung.concurrent.locks;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReadWriteLock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
|
||||
import static java.lang.Thread.sleep;
|
||||
|
||||
public class SynchronizedHashMapWithRWLock {
|
||||
|
||||
static Map<String, String> syncHashMap = new HashMap<>();
|
||||
Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class);
|
||||
|
||||
private final ReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
private final Lock readLock = lock.readLock();
|
||||
private final Lock writeLock = lock.writeLock();
|
||||
|
||||
public void put(String key, String value) throws InterruptedException {
|
||||
|
||||
try {
|
||||
writeLock.lock();
|
||||
logger.info(Thread.currentThread().getName() + " writing");
|
||||
syncHashMap.put(key, value);
|
||||
sleep(1000);
|
||||
} finally {
|
||||
writeLock.unlock();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public String get(String key) {
|
||||
try {
|
||||
readLock.lock();
|
||||
logger.info(Thread.currentThread().getName() + " reading");
|
||||
return syncHashMap.get(key);
|
||||
} finally {
|
||||
readLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public String remove(String key) {
|
||||
try {
|
||||
writeLock.lock();
|
||||
return syncHashMap.remove(key);
|
||||
} finally {
|
||||
writeLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean containsKey(String key) {
|
||||
try {
|
||||
readLock.lock();
|
||||
return syncHashMap.containsKey(key);
|
||||
} finally {
|
||||
readLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
boolean isReadLockAvailable() {
|
||||
return readLock.tryLock();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
|
||||
final int threadCount = 3;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
|
||||
|
||||
service.execute(new Thread(new Writer(object), "Writer"));
|
||||
service.execute(new Thread(new Reader(object), "Reader1"));
|
||||
service.execute(new Thread(new Reader(object), "Reader2"));
|
||||
|
||||
service.shutdown();
|
||||
}
|
||||
|
||||
private static class Reader implements Runnable {
|
||||
|
||||
SynchronizedHashMapWithRWLock object;
|
||||
|
||||
public Reader(SynchronizedHashMapWithRWLock object) {
|
||||
this.object = object;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
object.get("key" + i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class Writer implements Runnable {
|
||||
|
||||
SynchronizedHashMapWithRWLock object;
|
||||
|
||||
public Writer(SynchronizedHashMapWithRWLock object) {
|
||||
this.object = object;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
try {
|
||||
object.put("key" + i, "value" + i);
|
||||
sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.list.listoflist;
|
||||
|
||||
public class Pen implements Stationery {
|
||||
|
||||
public String name;
|
||||
|
||||
public Pen(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.list.listoflist;
|
||||
|
||||
public class Pencil implements Stationery{
|
||||
|
||||
public String name;
|
||||
|
||||
public Pencil(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.list.listoflist;
|
||||
|
||||
public class Rubber implements Stationery {
|
||||
|
||||
public String name;
|
||||
|
||||
public Rubber(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.list.listoflist;
|
||||
|
||||
public interface Stationery {
|
||||
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.algorithms;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
|
||||
|
||||
public class AntColonyOptimizationTest {
|
||||
|
||||
@Test
|
||||
public void testGenerateRandomMatrix() {
|
||||
AntColonyOptimization antTSP = new AntColonyOptimization(5);
|
||||
Assert.assertNotNull(antTSP.generateRandomMatrix(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStartAntOptimization() {
|
||||
AntColonyOptimization antTSP = new AntColonyOptimization(5);
|
||||
Assert.assertNotNull(antTSP.startAntOptimization());
|
||||
}
|
||||
|
||||
}
|
|
@ -3,7 +3,7 @@ package com.baeldung.algorithms;
|
|||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.annealing.SimulatedAnnealing;
|
||||
import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
|
||||
|
||||
public class SimulatedAnnealingTest {
|
||||
|
||||
|
|
|
@ -0,0 +1,75 @@
|
|||
package com.baeldung.concurrent.locks;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class SharedObjectWithLockManualTest {
|
||||
|
||||
@Test
|
||||
public void whenLockAcquired_ThenLockedIsTrue() {
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
|
||||
final int threadCount = 2;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
|
||||
executeThreads(object, threadCount, service);
|
||||
|
||||
assertEquals(true, object.isLocked());
|
||||
|
||||
service.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLocked_ThenQueuedThread() {
|
||||
final int threadCount = 4;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
|
||||
executeThreads(object, threadCount, service);
|
||||
|
||||
assertEquals(object.hasQueuedThreads(), true);
|
||||
|
||||
service.shutdown();
|
||||
|
||||
}
|
||||
|
||||
public void whenTryLock_ThenQueuedThread() {
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
|
||||
final int threadCount = 2;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
|
||||
executeThreads(object, threadCount, service);
|
||||
|
||||
assertEquals(true, object.isLocked());
|
||||
|
||||
service.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetCount_ThenCorrectCount() throws InterruptedException {
|
||||
final int threadCount = 4;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
|
||||
executeThreads(object, threadCount, service);
|
||||
Thread.sleep(1000);
|
||||
assertEquals(object.getCounter(), 4);
|
||||
|
||||
service.shutdown();
|
||||
|
||||
}
|
||||
|
||||
private void executeThreads(SharedObjectWithLock object, int threadCount, ExecutorService service) {
|
||||
for (int i = 0; i < threadCount; i++) {
|
||||
service.execute(() -> {
|
||||
object.perform();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
package com.baeldung.concurrent.locks;
|
||||
|
||||
import jdk.nashorn.internal.ir.annotations.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class SynchronizedHashMapWithRWLockManualTest {
|
||||
|
||||
@Test
|
||||
public void whenWriting_ThenNoReading() {
|
||||
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
|
||||
final int threadCount = 3;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
|
||||
executeWriterThreads(object, threadCount, service);
|
||||
|
||||
assertEquals(object.isReadLockAvailable(), false);
|
||||
|
||||
service.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReading_ThenMultipleReadingAllowed() {
|
||||
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
|
||||
final int threadCount = 5;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
|
||||
executeReaderThreads(object, threadCount, service);
|
||||
|
||||
assertEquals(object.isReadLockAvailable(), true);
|
||||
|
||||
service.shutdown();
|
||||
}
|
||||
|
||||
private void executeWriterThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
|
||||
for (int i = 0; i < threadCount; i++) {
|
||||
service.execute(() -> {
|
||||
try {
|
||||
object.put("key" + threadCount, "value" + threadCount);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void executeReaderThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
|
||||
for (int i = 0; i < threadCount; i++)
|
||||
service.execute(() -> {
|
||||
object.get("key" + threadCount);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
|
@ -1,2 +0,0 @@
|
|||
### Relevant Articles:
|
||||
- [The Java HashMap Under the Hood](http://www.baeldung.com/java-hashmap)
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.test.comparison;
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
|
@ -15,7 +15,7 @@ public class DivisibilityTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void givenNumber_whenDivisiblebyTwo_thenCorrect() {
|
||||
public void givenNumber_whenDivisibleByTwo_thenCorrect() {
|
||||
assertEquals(number % 2, 0);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.Parameterized;
|
||||
import org.junit.runners.Parameterized.Parameters;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
@RunWith(value = Parameterized.class)
|
||||
public class ParametrizedTests {
|
||||
|
||||
private int value;
|
||||
private boolean isEven;
|
||||
|
||||
public ParametrizedTests(int value, boolean isEven) {
|
||||
this.value = value;
|
||||
this.isEven = isEven;
|
||||
}
|
||||
|
||||
@Parameters
|
||||
public static Collection<Object[]> data() {
|
||||
Object[][] data = new Object[][]{{1, false}, {2, true}, {4, true}};
|
||||
return Arrays.asList(data);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParametrizedNumber_ifEvenCheckOK_thenCorrect() {
|
||||
Assert.assertEquals(isEven, value % 2 == 0);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
|
||||
public class RegistrationTest {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationTest.class);
|
||||
|
||||
@Test
|
||||
public void whenCalledFromSuite_thanOK() {
|
||||
LOGGER.info("Registration successful");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class SignInTest {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(SignInTest.class);
|
||||
|
||||
@Test
|
||||
public void whenCalledFromSuite_thanOK() {
|
||||
LOGGER.info("SignIn successful");
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.test.comparison;
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
|
@ -1,10 +1,10 @@
|
|||
package com.baeldung.test.comparison;
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.Suite;
|
||||
|
||||
@RunWith(Suite.class)
|
||||
@Suite.SuiteClasses({ StringCaseTest.class, DivisibilityTest.class })
|
||||
@Suite.SuiteClasses({ RegistrationTest.class, SignInTest.class })
|
||||
public class SuiteTest {
|
||||
|
||||
}
|
|
@ -1,8 +1,4 @@
|
|||
package com.baeldung.test.comparison;
|
||||
|
||||
import java.security.Security;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
|
@ -12,6 +8,9 @@ import org.junit.BeforeClass;
|
|||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class SummationServiceTest {
|
||||
private static List<Integer> numbers;
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
package com.baeldung.list.listoflist;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ListOfListsTest {
|
||||
|
||||
private List<ArrayList<? extends Stationery>> listOfLists = new ArrayList<ArrayList<? extends Stationery>>();
|
||||
private ArrayList<Pen> penList = new ArrayList<>();
|
||||
private ArrayList<Pencil> pencilList = new ArrayList<>();
|
||||
private ArrayList<Rubber> rubberList = new ArrayList<>();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Before
|
||||
public void init() {
|
||||
listOfLists.add(penList);
|
||||
listOfLists.add(pencilList);
|
||||
listOfLists.add(rubberList);
|
||||
|
||||
((ArrayList<Pen>) listOfLists.get(0)).add(new Pen("Pen 1"));
|
||||
((ArrayList<Pencil>) listOfLists.get(1)).add(new Pencil("Pencil 1"));
|
||||
((ArrayList<Rubber>) listOfLists.get(2)).add(new Rubber("Rubber 1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfLists_thenCheckNames() {
|
||||
assertEquals("Pen 1", ((Pen) listOfLists.get(0)
|
||||
.get(0)).getName());
|
||||
assertEquals("Pencil 1", ((Pencil) listOfLists.get(1)
|
||||
.get(0)).getName());
|
||||
assertEquals("Rubber 1", ((Rubber) listOfLists.get(2)
|
||||
.get(0)).getName());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void givenListOfLists_whenRemovingElements_thenCheckNames() {
|
||||
((ArrayList<Pencil>) listOfLists.get(1)).remove(0);
|
||||
listOfLists.remove(1);
|
||||
assertEquals("Rubber 1", ((Rubber) listOfLists.get(1)
|
||||
.get(0)).getName());
|
||||
listOfLists.remove(0);
|
||||
assertEquals("Rubber 1", ((Rubber) listOfLists.get(0)
|
||||
.get(0)).getName());
|
||||
}
|
||||
}
|
|
@ -12,7 +12,7 @@ import com.baeldung.string.JoinerSplitter;
|
|||
public class JoinerSplitterTest {
|
||||
|
||||
@Test
|
||||
public void givenArray_transformedToStream_convertToString() {
|
||||
public void provided_array_convert_to_stream_and_convert_to_string() {
|
||||
|
||||
String[] programming_languages = {"java", "python", "nodejs", "ruby"};
|
||||
|
||||
|
@ -24,6 +24,7 @@ public class JoinerSplitterTest {
|
|||
|
||||
@Test
|
||||
public void givenArray_transformedToStream_convertToPrefixPostfixString() {
|
||||
|
||||
String[] programming_languages = {"java", "python",
|
||||
"nodejs", "ruby"};
|
||||
String expectation = "[java,python,nodejs,ruby]";
|
||||
|
@ -34,6 +35,7 @@ public class JoinerSplitterTest {
|
|||
|
||||
@Test
|
||||
public void givenString_transformedToStream_convertToList() {
|
||||
|
||||
String programming_languages = "java,python,nodejs,ruby";
|
||||
|
||||
List<String> expectation = new ArrayList<String>();
|
||||
|
@ -49,6 +51,7 @@ public class JoinerSplitterTest {
|
|||
|
||||
@Test
|
||||
public void givenString_transformedToStream_convertToListOfChar() {
|
||||
|
||||
String programming_languages = "java,python,nodejs,ruby";
|
||||
|
||||
List<Character> expectation = new ArrayList<Character>();
|
||||
|
|
|
@ -1,46 +0,0 @@
|
|||
package com.baeldung.test.comparison;
|
||||
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
public class DependentTests {
|
||||
|
||||
private EmailValidator emailValidator;
|
||||
private LoginValidator loginValidator;
|
||||
private String validEmail = "abc@qwe.com";
|
||||
|
||||
@BeforeClass
|
||||
public void setup() {
|
||||
emailValidator = new EmailValidator();
|
||||
loginValidator = new LoginValidator();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmail_ifValid_thenTrue() {
|
||||
boolean valid = emailValidator.validate(validEmail);
|
||||
Assert.assertEquals(valid, true);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = { "givenEmail_ifValid_thenTrue" })
|
||||
public void givenValidEmail_whenLoggedin_thenTrue() {
|
||||
boolean valid = loginValidator.validate();
|
||||
Assert.assertEquals(valid, true);
|
||||
}
|
||||
}
|
||||
|
||||
class EmailValidator {
|
||||
|
||||
public boolean validate(String validEmail) {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class LoginValidator {
|
||||
|
||||
public boolean validate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,49 +0,0 @@
|
|||
package com.baeldung.test.comparison;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.Parameterized;
|
||||
import org.junit.runners.Parameterized.Parameters;
|
||||
|
||||
@RunWith(value = Parameterized.class)
|
||||
public class MyParameterisedUnitTest {
|
||||
|
||||
private String name;
|
||||
private NameCheck nameCheck;
|
||||
|
||||
@Before
|
||||
public void initialSetup() {
|
||||
nameCheck = new NameCheck();
|
||||
}
|
||||
|
||||
public MyParameterisedUnitTest(String myName) {
|
||||
this.name = myName;
|
||||
}
|
||||
|
||||
@Parameters
|
||||
public static Collection<Object[]> data() {
|
||||
Object[][] data = new Object[][] { { "Peter" }, { "Sam" }, { "Tim" }, { "Lucy" } };
|
||||
return Arrays.asList(data);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenValidLength_thenTrue() {
|
||||
boolean valid = nameCheck.nameCheck(name);
|
||||
Assert.assertEquals(valid, true);
|
||||
}
|
||||
}
|
||||
|
||||
class NameCheck {
|
||||
|
||||
public boolean nameCheck(String name) {
|
||||
if (name.length() > 0)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,81 +0,0 @@
|
|||
package com.baeldung.test.comparison;
|
||||
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.DataProvider;
|
||||
import org.testng.annotations.Parameters;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
public class MyParameterisedUnitTestNg {
|
||||
|
||||
private PrimeNumberCheck primeNumberChecker;
|
||||
|
||||
@BeforeClass
|
||||
public void intialSetup() {
|
||||
primeNumberChecker = new PrimeNumberCheck();
|
||||
}
|
||||
|
||||
@Test(enabled = false)
|
||||
@Parameters({ "num", "expectedResult" })
|
||||
public void givenNumber_ifPrime_thenCorrect(int number, boolean expectedResult) {
|
||||
Assert.assertEquals(expectedResult, primeNumberChecker.validate(number));
|
||||
}
|
||||
|
||||
@DataProvider(name = "test1")
|
||||
public static Object[][] primeNumbers() {
|
||||
return new Object[][] { { 2, true }, { 6, false }, { 19, true }, { 22, false }, { 23, true } };
|
||||
}
|
||||
|
||||
@Test(dataProvider = "test1")
|
||||
public void givenNumber_whenPrime_thenCorrect(Integer inputNumber, Boolean expectedResult) {
|
||||
Assert.assertEquals(expectedResult, primeNumberChecker.validate(inputNumber));
|
||||
}
|
||||
|
||||
@Test(dataProvider = "myDataProvider")
|
||||
public void parameterCheckTest(User user) {
|
||||
Assert.assertEquals("sam", user.getName());
|
||||
Assert.assertEquals(12, user.getAge());
|
||||
}
|
||||
|
||||
@DataProvider(name = "myDataProvider")
|
||||
public Object[][] parameterProvider() {
|
||||
User usr = new User();
|
||||
usr.setName("sam");
|
||||
usr.setAge(12);
|
||||
return new Object[][] { { usr } };
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class PrimeNumberCheck {
|
||||
|
||||
public Object validate(int number) {
|
||||
for (int i = 2; i < number; i++) {
|
||||
if (number % i == 0)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class User {
|
||||
private String name;
|
||||
private int age;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
}
|
|
@ -1,11 +0,0 @@
|
|||
package com.baeldung.test.comparison;
|
||||
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
public class RegistrationTest {
|
||||
|
||||
@Test
|
||||
public void givenEmail_ifValid_thenCorrect() {
|
||||
|
||||
}
|
||||
}
|
|
@ -1,12 +0,0 @@
|
|||
package com.baeldung.test.comparison;
|
||||
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
public class SignInTest {
|
||||
|
||||
@Test
|
||||
public void givenUsername_ifValid_thenCorrect() {
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -1,10 +0,0 @@
|
|||
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
|
||||
<suite name="My test suite">
|
||||
<test name="testing">
|
||||
<parameter name="num" value="2"/>
|
||||
<parameter name="expectedResult" value="true"/>
|
||||
<classes>
|
||||
<class name="com.baeldung.test.comparison.MyParameterisedUnitTestNg"/>
|
||||
</classes>
|
||||
</test>
|
||||
</suite>
|
|
@ -1,13 +0,0 @@
|
|||
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
|
||||
<suite name="regression_test">
|
||||
<test name="testing">
|
||||
<groups>
|
||||
<run>
|
||||
<include name="sanity" />
|
||||
</run>
|
||||
</groups>
|
||||
<classes>
|
||||
<class name="com.baeldung.test.comparison.SummationServiceTestTestNg" />
|
||||
</classes>
|
||||
</test>
|
||||
</suite>
|
|
@ -1,9 +0,0 @@
|
|||
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
|
||||
<suite name="Evaluation_Suite">
|
||||
<test name="Sanity">
|
||||
<classes>
|
||||
<class name="com.baeldung.test.comparison.RegistrationTest" />
|
||||
<class name="com.baeldung.test.comparison.SignInTest" />
|
||||
</classes>
|
||||
</test>
|
||||
</suite>
|
|
@ -4,6 +4,7 @@
|
|||
- [Introduction to Couchbase SDK for Java](http://www.baeldung.com/java-couchbase-sdk)
|
||||
- [Using Couchbase in a Spring Application](http://www.baeldung.com/couchbase-sdk-spring)
|
||||
- [Asynchronous Batch Opereations in Couchbase](http://www.baeldung.com/async-batch-operations-in-couchbase)
|
||||
- [Querying Couchbase with MapReduce Views](http://www.baeldung.com/couchbase-query-mapreduce-view)
|
||||
|
||||
### Overview
|
||||
This Maven project contains the Java code for the Couchbase entities and Spring services
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant articles:
|
||||
|
||||
- [Concurrency with LMAX Disruptor – An Introduction](http://www.baeldung.com/lmax-disruptor-concurrency)
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant articles:
|
||||
|
||||
- [Guide to EJB Set-up](http://www.baeldung.com/ejb-intro)
|
|
@ -16,3 +16,11 @@
|
|||
- [Guava – Sets](http://www.baeldung.com/guava-sets)
|
||||
- [Guava – Maps](http://www.baeldung.com/guava-maps)
|
||||
- [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial)
|
||||
- [Guide to Guava’s Ordering](http://www.baeldung.com/guava-ordering)
|
||||
- [Guide to Guava’s PreConditions](http://www.baeldung.com/guava-preconditions)
|
||||
- [Introduction to Guava CacheLoader](http://www.baeldung.com/guava-cacheloader)
|
||||
- [Guide to Guava’s EventBus](http://www.baeldung.com/guava-eventbus)
|
||||
- [Guide to Guava Multimap](http://www.baeldung.com/guava-multimap)
|
||||
- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset)
|
||||
- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap)
|
||||
- [Guide to Guava Table](http://www.baeldung.com/guava-table)
|
||||
|
|
|
@ -19,3 +19,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
|||
- [Multipart Upload with HttpClient 4](http://www.baeldung.com/httpclient-multipart-upload)
|
||||
- [HttpAsyncClient Tutorial](http://www.baeldung.com/httpasyncclient-tutorial)
|
||||
- [HttpClient 4 Tutorial](http://www.baeldung.com/httpclient-guide)
|
||||
- [Advanced HttpClient Configuration](http://www.baeldung.com/httpclient-advanced-config)
|
||||
|
|
|
@ -25,3 +25,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
|||
- [More Jackson Annotations](http://www.baeldung.com/jackson-advanced-annotations)
|
||||
- [Inheritance with Jackson](http://www.baeldung.com/jackson-inheritance)
|
||||
- [Guide to @JsonFormat in Jackson](http://www.baeldung.com/jackson-jsonformat)
|
||||
- [A Guide to Optional with Jackson](http://www.baeldung.com/jackson-optional)
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant articles:
|
||||
|
||||
- [A Guide to MongoDB with Java](http://www.baeldung.com/java-mongodb)
|
|
@ -1,2 +1,4 @@
|
|||
### Relevant Articles:
|
||||
- [Introduction to Javaslang](http://www.baeldung.com/javaslang)
|
||||
- [Guide to Try in Javaslang](http://www.baeldung.com/javaslang-try)
|
||||
- [Guide to Pattern Matching in Javaslang](http://www.baeldung.com/javaslang-pattern-matching)
|
||||
|
|
|
@ -1,2 +1,3 @@
|
|||
### Relevant Articles:
|
||||
- [Scheduling in Java EE](http://www.baeldung.com/scheduling-in-java-enterprise-edition)
|
||||
- [JSON Processing in Java EE 7](http://www.baeldung.com/jee7-json)
|
||||
|
|
|
@ -0,0 +1,57 @@
|
|||
package com.baeldung.javaeeannotations;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
import javax.servlet.ServletConfig;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.HttpConstraint;
|
||||
import javax.servlet.annotation.HttpMethodConstraint;
|
||||
import javax.servlet.annotation.ServletSecurity;
|
||||
import javax.servlet.annotation.WebInitParam;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
@WebServlet(
|
||||
name = "BankAccountServlet",
|
||||
description = "Represents a Bank Account and it's transactions",
|
||||
urlPatterns = {"/account", "/bankAccount" },
|
||||
initParams = { @WebInitParam(name = "type", value = "savings") }
|
||||
)
|
||||
@ServletSecurity(
|
||||
value = @HttpConstraint(rolesAllowed = {"admin"}),
|
||||
httpMethodConstraints = {@HttpMethodConstraint(value = "POST", rolesAllowed = {"admin"})}
|
||||
)
|
||||
public class AccountServlet extends javax.servlet.http.HttpServlet {
|
||||
|
||||
String accountType = null;
|
||||
|
||||
@Override
|
||||
public void init(ServletConfig config) throws ServletException {
|
||||
accountType = config.getInitParameter("type");
|
||||
}
|
||||
|
||||
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
PrintWriter writer = response.getWriter();
|
||||
writer.println("<html>Hello, I am an AccountServlet!</html>");
|
||||
writer.flush();
|
||||
}
|
||||
|
||||
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
double accountBalance = 1000d;
|
||||
double interestRate = Double.parseDouble(request.getAttribute("interest").toString());
|
||||
|
||||
String paramDepositAmt = request.getParameter("dep");
|
||||
double depositAmt = Double.parseDouble(paramDepositAmt);
|
||||
|
||||
accountBalance = accountBalance + depositAmt;
|
||||
|
||||
PrintWriter writer = response.getWriter();
|
||||
writer.println("<html> Balance of " + accountType + " account is: " +
|
||||
accountBalance + "<br> This account bares an interest rate of " + interestRate +
|
||||
" % </html>");
|
||||
writer.flush();
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.javaeeannotations;
|
||||
|
||||
import javax.servlet.ServletContextEvent;
|
||||
import javax.servlet.ServletContextListener;
|
||||
import javax.servlet.annotation.WebListener;
|
||||
|
||||
@WebListener
|
||||
public class BankAppServletContextListener implements ServletContextListener {
|
||||
|
||||
public void contextInitialized(ServletContextEvent sce) {
|
||||
sce.getServletContext().setAttribute("ATTR_DEFAULT_LANGUAGE", "english");
|
||||
}
|
||||
|
||||
public void contextDestroyed(ServletContextEvent sce) {
|
||||
System.out.println("CONTEXT DESTROYED");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.javaeeannotations;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.FilterConfig;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.annotation.WebFilter;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
@WebFilter(
|
||||
urlPatterns = "/bankAccount/*",
|
||||
filterName = "LoggingFilter",
|
||||
description = "Filter all account transaction URLs"
|
||||
)
|
||||
public class LoggingFilter implements javax.servlet.Filter {
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
}
|
||||
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||
HttpServletRequest req = (HttpServletRequest) request;
|
||||
HttpServletResponse res = (HttpServletResponse) response;
|
||||
|
||||
res.sendRedirect(req.getContextPath() + "/login.jsp");
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.javaeeannotations;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.MultipartConfig;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.Part;
|
||||
|
||||
@WebServlet(urlPatterns = { "/uploadCustDocs" })
|
||||
@MultipartConfig(
|
||||
fileSizeThreshold = 1024 * 1024 * 20,
|
||||
maxFileSize = 1024 * 1024 * 20,
|
||||
maxRequestSize = 1024 * 1024 * 25,
|
||||
location = "D:/custDocs"
|
||||
)
|
||||
public class UploadCustomerDocumentsServlet extends HttpServlet {
|
||||
|
||||
protected void doPost(
|
||||
HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
for (Part part : request.getParts()) {
|
||||
part.write("myFile");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
|
||||
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
|
||||
|
||||
<login-config>
|
||||
<auth-method>BASIC</auth-method>
|
||||
<realm-name>default</realm-name>
|
||||
</login-config>
|
||||
|
||||
</web-app>
|
|
@ -0,0 +1,16 @@
|
|||
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||
pageEncoding="ISO-8859-1"%>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>My Account</title>
|
||||
</head>
|
||||
<body>
|
||||
<form action="account" method="post">
|
||||
Width: <input type="text" size="5" name="dep"/>
|
||||
|
||||
<input type="submit" value="Deposit" />
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,12 @@
|
|||
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||
pageEncoding="ISO-8859-1"%>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>Login</title>
|
||||
</head>
|
||||
<body>
|
||||
Login Here...
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,16 @@
|
|||
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||
pageEncoding="ISO-8859-1"%>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>Insert title here</title>
|
||||
</head>
|
||||
<body>
|
||||
<form action="uploadCustDocs" method="post" enctype="multipart/form-data">
|
||||
<input type="file" name="file" size="50" />
|
||||
<br />
|
||||
<input type="submit" value="Upload File" />
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,46 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>jooq</artifactId>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jooq</groupId>
|
||||
<artifactId>jool</artifactId>
|
||||
<version>${jool.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<jool.version>0.9.12</jool.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
</properties>
|
||||
|
||||
|
||||
</project>
|
|
@ -0,0 +1,243 @@
|
|||
package com.baeldung;
|
||||
|
||||
|
||||
import junit.framework.Assert;
|
||||
import org.jooq.lambda.Seq;
|
||||
import org.jooq.lambda.Unchecked;
|
||||
import org.jooq.lambda.function.Function1;
|
||||
import org.jooq.lambda.function.Function2;
|
||||
import org.jooq.lambda.tuple.Tuple;
|
||||
import org.jooq.lambda.tuple.Tuple2;
|
||||
import org.jooq.lambda.tuple.Tuple3;
|
||||
import org.jooq.lambda.tuple.Tuple4;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static junit.framework.Assert.assertTrue;
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
import static org.jooq.lambda.tuple.Tuple.tuple;
|
||||
|
||||
public class JOOLTest {
|
||||
@Test
|
||||
public void givenSeq_whenCheckContains_shouldReturnTrue() {
|
||||
List<Integer> concat = Seq.of(1, 2, 3).concat(Seq.of(4, 5, 6)).toList();
|
||||
|
||||
assertEquals(concat, Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
|
||||
|
||||
assertTrue(Seq.of(1, 2, 3, 4).contains(2));
|
||||
|
||||
|
||||
assertTrue(Seq.of(1, 2, 3, 4).containsAll(2, 3));
|
||||
|
||||
|
||||
assertTrue(Seq.of(1, 2, 3, 4).containsAny(2, 5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStreams_whenJoin_shouldHaveElementsFromTwoStreams() {
|
||||
//given
|
||||
Stream<Integer> left = Stream.of(1, 2, 4);
|
||||
Stream<Integer> right = Stream.of(1, 2, 3);
|
||||
|
||||
//when
|
||||
List<Integer> rightCollected = right.collect(Collectors.toList());
|
||||
List<Integer> collect = left.filter(rightCollected::contains).collect(Collectors.toList());
|
||||
|
||||
//then
|
||||
assertEquals(collect, Arrays.asList(1, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSeq_whenJoin_shouldHaveElementsFromBothSeq() {
|
||||
assertEquals(
|
||||
Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), (a, b) -> a == b).toList(),
|
||||
Arrays.asList(tuple(1, 1), tuple(2, 2))
|
||||
);
|
||||
|
||||
|
||||
assertEquals(
|
||||
Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), (a, b) -> a == b).toList(),
|
||||
Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null))
|
||||
);
|
||||
|
||||
assertEquals(
|
||||
Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), (a, b) -> a == b).toList(),
|
||||
Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3))
|
||||
);
|
||||
|
||||
assertEquals(
|
||||
Seq.of(1, 2).crossJoin(Seq.of("A", "B")).toList(),
|
||||
Arrays.asList(tuple(1, "A"), tuple(1, "B"), tuple(2, "A"), tuple(2, "B"))
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSeq_whenManipulateSeq_seqShouldHaveNewElementsInIt() {
|
||||
assertEquals(
|
||||
Seq.of(1, 2, 3).cycle().limit(9).toList(),
|
||||
Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3)
|
||||
);
|
||||
|
||||
assertEquals(
|
||||
Seq.of(1, 2, 3).duplicate().map((first, second) -> tuple(first.toList(), second.toList())),
|
||||
tuple(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3))
|
||||
);
|
||||
|
||||
assertEquals(
|
||||
Seq.of(1, 2, 3, 4).intersperse(0).toList(),
|
||||
Arrays.asList(1, 0, 2, 0, 3, 0, 4)
|
||||
);
|
||||
|
||||
assertEquals(
|
||||
Seq.of(1, 2, 3, 4, 5).shuffle().toList().size(),
|
||||
5
|
||||
);
|
||||
|
||||
assertEquals(
|
||||
Seq.of(1, 2, 3, 4).partition(i -> i > 2).map((first, second) -> tuple(first.toList(), second.toList())),
|
||||
tuple(Arrays.asList(3, 4), Arrays.asList(1, 2))
|
||||
|
||||
);
|
||||
|
||||
assertEquals(
|
||||
Seq.of(1, 2, 3, 4).reverse().toList(),
|
||||
Arrays.asList(4, 3, 2, 1)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSeq_whenGroupByAndFold_shouldReturnProperSeq() {
|
||||
|
||||
Map<Integer, List<Integer>> expectedAfterGroupBy = new HashMap<>();
|
||||
expectedAfterGroupBy.put(1, Arrays.asList(1, 3));
|
||||
expectedAfterGroupBy.put(0, Arrays.asList(2, 4));
|
||||
|
||||
assertEquals(
|
||||
Seq.of(1, 2, 3, 4).groupBy(i -> i % 2),
|
||||
expectedAfterGroupBy
|
||||
);
|
||||
|
||||
|
||||
assertEquals(
|
||||
Seq.of("a", "b", "c").foldLeft("!", (u, t) -> u + t),
|
||||
"!abc"
|
||||
);
|
||||
|
||||
|
||||
assertEquals(
|
||||
Seq.of("a", "b", "c").foldRight("!", (t, u) -> t + u),
|
||||
"abc!"
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSeq_whenUsingSeqWhile_shouldBehaveAsWhileLoop() {
|
||||
|
||||
assertEquals(
|
||||
Seq.of(1, 2, 3, 4, 5).skipWhile(i -> i < 3).toList(),
|
||||
Arrays.asList(3, 4, 5)
|
||||
);
|
||||
|
||||
assertEquals(
|
||||
Seq.of(1, 2, 3, 4, 5).skipUntil(i -> i == 3).toList(),
|
||||
Arrays.asList(3, 4, 5)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSeq_whenZip_shouldHaveZippedSeq() {
|
||||
|
||||
assertEquals(
|
||||
Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")).toList(),
|
||||
Arrays.asList(tuple(1, "a"), tuple(2, "b"), tuple(3, "c"))
|
||||
);
|
||||
|
||||
assertEquals(
|
||||
Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y).toList(),
|
||||
Arrays.asList("1:a", "2:b", "3:c")
|
||||
);
|
||||
|
||||
|
||||
assertEquals(
|
||||
Seq.of("a", "b", "c").zipWithIndex().toList(),
|
||||
Arrays.asList(tuple("a", 0L), tuple("b", 1L), tuple("c", 2L))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
public Integer methodThatThrowsChecked(String arg) throws Exception {
|
||||
return arg.length();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOperationThatThrowsCheckedException_whenExecuteAndNeedToWrapCheckedIntoUnchecked_shouldPass() {
|
||||
//when
|
||||
List<Integer> collect = Stream.of("a", "b", "c").map(elem -> {
|
||||
try {
|
||||
return methodThatThrowsChecked(elem);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}).collect(Collectors.toList());
|
||||
|
||||
//then
|
||||
assertEquals(
|
||||
collect,
|
||||
Arrays.asList(1, 1, 1)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenOperationThatThrowsCheckedException_whenExecuteUsingUncheckedFuction_shouldPass() {
|
||||
//when
|
||||
List<Integer> collect = Stream.of("a", "b", "c")
|
||||
.map(Unchecked.function(elem -> methodThatThrowsChecked(elem)))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
//then
|
||||
assertEquals(
|
||||
collect,
|
||||
Arrays.asList(1, 1, 1)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFunction_whenAppliedPartially_shouldAddNumberToPartialArgument() {
|
||||
//given
|
||||
Function2<Integer, Integer, Integer> addTwoNumbers = (v1, v2) -> v1 + v2;
|
||||
addTwoNumbers.toBiFunction();
|
||||
Function1<Integer, Integer> addToTwo = addTwoNumbers.applyPartially(2);
|
||||
|
||||
//when
|
||||
Integer result = addToTwo.apply(5);
|
||||
|
||||
//then
|
||||
assertEquals(result, (Integer) 7);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSeqOfTuples_whenTransformToLowerNumberOfTuples_shouldHaveProperResult() {
|
||||
//given
|
||||
Seq<Tuple3<String, String, Integer>> personDetails = Seq.of(tuple("michael", "similar", 49), tuple("jodie", "variable", 43));
|
||||
Tuple2<String, String> tuple = tuple("winter", "summer");
|
||||
|
||||
//when
|
||||
List<Tuple4<String, String, String, String>> result = personDetails.map(t -> t.limit2().concat(tuple)).toList();
|
||||
|
||||
//then
|
||||
assertEquals(
|
||||
result,
|
||||
Arrays.asList(tuple("michael", "similar", "winter", "summer"), tuple("jodie", "variable", "winter", "summer"))
|
||||
);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant articles:
|
||||
|
||||
- [Introduction to the Kotlin Language](http://www.baeldung.com/kotlin)
|
|
@ -0,0 +1,48 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>libraries</artifactId>
|
||||
<name>libraries</name>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
|
||||
<dependency>
|
||||
<groupId>cglib</groupId>
|
||||
<artifactId>cglib</artifactId>
|
||||
<version>${cglib.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<cglib.version>3.2.4</cglib.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
</properties>
|
||||
|
||||
|
||||
</project>
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.cglib.mixin;
|
||||
|
||||
public class Class1 implements Interface1 {
|
||||
@Override
|
||||
public String first() {
|
||||
return "first behaviour";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.cglib.mixin;
|
||||
|
||||
public class Class2 implements Interface2 {
|
||||
@Override
|
||||
public String second() {
|
||||
return "second behaviour";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.cglib.mixin;
|
||||
|
||||
public interface Interface1 {
|
||||
String first();
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.cglib.mixin;
|
||||
|
||||
public interface Interface2 {
|
||||
String second();
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package com.baeldung.cglib.mixin;
|
||||
|
||||
public interface MixinInterface extends Interface1, Interface2 {
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.cglib.proxy;
|
||||
|
||||
public class PersonService {
|
||||
public String sayHello(String name) {
|
||||
return "Hello " + name;
|
||||
}
|
||||
|
||||
public Integer lengthOfName(String name) {
|
||||
return name.length();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.cglib.proxy;
|
||||
|
||||
|
||||
import net.sf.cglib.beans.BeanGenerator;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class BeanGeneratorTest {
|
||||
|
||||
@Test
|
||||
public void givenBeanCreator_whenAddProperty_thenClassShouldHaveFieldValue() throws Exception {
|
||||
//given
|
||||
BeanGenerator beanGenerator = new BeanGenerator();
|
||||
|
||||
//when
|
||||
beanGenerator.addProperty("name", String.class);
|
||||
Object myBean = beanGenerator.create();
|
||||
Method setter = myBean
|
||||
.getClass()
|
||||
.getMethod("setName", String.class);
|
||||
setter.invoke(myBean, "some string value set by a cglib");
|
||||
|
||||
//then
|
||||
Method getter = myBean
|
||||
.getClass()
|
||||
.getMethod("getName");
|
||||
assertEquals("some string value set by a cglib", getter.invoke(myBean));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.cglib.proxy;
|
||||
|
||||
import com.baeldung.cglib.mixin.*;
|
||||
import net.sf.cglib.proxy.Mixin;
|
||||
import org.junit.Test;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class MixinTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoClasses_whenMixedIntoOne_thenMixinShouldHaveMethodsFromBothClasses() throws Exception {
|
||||
//when
|
||||
Mixin mixin = Mixin.create(
|
||||
new Class[]{Interface1.class, Interface2.class, MixinInterface.class},
|
||||
new Object[]{new Class1(), new Class2()}
|
||||
);
|
||||
MixinInterface mixinDelegate = (MixinInterface) mixin;
|
||||
|
||||
//then
|
||||
assertEquals("first behaviour", mixinDelegate.first());
|
||||
assertEquals("second behaviour", mixinDelegate.second());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
package com.baeldung.cglib.proxy;
|
||||
|
||||
import net.sf.cglib.proxy.Enhancer;
|
||||
import net.sf.cglib.proxy.FixedValue;
|
||||
import net.sf.cglib.proxy.MethodInterceptor;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ProxyTest {
|
||||
@Test
|
||||
public void givenPersonService_whenSayHello_thenReturnResult() {
|
||||
//given
|
||||
PersonService personService = new PersonService();
|
||||
|
||||
//when
|
||||
String res = personService.sayHello("Tom");
|
||||
|
||||
//then
|
||||
assertEquals(res, "Hello Tom");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEnhancerProxy_whenExtendPersonService_thenInterceptMethod() throws Exception {
|
||||
//given
|
||||
Enhancer enhancer = new Enhancer();
|
||||
enhancer.setSuperclass(PersonService.class);
|
||||
enhancer.setCallback((FixedValue) () -> "Hello Tom!");
|
||||
PersonService proxy = (PersonService) enhancer.create();
|
||||
|
||||
//when
|
||||
String res = proxy.sayHello(null);
|
||||
|
||||
//then
|
||||
assertEquals("Hello Tom!", res);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEnhancer_whenExecuteMethodOnProxy_thenInterceptOnlyStringReturnTypeMethod() throws Exception {
|
||||
//given
|
||||
Enhancer enhancer = new Enhancer();
|
||||
enhancer.setSuperclass(PersonService.class);
|
||||
enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> {
|
||||
if (method.getDeclaringClass() != Object.class && method.getReturnType() == String.class) {
|
||||
return "Hello Tom!";
|
||||
} else {
|
||||
return proxy.invokeSuper(obj, args);
|
||||
}
|
||||
});
|
||||
|
||||
//when
|
||||
PersonService proxy = (PersonService) enhancer.create();
|
||||
|
||||
//then
|
||||
assertEquals("Hello Tom!", proxy.sayHello(null));
|
||||
int lengthOfName = proxy.lengthOfName("Mary");
|
||||
assertEquals(4, lengthOfName);
|
||||
}
|
||||
|
||||
}
|
179
log4j2/pom.xml
179
log4j2/pom.xml
|
@ -1,105 +1,104 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>log4j2</artifactId>
|
||||
<artifactId>log4j2</artifactId>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>..</relativePath>
|
||||
</parent>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>..</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- This is the needed core component. -->
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>${log4j-core.version}</version>
|
||||
</dependency>
|
||||
<dependencies>
|
||||
<!-- This is the needed core component. -->
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>${log4j-core.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- This is used by JSONLayout. -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<!-- This is used by JSONLayout. -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- This is used by XMLLayout. -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-xml</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<!-- This is used by XMLLayout. -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-xml</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- This is used by JDBC Appender. -->
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-dbcp2</artifactId>
|
||||
<version>${commons-dbcp2.version}</version>
|
||||
</dependency>
|
||||
<!-- This is used by JDBC Appender. -->
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-dbcp2</artifactId>
|
||||
<version>${commons-dbcp2.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- This is used for testing only. -->
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>${log4j-core.version}</version>
|
||||
<type>test-jar</type>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<!-- This is used for testing only. -->
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>${log4j-core.version}</version>
|
||||
<type>test-jar</type>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<build>
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
<testFailureIgnore>true</testFailureIgnore>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
<testFailureIgnore>true</testFailureIgnore>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<jackson.version>2.8.5</jackson.version>
|
||||
<h2.version>1.4.193</h2.version>
|
||||
<commons-dbcp2.version>2.1.1</commons-dbcp2.version>
|
||||
<log4j-core.version>2.7</log4j-core.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
<properties>
|
||||
<jackson.version>2.8.5</jackson.version>
|
||||
<h2.version>1.4.193</h2.version>
|
||||
<commons-dbcp2.version>2.1.1</commons-dbcp2.version>
|
||||
<log4j-core.version>2.7</log4j-core.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -1,32 +0,0 @@
|
|||
package com.baeldung.logging.log4j2.tests;
|
||||
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.junit.LoggerContextRule;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class AsyncFileAppenderUsingJsonLayoutTest {
|
||||
@Rule
|
||||
public LoggerContextRule contextRule =
|
||||
new LoggerContextRule("log4j2-async-file-appender_json-layout.xml");
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithAsyncConfig_shouldLogToJsonFile()
|
||||
throws Exception {
|
||||
Logger logger = contextRule.getLogger(getClass().getSimpleName());
|
||||
final int count = 88;
|
||||
for (int i = 0; i < count; i++) {
|
||||
logger.info("This is async JSON message #{} at INFO level.", count);
|
||||
}
|
||||
long logEventsCount = Files.lines(Paths.get("target/logfile.json")).count();
|
||||
assertTrue(logEventsCount > 0 && logEventsCount <= count);
|
||||
}
|
||||
}
|
|
@ -1,21 +0,0 @@
|
|||
package com.baeldung.logging.log4j2.tests;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class ConsoleAppenderUsingDefaultLayoutTest {
|
||||
@Test
|
||||
public void givenLoggerWithDefaultConfig_shouldLogToConsole()
|
||||
throws Exception {
|
||||
Logger logger = LogManager.getLogger(getClass());
|
||||
Exception e = new RuntimeException("This is only a test!");
|
||||
logger.info("This is a simple message at INFO level. " +
|
||||
"It will be hidden.");
|
||||
logger.error("This is a simple message at ERROR level. " +
|
||||
"This is the minimum visible level.", e);
|
||||
}
|
||||
}
|
|
@ -1,51 +0,0 @@
|
|||
package com.baeldung.logging.log4j2.tests;
|
||||
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.Marker;
|
||||
import org.apache.logging.log4j.MarkerManager;
|
||||
import org.apache.logging.log4j.ThreadContext;
|
||||
import org.apache.logging.log4j.junit.LoggerContextRule;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class ConsoleAppenderUsingPatternLayoutWithColorsTest {
|
||||
@Rule
|
||||
public LoggerContextRule contextRule =
|
||||
new LoggerContextRule("log4j2-console-appender_pattern-layout.xml");
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithConsoleConfig_shouldLogToConsoleInColors()
|
||||
throws Exception {
|
||||
Logger logger = contextRule.getLogger(getClass().getSimpleName());
|
||||
logger.trace("This is a colored message at TRACE level.");
|
||||
logger.debug("This is a colored message at DEBUG level. " +
|
||||
"This is the minimum visible level.");
|
||||
logger.info("This is a colored message at INFO level.");
|
||||
logger.warn("This is a colored message at WARN level.");
|
||||
Exception e = new RuntimeException("This is only a test!");
|
||||
logger.error("This is a colored message at ERROR level.", e);
|
||||
logger.fatal("This is a colored message at FATAL level.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithConsoleConfig_shouldFilterByMarker() throws Exception {
|
||||
Logger logger = contextRule.getLogger("ConnTrace");
|
||||
Marker appError = MarkerManager.getMarker("APP_ERROR");
|
||||
logger.error(appError, "This marker message at ERROR level should be hidden.");
|
||||
Marker connectionTrace = MarkerManager.getMarker("CONN_TRACE");
|
||||
logger.trace(connectionTrace, "This is a marker message at TRACE level.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithConsoleConfig_shouldFilterByThreadContext() throws Exception {
|
||||
Logger logger = contextRule.getLogger("UserAudit");
|
||||
ThreadContext.put("userId", "1000");
|
||||
logger.info("This is a log-visible user login. Maybe from an admin account?");
|
||||
ThreadContext.put("userId", "1001");
|
||||
logger.info("This is a log-invisible user login.");
|
||||
boolean b = true;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,122 @@
|
|||
package com.baeldung.logging.log4j2.tests;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.Marker;
|
||||
import org.apache.logging.log4j.MarkerManager;
|
||||
import org.apache.logging.log4j.ThreadContext;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
import com.baeldung.logging.log4j2.tests.jdbc.ConnectionFactory;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class CustomLoggingTest {
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() throws Exception {
|
||||
Connection connection = ConnectionFactory.getConnection();
|
||||
connection.createStatement()
|
||||
.execute("CREATE TABLE logs(" + "when TIMESTAMP," + "logger VARCHAR(255)," + "level VARCHAR(255)," + "message VARCHAR(4096)," + "throwable TEXT)");
|
||||
connection.commit();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithDefaultConfig_shouldLogToConsole() throws Exception {
|
||||
Logger logger = LogManager.getLogger(getClass());
|
||||
Exception e = new RuntimeException("This is only a test!");
|
||||
logger.info("This is a simple message at INFO level. " + "It will be hidden.");
|
||||
logger.error("This is a simple message at ERROR level. " + "This is the minimum visible level.", e);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithConsoleConfig_shouldLogToConsoleInColors() throws Exception {
|
||||
Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_MARKER");
|
||||
logger.trace("This is a colored message at TRACE level.");
|
||||
logger.debug("This is a colored message at DEBUG level. " + "This is the minimum visible level.");
|
||||
logger.info("This is a colored message at INFO level.");
|
||||
logger.warn("This is a colored message at WARN level.");
|
||||
Exception e = new RuntimeException("This is only a test!");
|
||||
logger.error("This is a colored message at ERROR level.", e);
|
||||
logger.fatal("This is a colored message at FATAL level.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithConsoleConfig_shouldFilterByMarker() throws Exception {
|
||||
Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_MARKER");
|
||||
Marker appError = MarkerManager.getMarker("APP_ERROR");
|
||||
logger.error(appError, "This marker message at ERROR level should be hidden.");
|
||||
Marker connectionTrace = MarkerManager.getMarker("CONN_TRACE");
|
||||
logger.trace(connectionTrace, "This is a marker message at TRACE level.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithConsoleConfig_shouldFilterByThreadContext() throws Exception {
|
||||
Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_THREAD_CONTEXT");
|
||||
ThreadContext.put("userId", "1000");
|
||||
logger.info("This is a log-visible user login. Maybe from an admin account?");
|
||||
ThreadContext.put("userId", "1001");
|
||||
logger.info("This is a log-invisible user login.");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithAsyncConfig_shouldLogToJsonFile() throws Exception {
|
||||
Logger logger = LogManager.getLogger("ASYNC_JSON_FILE_APPENDER");
|
||||
final int count = 88;
|
||||
for (int i = 0; i < count; i++) {
|
||||
logger.info("This is async JSON message #{} at INFO level.", count);
|
||||
}
|
||||
long logEventsCount = Files.lines(Paths.get("target/logfile.json"))
|
||||
.count();
|
||||
assertTrue(logEventsCount > 0 && logEventsCount <= count);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithFailoverConfig_shouldLog() throws Exception {
|
||||
Logger logger = LogManager.getLogger("FAIL_OVER_SYSLOG_APPENDER");
|
||||
logger.trace("This is a syslog message at TRACE level.");
|
||||
logger.debug("This is a syslog message at DEBUG level.");
|
||||
logger.info("This is a syslog message at INFO level. This is the minimum visible level.");
|
||||
logger.warn("This is a syslog message at WARN level.");
|
||||
Exception e = new RuntimeException("This is only a test!");
|
||||
logger.error("This is a syslog message at ERROR level.", e);
|
||||
logger.fatal("This is a syslog message at FATAL level.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithJdbcConfig_shouldLogToDataSource() throws Exception {
|
||||
Logger logger = LogManager.getLogger("JDBC_APPENDER");
|
||||
final int count = 88;
|
||||
for (int i = 0; i < count; i++) {
|
||||
logger.info("This is JDBC message #{} at INFO level.", count);
|
||||
}
|
||||
Connection connection = ConnectionFactory.getConnection();
|
||||
ResultSet resultSet = connection.createStatement()
|
||||
.executeQuery("SELECT COUNT(*) AS ROW_COUNT FROM logs");
|
||||
int logCount = 0;
|
||||
if (resultSet.next()) {
|
||||
logCount = resultSet.getInt("ROW_COUNT");
|
||||
}
|
||||
assertTrue(logCount == count);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithRollingFileConfig_shouldLogToXMLFile() throws Exception {
|
||||
Logger logger = LogManager.getLogger("XML_ROLLING_FILE_APPENDER");
|
||||
final int count = 88;
|
||||
for (int i = 0; i < count; i++) {
|
||||
logger.info("This is rolling file XML message #{} at INFO level.", i);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,27 +0,0 @@
|
|||
package com.baeldung.logging.log4j2.tests;
|
||||
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.junit.LoggerContextRule;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class FailoverSyslogConsoleAppenderTest {
|
||||
@Rule
|
||||
public LoggerContextRule contextRule =
|
||||
new LoggerContextRule("log4j2-failover-syslog-console-appender_pattern-layout.xml");
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithFailoverConfig_shouldLog() throws Exception {
|
||||
Logger logger = contextRule.getLogger(getClass().getSimpleName());
|
||||
logger.trace("This is a syslog message at TRACE level.");
|
||||
logger.debug("This is a syslog message at DEBUG level.");
|
||||
logger.info("This is a syslog message at INFO level. This is the minimum visible level.");
|
||||
logger.warn("This is a syslog message at WARN level.");
|
||||
Exception e = new RuntimeException("This is only a test!");
|
||||
logger.error("This is a syslog message at ERROR level.", e);
|
||||
logger.fatal("This is a syslog message at FATAL level.");
|
||||
}
|
||||
}
|
|
@ -1,51 +0,0 @@
|
|||
package com.baeldung.logging.log4j2.tests;
|
||||
|
||||
import com.baeldung.logging.log4j2.tests.jdbc.ConnectionFactory;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.junit.LoggerContextRule;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class JDBCAppenderTest {
|
||||
@Rule
|
||||
public LoggerContextRule contextRule = new LoggerContextRule("log4j2-jdbc-appender.xml");
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() throws Exception {
|
||||
Connection connection = ConnectionFactory.getConnection();
|
||||
connection.createStatement()
|
||||
.execute("CREATE TABLE logs(" +
|
||||
"when TIMESTAMP," +
|
||||
"logger VARCHAR(255)," +
|
||||
"level VARCHAR(255)," +
|
||||
"message VARCHAR(4096)," +
|
||||
"throwable TEXT)");
|
||||
//connection.commit();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithJdbcConfig_shouldLogToDataSource() throws Exception {
|
||||
Logger logger = contextRule.getLogger(getClass().getSimpleName());
|
||||
final int count = 88;
|
||||
for (int i = 0; i < count; i++) {
|
||||
logger.info("This is JDBC message #{} at INFO level.", count);
|
||||
}
|
||||
Connection connection = ConnectionFactory.getConnection();
|
||||
ResultSet resultSet = connection.createStatement()
|
||||
.executeQuery("SELECT COUNT(*) AS ROW_COUNT FROM logs");
|
||||
int logCount = 0;
|
||||
if (resultSet.next()) {
|
||||
logCount = resultSet.getInt("ROW_COUNT");
|
||||
}
|
||||
assertTrue(logCount == count);
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue