Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
5e1842e848
@ -34,6 +34,11 @@
|
||||
<artifactId>jenetics</artifactId>
|
||||
<version>3.7.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jgrapht</groupId>
|
||||
<artifactId>jgrapht-core</artifactId>
|
||||
<version>1.0.1</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
1
atomix/.gitignore
vendored
Normal file
1
atomix/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
/target
|
46
atomix/pom.xml
Normal file
46
atomix/pom.xml
Normal file
@ -0,0 +1,46 @@
|
||||
<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.atomix.io</groupId>
|
||||
<artifactId>atomix</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.atomix</groupId>
|
||||
<artifactId>atomix-all</artifactId>
|
||||
<version>1.0.0-rc9</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.9</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>1.2.17</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.7.0</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
</project>
|
@ -0,0 +1,27 @@
|
||||
package com.atomix.example;
|
||||
|
||||
import io.atomix.AtomixReplica;
|
||||
import io.atomix.catalyst.transport.Address;
|
||||
import io.atomix.catalyst.transport.netty.NettyTransport;
|
||||
import io.atomix.copycat.server.storage.Storage;
|
||||
import io.atomix.copycat.server.storage.StorageLevel;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class BootstrapingCluster {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Storage storage = Storage.builder()
|
||||
.withDirectory(new File("log"))
|
||||
.withStorageLevel(StorageLevel.DISK)
|
||||
.build();
|
||||
AtomixReplica replica = AtomixReplica.builder(new Address("localhost", 8700))
|
||||
.withStorage(storage)
|
||||
.withTransport(new NettyTransport())
|
||||
.build();
|
||||
|
||||
CompletableFuture<AtomixReplica> completableFuture = replica.bootstrap();
|
||||
completableFuture.join();
|
||||
}
|
||||
}
|
71
atomix/src/main/java/com/atomix/example/OtherNodes.java
Normal file
71
atomix/src/main/java/com/atomix/example/OtherNodes.java
Normal file
@ -0,0 +1,71 @@
|
||||
package com.atomix.example;
|
||||
|
||||
import io.atomix.AtomixReplica;
|
||||
import io.atomix.catalyst.transport.Address;
|
||||
import io.atomix.catalyst.transport.netty.NettyTransport;
|
||||
import io.atomix.concurrent.DistributedLock;
|
||||
import io.atomix.copycat.server.storage.Storage;
|
||||
import io.atomix.copycat.server.storage.StorageLevel;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class OtherNodes {
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
List<Address> cluster = Arrays
|
||||
.asList(
|
||||
new Address("localhost", 8700),
|
||||
new Address("localhost", 8701),
|
||||
new Address("localhost", 8702));
|
||||
|
||||
Storage storage = Storage.builder()
|
||||
.withDirectory(new File("log"))
|
||||
.withStorageLevel(StorageLevel.DISK)
|
||||
.build();
|
||||
|
||||
AtomixReplica replica2 = AtomixReplica.builder(new Address("localhost", 8701))
|
||||
.withStorage(storage)
|
||||
.withTransport(new NettyTransport())
|
||||
.build();
|
||||
|
||||
WorkerThread WT1 = new WorkerThread(replica2, cluster);
|
||||
WT1.run();
|
||||
|
||||
AtomixReplica replica3 = AtomixReplica.builder(new Address("localhost", 8702))
|
||||
.withStorage(storage)
|
||||
.withTransport(new NettyTransport())
|
||||
.build();
|
||||
|
||||
WorkerThread WT2 = new WorkerThread(replica3, cluster);
|
||||
WT2.run();
|
||||
|
||||
Thread.sleep(6000);
|
||||
|
||||
DistributedLock lock = replica2.getLock("my-lock")
|
||||
.join();
|
||||
lock.lock()
|
||||
.thenRun(() -> System.out.println("Acquired a lock"));
|
||||
|
||||
replica2.getMap("map")
|
||||
.thenCompose(m -> m.put("bar", "Hello world!"))
|
||||
.thenRun(() -> System.out.println("Value is set in Distributed Map"))
|
||||
.join();
|
||||
}
|
||||
|
||||
private static class WorkerThread extends Thread {
|
||||
private AtomixReplica replica;
|
||||
private List<Address> cluster;
|
||||
|
||||
WorkerThread(AtomixReplica replica, List<Address> cluster) {
|
||||
this.replica = replica;
|
||||
this.cluster = cluster;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
replica.join(cluster)
|
||||
.join();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package com.atomix.exampletest;
|
||||
|
||||
import io.atomix.AtomixClient;
|
||||
import io.atomix.catalyst.transport.Address;
|
||||
import io.atomix.catalyst.transport.netty.NettyTransport;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class AtomixClientLiveTest {
|
||||
|
||||
private final AtomixClient client = AtomixClient.builder()
|
||||
.withTransport(new NettyTransport())
|
||||
.build();
|
||||
|
||||
@Test
|
||||
public void whenBootstrap_thenShouldGet() throws InterruptedException, ExecutionException {
|
||||
List<Address> cluster = Arrays.asList(
|
||||
new Address("localhost", 8700),
|
||||
new Address("localhsot", 8701));
|
||||
|
||||
String value = client.connect(cluster)
|
||||
.thenRun(() -> System.out.println("Client Connected"))
|
||||
.thenCompose(c -> client.getMap("map"))
|
||||
.thenCompose(m -> m.get("bar"))
|
||||
.thenApply(a -> (String) a)
|
||||
.get();
|
||||
|
||||
assertEquals("Hello world!", value);
|
||||
}
|
||||
}
|
@ -1,42 +0,0 @@
|
||||
<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.beanvalidation</groupId>
|
||||
<artifactId>beanvalidation</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>beanvalidation</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
<version>2.0.0.Final</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
<version>6.0.2.Final</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.el</groupId>
|
||||
<artifactId>javax.el-api</artifactId>
|
||||
<version>3.0.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.web</groupId>
|
||||
<artifactId>javax.el</artifactId>
|
||||
<version>2.2.4</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
@ -1,17 +0,0 @@
|
||||
package com.baeldung.beanvalidation.application;
|
||||
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import com.baeldung.beanvalidation.model.User;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main( String[] args ) {
|
||||
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
|
||||
User user = new User();
|
||||
user.setName("Mary");
|
||||
user.setEmail("no-email");
|
||||
user.setAge(36);
|
||||
validator.validate(user).stream().forEach(violation -> System.out.println(violation.getMessage()));
|
||||
}
|
||||
}
|
@ -1,13 +0,0 @@
|
||||
package com.baeldung.beanvalidation.container;
|
||||
|
||||
import java.util.Optional;
|
||||
import javax.validation.constraints.Positive;
|
||||
|
||||
public class IntegerContainer {
|
||||
|
||||
private Optional<@Positive(message = "Value must be a positive integer") Integer> container = Optional.empty();
|
||||
|
||||
public void addElement(int element) {
|
||||
container = Optional.of(element);
|
||||
}
|
||||
}
|
@ -1,14 +0,0 @@
|
||||
package com.baeldung.beanvalidation.container;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public class StringContainer {
|
||||
|
||||
private List<@NotNull String> container = new ArrayList<>();
|
||||
|
||||
public void addElement(String element) {
|
||||
container.add(element);
|
||||
}
|
||||
}
|
@ -1,48 +0,0 @@
|
||||
package com.baeldung.beanvalidation.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
import javax.validation.constraints.Max;
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
import org.hibernate.validator.constraints.Email;
|
||||
|
||||
public class User implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@NotNull(message = "Name cannot be null")
|
||||
@Size(min = 2, max = 32, message = "Name must be between 2 and 32 characters")
|
||||
private String name;
|
||||
|
||||
@Email(message = "Email must be a well-formed email address")
|
||||
private String email;
|
||||
|
||||
@Min(value = 1, message = "Age must not be lesser than 1")
|
||||
@Max(value = 99, message = "Age must not be greater than 99")
|
||||
private int age;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
}
|
@ -1,8 +0,0 @@
|
||||
package com.baeldung.beanvalidation.service;
|
||||
|
||||
public interface EntityService {
|
||||
|
||||
public String toString();
|
||||
|
||||
public void processEntity();
|
||||
}
|
@ -1,45 +0,0 @@
|
||||
package com.baeldung.beanvalidation.service;
|
||||
|
||||
import java.io.Serializable;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
import com.baeldung.beanvalidation.model.User;
|
||||
|
||||
public class UserService implements EntityService, Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Valid
|
||||
private User user;
|
||||
|
||||
@NotNull(message = "FileName cannot be null")
|
||||
@Size(min = 5, max = 10, message = "FileName must be between 5 and 10 characters")
|
||||
private String fileName;
|
||||
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public String getFileName() {
|
||||
return fileName;
|
||||
}
|
||||
|
||||
public void setFileName(String fileName) {
|
||||
this.fileName = fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processEntity() {
|
||||
// process the user here
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "UserService [user=" + user + ", fileName=" + fileName + "]";
|
||||
}
|
||||
}
|
@ -1,134 +0,0 @@
|
||||
package com.baeldung.beanvalidation;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import com.baeldung.beanvalidation.container.IntegerContainer;
|
||||
import com.baeldung.beanvalidation.container.StringContainer;
|
||||
import com.baeldung.beanvalidation.model.User;
|
||||
import com.baeldung.beanvalidation.service.UserService;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ValidationTest {
|
||||
|
||||
private static Validator validator;
|
||||
private static User user;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpHibernateValidatorInstance() {
|
||||
validator = Validation.buildDefaultValidatorFactory().getValidator();
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpUserInstance() {
|
||||
user = new User();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDownHibernateValidatorInstance() {
|
||||
validator = null;
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDownUserInstance() {
|
||||
user = null;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullName_whenValidated_thenMessageDescriptorForName() {
|
||||
user.setName(null);
|
||||
user.setEmail("mary@domain.com");
|
||||
user.setAge(36);
|
||||
assertEquals("Name cannot be null", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidEmail_whenValidated_thenMessageDescriptorforEmail() {
|
||||
user.setName("Mary");
|
||||
user.setEmail("no-email");
|
||||
user.setAge(36);
|
||||
assertEquals("Email must be a well-formed email address", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAgeLesserThanLowerBound_whenValidated_thenMessageDescriptorforAge() {
|
||||
user.setName("Mary");
|
||||
user.setEmail("mary@domain.com");
|
||||
user.setAge(0);
|
||||
assertEquals("Age must not be lesser than 1", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAgeGreaterThanUpperBound_whenValidated_thenMessageDescriptorforAge() {
|
||||
user.setName("Mary");
|
||||
user.setEmail("mary@domain.com");
|
||||
user.setAge(100);
|
||||
assertEquals("Age must not be greater than 99", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullFileName_whenValidated_thenMessageDescriptorforFileName() {
|
||||
user.setName("Mary");
|
||||
user.setEmail("mary@domain.com");
|
||||
user.setAge(36);
|
||||
UserService userService = new UserService();
|
||||
userService.setFileName(null);
|
||||
userService.setUser(user);
|
||||
assertEquals("FileName cannot be null", validator.validate(userService).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileNameShortherThanLowerBound_whenValidated_thenMessageDescriptorforFileName() {
|
||||
user.setName("Mary");
|
||||
user.setEmail("mary@domain.com");
|
||||
user.setAge(36);
|
||||
UserService userService = new UserService();
|
||||
userService.setFileName("");
|
||||
userService.setUser(user);
|
||||
assertEquals("FileName must be between 5 and 10 characters", validator.validate(userService).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileNameLongerThanUpperBound_whenValidated_thenMessageDescriptorforFileName() {
|
||||
user.setName("Mary");
|
||||
user.setEmail("mary@domain.com");
|
||||
user.setAge(36);
|
||||
UserService userService = new UserService();
|
||||
userService.setFileName("waytoolongfilename");
|
||||
userService.setUser(user);
|
||||
assertEquals("FileName must be between 5 and 10 characters", validator.validate(userService).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullUserAndNullFileName_whenValidated_thenTwoConstraintViolations() {
|
||||
user.setName(null);
|
||||
user.setEmail("mary@domain.com");
|
||||
user.setAge(36);
|
||||
UserService userService = new UserService();
|
||||
userService.setFileName(null);
|
||||
userService.setUser(user);
|
||||
Set<ConstraintViolation<UserService>> constraintViolations = validator.validate(userService);
|
||||
assertEquals(2, constraintViolations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullElement_whenValidated_thenOneConstraintViolation() {
|
||||
StringContainer container = new StringContainer();
|
||||
container.addElement(null);
|
||||
Set<ConstraintViolation<StringContainer>> constraintViolations = validator.validate(container);
|
||||
assertEquals(1, constraintViolations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNegativeInteger_whenValidated_thenOneConstraintViolation() {
|
||||
IntegerContainer container = new IntegerContainer();
|
||||
container.addElement(-1);
|
||||
Set<ConstraintViolation<IntegerContainer>> constraintViolations = validator.validate(container);
|
||||
assertEquals(1, constraintViolations.size());
|
||||
}
|
||||
}
|
@ -6,8 +6,8 @@
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<validation-api.version>1.1.0.Final</validation-api.version>
|
||||
<hibernate-validator.version>5.3.4.Final</hibernate-validator.version>
|
||||
<validation-api.version>2.0.0.Final</validation-api.version>
|
||||
<hibernate-validator.version>6.0.2.Final</hibernate-validator.version>
|
||||
<javax.el-api.version>3.0.0</javax.el-api.version>
|
||||
<javax.el.version>2.2.6</javax.el.version>
|
||||
</properties>
|
||||
|
66
javaxval/src/main/java/org/baeldung/Customer.java
Normal file
66
javaxval/src/main/java/org/baeldung/Customer.java
Normal file
@ -0,0 +1,66 @@
|
||||
package org.baeldung;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.PositiveOrZero;
|
||||
|
||||
public class Customer {
|
||||
|
||||
@NotBlank(message="Name cannot be empty")
|
||||
private String name;
|
||||
|
||||
private List<@NotBlank(message="Address must not be blank") String> addresses;
|
||||
|
||||
private Integer age;
|
||||
|
||||
@PositiveOrZero
|
||||
private OptionalInt numberOfOrders;
|
||||
|
||||
//@NotBlank
|
||||
private Profile profile;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<String> getAddresses() {
|
||||
return addresses;
|
||||
}
|
||||
|
||||
public void setAddresses(List<String> addresses) {
|
||||
this.addresses = addresses;
|
||||
}
|
||||
|
||||
public Optional<@Min(18) Integer> getAge() {
|
||||
return Optional.ofNullable(age);
|
||||
}
|
||||
|
||||
public void setAge(Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public OptionalInt getNumberOfOrders() {
|
||||
return numberOfOrders;
|
||||
}
|
||||
|
||||
public void setNumberOfOrders(OptionalInt numberOfOrders) {
|
||||
this.numberOfOrders = numberOfOrders;
|
||||
}
|
||||
|
||||
public Profile getProfile() {
|
||||
return profile;
|
||||
}
|
||||
|
||||
public void setProfile(Profile profile) {
|
||||
this.profile = profile;
|
||||
}
|
||||
|
||||
}
|
19
javaxval/src/main/java/org/baeldung/CustomerMap.java
Normal file
19
javaxval/src/main/java/org/baeldung/CustomerMap.java
Normal file
@ -0,0 +1,19 @@
|
||||
package org.baeldung;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import javax.validation.constraints.Email;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public class CustomerMap {
|
||||
|
||||
private Map<@Email(message="Must be a valid email") String, @NotNull Customer> customers;
|
||||
|
||||
public Map<String, Customer> getCustomers() {
|
||||
return customers;
|
||||
}
|
||||
|
||||
public void setCustomers(Map<String, Customer> customers) {
|
||||
this.customers = customers;
|
||||
}
|
||||
}
|
13
javaxval/src/main/java/org/baeldung/Profile.java
Normal file
13
javaxval/src/main/java/org/baeldung/Profile.java
Normal file
@ -0,0 +1,13 @@
|
||||
package org.baeldung;
|
||||
|
||||
public class Profile {
|
||||
private String companyName;
|
||||
|
||||
public String getCompanyName() {
|
||||
return companyName;
|
||||
}
|
||||
|
||||
public void setCompanyName(String companyName) {
|
||||
this.companyName = companyName;
|
||||
}
|
||||
}
|
@ -1,56 +1,94 @@
|
||||
package org.baeldung;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import javax.validation.constraints.AssertTrue;
|
||||
import javax.validation.constraints.Email;
|
||||
import javax.validation.constraints.Max;
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Past;
|
||||
import javax.validation.constraints.Size;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
|
||||
public class User {
|
||||
|
||||
@NotNull(message = "Name cannot be null")
|
||||
private String name;
|
||||
@NotNull(message = "Name cannot be null")
|
||||
private String name;
|
||||
|
||||
@AssertTrue
|
||||
private boolean working;
|
||||
@AssertTrue
|
||||
private boolean working;
|
||||
|
||||
@Size(min = 10, max = 200, message = "Number of characters should be in between 10 and 200 inclusive")
|
||||
private String aboutMe;
|
||||
@Size(min = 10, max = 200, message = "Number of characters should be in between 10 and 200 inclusive")
|
||||
private String aboutMe;
|
||||
|
||||
@Min(value = 18, message = "Age should not be less than 18")
|
||||
@Max(value = 150, message = "Age should not be more than 150")
|
||||
private int age;
|
||||
@Min(value = 18, message = "Age should not be less than 18")
|
||||
@Max(value = 150, message = "Age should not be more than 150")
|
||||
private int age;
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
@Email(message = "Email should be valid")
|
||||
private String email;
|
||||
|
||||
List<@NotBlank String> preferences;
|
||||
|
||||
private LocalDate dateOfBirth;
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public boolean isWorking() {
|
||||
return working;
|
||||
}
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public void setWorking(boolean working) {
|
||||
this.working = working;
|
||||
}
|
||||
public boolean isWorking() {
|
||||
return working;
|
||||
}
|
||||
|
||||
public String getAboutMe() {
|
||||
return aboutMe;
|
||||
}
|
||||
public void setWorking(boolean working) {
|
||||
this.working = working;
|
||||
}
|
||||
|
||||
public void setAboutMe(String aboutMe) {
|
||||
this.aboutMe = aboutMe;
|
||||
}
|
||||
public String getAboutMe() {
|
||||
return aboutMe;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public void setAboutMe(String aboutMe) {
|
||||
this.aboutMe = aboutMe;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Optional<@Past LocalDate> getDateOfBirth() {
|
||||
return Optional.ofNullable(dateOfBirth);
|
||||
}
|
||||
|
||||
public void setDateOfBirth(LocalDate dateOfBirth) {
|
||||
this.dateOfBirth = dateOfBirth;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public List<String> getPreferences() {
|
||||
return preferences;
|
||||
}
|
||||
|
||||
public void setPreferences(List<String> preferences) {
|
||||
this.preferences = preferences;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,17 @@
|
||||
package org.baeldung.valueextractors;
|
||||
|
||||
import javax.validation.valueextraction.ExtractedValue;
|
||||
import javax.validation.valueextraction.UnwrapByDefault;
|
||||
import javax.validation.valueextraction.ValueExtractor;
|
||||
|
||||
import org.baeldung.Profile;
|
||||
|
||||
@UnwrapByDefault
|
||||
public class ProfileValueExtractor implements ValueExtractor<@ExtractedValue(type = String.class) Profile> {
|
||||
|
||||
@Override
|
||||
public void extractValues(Profile originalValue, ValueExtractor.ValueReceiver receiver) {
|
||||
receiver.value(null, originalValue.getCompanyName());
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1 @@
|
||||
org.baeldung.valueextractors.ProfileValueExtractor
|
@ -0,0 +1,88 @@
|
||||
package org.baeldung;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import javax.validation.ValidatorFactory;
|
||||
import org.baeldung.valueextractors.ProfileValueExtractor;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ContainerValidationIntegrationTest {
|
||||
private Validator validator;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
ValidatorFactory factory = Validation.byDefaultProvider().configure()
|
||||
.addValueExtractor(new ProfileValueExtractor()).buildValidatorFactory();
|
||||
validator = factory.getValidator();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenEmptyAddress_thenValidationFails() {
|
||||
Customer customer = new Customer();
|
||||
customer.setName("John");
|
||||
customer.setAddresses(Collections.singletonList(" "));
|
||||
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
|
||||
assertEquals(1, violations.size());
|
||||
assertEquals("Address must not be blank", violations.iterator()
|
||||
.next()
|
||||
.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInvalidEmail_thenValidationFails() {
|
||||
CustomerMap map = new CustomerMap();
|
||||
map.setCustomers(Collections.singletonMap("john", new Customer()));
|
||||
Set<ConstraintViolation<CustomerMap>> violations = validator.validate(map);
|
||||
assertEquals(1, violations.size());
|
||||
assertEquals("Must be a valid email", violations.iterator()
|
||||
.next()
|
||||
.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAgeTooLow_thenValidationFails() {
|
||||
Customer customer = new Customer();
|
||||
customer.setName("John");
|
||||
customer.setAge(15);
|
||||
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
|
||||
assertEquals(1, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAgeNull_thenValidationSucceeds() {
|
||||
Customer customer = new Customer();
|
||||
customer.setName("John");
|
||||
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
|
||||
assertEquals(0, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNumberOrdersValid_thenValidationSucceeds() {
|
||||
Customer customer = new Customer();
|
||||
customer.setName("John");
|
||||
customer.setNumberOfOrders(OptionalInt.of(1));
|
||||
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
|
||||
assertEquals(0, violations.size());
|
||||
}
|
||||
|
||||
//@Test
|
||||
public void whenProfileCompanyNameBlank_thenValidationFails() {
|
||||
Customer customer = new Customer();
|
||||
customer.setName("John");
|
||||
Profile profile = new Profile();
|
||||
profile.setCompanyName(" ");
|
||||
customer.setProfile(profile);
|
||||
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
|
||||
assertEquals(1, violations.size());
|
||||
}
|
||||
|
||||
}
|
@ -1,81 +1,126 @@
|
||||
package org.baeldung;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.Set;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import javax.validation.ValidatorFactory;
|
||||
|
||||
import org.junit.Assert;
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
import org.junit.Before;
|
||||
|
||||
public class ValidationIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void ifNameIsNull_nameValidationFails() {
|
||||
User user = new User();
|
||||
user.setWorking(true);
|
||||
user.setAboutMe("Its all about me!!");
|
||||
user.setAge(50);
|
||||
private Validator validator;
|
||||
|
||||
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
|
||||
Validator validator = factory.getValidator();
|
||||
Set<ConstraintViolation<User>> violations = validator.validate(user);
|
||||
Assert.assertEquals(violations.isEmpty(), false);
|
||||
}
|
||||
@Before
|
||||
public void setup() {
|
||||
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
|
||||
validator = factory.getValidator();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ifSizeNotInRange_aboutMeValidationFails() {
|
||||
User user = new User();
|
||||
user.setName("MyName");
|
||||
user.setAboutMe("Its all about me!!");
|
||||
user.setAge(50);
|
||||
private User createUser() {
|
||||
User user = new User();
|
||||
user.setName("John");
|
||||
user.setWorking(true);
|
||||
user.setAge(18);
|
||||
return user;
|
||||
}
|
||||
|
||||
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
|
||||
Validator validator = factory.getValidator();
|
||||
Set<ConstraintViolation<User>> violations = validator.validate(user);
|
||||
Assert.assertEquals(violations.isEmpty(), false);
|
||||
}
|
||||
@Test
|
||||
public void ifNameIsNull_nameValidationFails() {
|
||||
User user = new User();
|
||||
user.setWorking(true);
|
||||
user.setAboutMe("Its all about me!!");
|
||||
user.setAge(50);
|
||||
Set<ConstraintViolation<User>> violations = validator.validate(user);
|
||||
assertEquals(violations.isEmpty(), false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ifWorkingIsFalse_workingValidationFails() {
|
||||
User user = new User();
|
||||
user.setName("MyName");
|
||||
user.setAboutMe("Its all about me!!");
|
||||
user.setAge(50);
|
||||
@Test
|
||||
public void ifSizeNotInRange_aboutMeValidationFails() {
|
||||
User user = new User();
|
||||
user.setName("MyName");
|
||||
user.setAboutMe("Its all about me!!");
|
||||
user.setAge(50);
|
||||
|
||||
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
|
||||
Validator validator = factory.getValidator();
|
||||
Set<ConstraintViolation<User>> violations = validator.validate(user);
|
||||
Assert.assertEquals(violations.isEmpty(), false);
|
||||
}
|
||||
Set<ConstraintViolation<User>> violations = validator.validate(user);
|
||||
assertEquals(violations.isEmpty(), false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ifAgeNotRange_ageValidationFails() {
|
||||
User user = new User();
|
||||
user.setName("MyName");
|
||||
user.setAboutMe("Its all about me!!");
|
||||
user.setAge(8);
|
||||
@Test
|
||||
public void ifWorkingIsFalse_workingValidationFails() {
|
||||
User user = new User();
|
||||
user.setName("MyName");
|
||||
user.setAboutMe("Its all about me!!");
|
||||
user.setAge(50);
|
||||
|
||||
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
|
||||
Validator validator = factory.getValidator();
|
||||
Set<ConstraintViolation<User>> violations = validator.validate(user);
|
||||
Assert.assertEquals(violations.isEmpty(), false);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void ifFnameNullAgeNotRangeAndWorkingIsFalse_validationFailsWithThreeErrors() {
|
||||
User user = new User();
|
||||
user.setAboutMe("Its all about me!!");
|
||||
user.setAge(300);
|
||||
Set<ConstraintViolation<User>> violations = validator.validate(user);
|
||||
assertEquals(violations.isEmpty(), false);
|
||||
}
|
||||
|
||||
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
|
||||
Validator validator = factory.getValidator();
|
||||
Set<ConstraintViolation<User>> violations = validator.validate(user);
|
||||
Assert.assertEquals(violations.isEmpty(), false);
|
||||
Assert.assertEquals(violations.size(), 3);
|
||||
}
|
||||
@Test
|
||||
public void ifAgeNotRange_ageValidationFails() {
|
||||
User user = new User();
|
||||
user.setName("MyName");
|
||||
user.setAboutMe("Its all about me!!");
|
||||
user.setAge(8);
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validate(user);
|
||||
assertEquals(violations.isEmpty(), false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ifFnameNullAgeNotRangeAndWorkingIsFalse_validationFailsWithThreeErrors() {
|
||||
User user = new User();
|
||||
user.setAboutMe("Its all about me!!");
|
||||
user.setAge(300);
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validate(user);
|
||||
assertEquals(violations.isEmpty(), false);
|
||||
assertEquals(violations.size(), 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidEmail_thenValidationFails() {
|
||||
User user = createUser();
|
||||
user.setEmail("john");
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validate(user);
|
||||
assertEquals(1, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBlankPreference_thenValidationFails() {
|
||||
User user = createUser();
|
||||
user.setPreferences(Collections.singletonList(" "));
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validate(user);
|
||||
assertEquals(1, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyOptional_thenValidationSucceeds() {
|
||||
User user = createUser();
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validate(user);
|
||||
assertEquals(0, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPastDateOfBirth_thenValidationSuccess() {
|
||||
User user = createUser();
|
||||
user.setDateOfBirth(LocalDate.of(1980, 5, 20));
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validate(user);
|
||||
assertEquals(0, violations.size());
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -585,11 +585,6 @@
|
||||
<artifactId>fugue</artifactId>
|
||||
<version>3.0.0-m007</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jgrapht</groupId>
|
||||
<artifactId>jgrapht-core</artifactId>
|
||||
<version>1.0.1</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<repositories>
|
||||
<repository>
|
||||
|
@ -3,6 +3,8 @@ package com.baeldung.commons.lang3;
|
||||
import org.apache.commons.lang3.builder.EqualsBuilder;
|
||||
import org.apache.commons.lang3.builder.HashCodeBuilder;
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
import org.apache.commons.lang3.concurrent.ConcurrentException;
|
||||
import org.apache.commons.lang3.concurrent.BackgroundInitializer;
|
||||
|
||||
public class BuilderMethods {
|
||||
|
||||
@ -56,5 +58,36 @@ public class BuilderMethods {
|
||||
System.out.println(simple1.getName());
|
||||
System.out.println(simple1.hashCode());
|
||||
System.out.println(simple1.toString());
|
||||
|
||||
SampleLazyInitializer sampleLazyInitializer = new SampleLazyInitializer();
|
||||
|
||||
try {
|
||||
sampleLazyInitializer.get();
|
||||
} catch (ConcurrentException e1) {
|
||||
// TODO Auto-generated catch block
|
||||
e1.printStackTrace();
|
||||
}
|
||||
|
||||
SampleBackgroundInitializer sampleBackgroundInitializer = new SampleBackgroundInitializer();
|
||||
sampleBackgroundInitializer.start();
|
||||
|
||||
// Proceed with other tasks instead of waiting for the SampleBackgroundInitializer task to finish.
|
||||
|
||||
try {
|
||||
Object result = sampleBackgroundInitializer.get();
|
||||
} catch (ConcurrentException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class SampleBackgroundInitializer extends BackgroundInitializer<String>{
|
||||
|
||||
@Override
|
||||
protected String initialize() throws Exception {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Any complex task that takes some time
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,72 @@
|
||||
package com.baeldung.jdo.xml;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.jdo.annotations.Element;
|
||||
import javax.jdo.annotations.PersistenceCapable;
|
||||
import javax.jdo.annotations.PrimaryKey;
|
||||
import javax.xml.bind.annotation.XmlAttribute;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlElementWrapper;
|
||||
|
||||
@PersistenceCapable(
|
||||
schema="/myproduct/people",
|
||||
table="person"
|
||||
)
|
||||
public class AnnotadedPerson {
|
||||
@XmlAttribute
|
||||
private long personNum;
|
||||
|
||||
@PrimaryKey
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
@XmlElementWrapper(name="phone-numbers")
|
||||
@XmlElement(name="phone-number")
|
||||
@Element(types=String.class)
|
||||
private List phoneNumbers = new ArrayList();
|
||||
|
||||
|
||||
public AnnotadedPerson(long personNum, String firstName, String lastName) {
|
||||
super();
|
||||
this.personNum = personNum;
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public long getPersonNum() {
|
||||
return personNum;
|
||||
}
|
||||
|
||||
public void setPersonNum(long personNum) {
|
||||
this.personNum = personNum;
|
||||
}
|
||||
|
||||
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 List getPhoneNumbers() {
|
||||
return phoneNumbers;
|
||||
}
|
||||
|
||||
public void setPhoneNumbers(List phoneNumbers) {
|
||||
this.phoneNumbers = phoneNumbers;
|
||||
}
|
||||
|
||||
}
|
105
libraries/src/main/java/com/baeldung/jdo/xml/MyApp.java
Normal file
105
libraries/src/main/java/com/baeldung/jdo/xml/MyApp.java
Normal file
@ -0,0 +1,105 @@
|
||||
package com.baeldung.jdo.xml;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.jdo.JDOHelper;
|
||||
import javax.jdo.PersistenceManager;
|
||||
import javax.jdo.PersistenceManagerFactory;
|
||||
import javax.jdo.Query;
|
||||
import javax.jdo.Transaction;
|
||||
|
||||
import org.datanucleus.api.jdo.JDOPersistenceManagerFactory;
|
||||
import org.datanucleus.metadata.PersistenceUnitMetaData;
|
||||
|
||||
public class MyApp {
|
||||
|
||||
private static PersistenceUnitMetaData pumd;
|
||||
private static PersistenceManagerFactory pmf;
|
||||
private static PersistenceManager pm;
|
||||
|
||||
public static void main( String[] args ) {
|
||||
|
||||
//persist product object using dynamic persistence unit
|
||||
defineDynamicPersistentUnit();
|
||||
Product product = new Product("id1","Sony Discman", "A standard discman from Sony", 49.99);
|
||||
persistObject(product);
|
||||
closePersistenceManager();
|
||||
|
||||
//persist AnnotatedPerson object using named pmf
|
||||
defineNamedPersistenceManagerFactory("XmlDatastore");
|
||||
AnnotadedPerson annotatedPerson = new AnnotadedPerson(654320,"annotated","person");
|
||||
annotatedPerson.getPhoneNumbers().add("999999999");
|
||||
annotatedPerson.getPhoneNumbers().add("000000000");
|
||||
persistObject(annotatedPerson);
|
||||
queryAnnotatedPersonsInXML();
|
||||
closePersistenceManager();
|
||||
|
||||
//persist Person object using PMF created by properties file
|
||||
definePersistenceManagerFactoryUsingPropertiesFile("META-INF\\datanucleus.properties");
|
||||
Person person = new Person(654321,"bealdung","author");
|
||||
person.getPhoneNumbers().add("123456789");
|
||||
person.getPhoneNumbers().add("987654321");
|
||||
persistObject(person);
|
||||
queryPersonsInXML();
|
||||
closePersistenceManager();
|
||||
}
|
||||
|
||||
public static void defineDynamicPersistentUnit(){
|
||||
|
||||
PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
|
||||
pumd.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myfile_dynamicPMF.xml");
|
||||
pumd.addProperty("datanucleus.schema.autoCreateAll", "true");
|
||||
pumd.addProperty("datanucleus.xml.indentSize", "4");
|
||||
|
||||
pmf = new JDOPersistenceManagerFactory(pumd, null);
|
||||
pm = pmf.getPersistenceManager();
|
||||
}
|
||||
|
||||
public static void defineNamedPersistenceManagerFactory(String pmfName){
|
||||
|
||||
pmf = JDOHelper.getPersistenceManagerFactory("XmlDatastore");
|
||||
pm = pmf.getPersistenceManager();
|
||||
}
|
||||
|
||||
public static void definePersistenceManagerFactoryUsingPropertiesFile(String filePath){
|
||||
|
||||
pmf = JDOHelper.getPersistenceManagerFactory(filePath);
|
||||
pm = pmf.getPersistenceManager();
|
||||
}
|
||||
|
||||
public static void closePersistenceManager(){
|
||||
|
||||
if(pm!=null && !pm.isClosed()){
|
||||
pm.close();
|
||||
}
|
||||
}
|
||||
|
||||
public static void persistObject(Object obj){
|
||||
|
||||
Transaction tx = pm.currentTransaction();
|
||||
|
||||
try {
|
||||
tx.begin();
|
||||
pm.makePersistent(obj);
|
||||
tx.commit();
|
||||
} finally {
|
||||
if (tx.isActive()) {
|
||||
tx.rollback();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void queryPersonsInXML(){
|
||||
|
||||
Query<Person> query = pm.newQuery(Person.class);
|
||||
List<Person> result = query.executeList();
|
||||
System.out.println("name: "+result.get(0).getFirstName());
|
||||
}
|
||||
|
||||
public static void queryAnnotatedPersonsInXML(){
|
||||
|
||||
Query<AnnotadedPerson> query = pm.newQuery(AnnotadedPerson.class);
|
||||
List<AnnotadedPerson> result = query.executeList();
|
||||
System.out.println("name: "+result.get(0).getFirstName());
|
||||
}
|
||||
}
|
65
libraries/src/main/java/com/baeldung/jdo/xml/Person.java
Normal file
65
libraries/src/main/java/com/baeldung/jdo/xml/Person.java
Normal file
@ -0,0 +1,65 @@
|
||||
package com.baeldung.jdo.xml;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.jdo.annotations.Element;
|
||||
import javax.jdo.annotations.PersistenceCapable;
|
||||
import javax.jdo.annotations.PrimaryKey;
|
||||
import javax.xml.bind.annotation.XmlAttribute;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlElementWrapper;
|
||||
|
||||
|
||||
@PersistenceCapable
|
||||
public class Person {
|
||||
private long personNum;
|
||||
|
||||
@PrimaryKey
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
private List phoneNumbers = new ArrayList();
|
||||
|
||||
public Person(long personNum, String firstName, String lastName) {
|
||||
super();
|
||||
this.personNum = personNum;
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public long getPersonNum() {
|
||||
return personNum;
|
||||
}
|
||||
|
||||
public void setPersonNum(long personNum) {
|
||||
this.personNum = personNum;
|
||||
}
|
||||
|
||||
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 List getPhoneNumbers() {
|
||||
return phoneNumbers;
|
||||
}
|
||||
|
||||
public void setPhoneNumbers(List phoneNumbers) {
|
||||
this.phoneNumbers = phoneNumbers;
|
||||
}
|
||||
|
||||
}
|
58
libraries/src/main/java/com/baeldung/jdo/xml/Product.java
Normal file
58
libraries/src/main/java/com/baeldung/jdo/xml/Product.java
Normal file
@ -0,0 +1,58 @@
|
||||
package com.baeldung.jdo.xml;
|
||||
|
||||
import javax.jdo.annotations.IdGeneratorStrategy;
|
||||
import javax.jdo.annotations.PersistenceAware;
|
||||
import javax.jdo.annotations.PersistenceCapable;
|
||||
import javax.jdo.annotations.Persistent;
|
||||
import javax.jdo.annotations.PrimaryKey;
|
||||
|
||||
@PersistenceCapable
|
||||
public class Product {
|
||||
|
||||
@PrimaryKey
|
||||
String id;
|
||||
String name;
|
||||
String description;
|
||||
double price;
|
||||
|
||||
public Product(){
|
||||
|
||||
}
|
||||
|
||||
public Product(String id,String name,String description,double price){
|
||||
this.id = id;
|
||||
this.name=name;
|
||||
this.description = description;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
public double getPrice() {
|
||||
return price;
|
||||
}
|
||||
public void setPrice(double price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
javax.jdo.PersistenceManagerFactoryClass=org.datanucleus.api.jdo.JDOPersistenceManagerFactory
|
||||
javax.jdo.option.ConnectionURL= xml:file:myfile-ds.xml
|
||||
datanucleus.xml.indentSize=6
|
||||
datanucleus.schema.autoCreateAll=true
|
17
libraries/src/main/resources/META-INF/jdoconfig.xml
Normal file
17
libraries/src/main/resources/META-INF/jdoconfig.xml
Normal file
@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<jdoconfig xmlns="http://xmlns.jcp.org/xml/ns/jdo/jdoconfig"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/jdo/jdoconfig
|
||||
http://xmlns.jcp.org/xml/ns/jdo/jdoconfig_3_2.xsd"
|
||||
version="3.2">
|
||||
|
||||
<!-- Datastore Txn PMF -->
|
||||
<persistence-manager-factory name="XmlDatastore">
|
||||
<property name="javax.jdo.PersistenceManagerFactoryClass"
|
||||
value="org.datanucleus.api.jdo.JDOPersistenceManagerFactory" />
|
||||
<property name="javax.jdo.option.ConnectionURL" value="xml:file:namedPMF-ds.xml" />
|
||||
<property name="datanucleus.xml.indentSize" value="6" />
|
||||
<property name="datanucleus.schema.autoCreateAll"
|
||||
value="true" />
|
||||
</persistence-manager-factory>
|
||||
</jdoconfig>
|
21
libraries/src/main/resources/META-INF/package.jdo
Normal file
21
libraries/src/main/resources/META-INF/package.jdo
Normal file
@ -0,0 +1,21 @@
|
||||
<jdo xmlns="http://xmlns.jcp.org/xml/ns/jdo/jdo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/jdo/jdo http://xmlns.jcp.org/xml/ns/jdo/jdo_3_1.xsd"
|
||||
version="3.1">
|
||||
<package name="com.baeldung.jdo.xml">
|
||||
<class name="Person" detachable="true" schema="/myproduct/people"
|
||||
table="person">
|
||||
<field name="personNum">
|
||||
<extension vendor-name="datanucleus" key="XmlAttribute"
|
||||
value="true" />
|
||||
</field>
|
||||
<field name="firstName" primary-key="true" /> <!-- PK since JAXB requires String -->
|
||||
<field name="lastName" />
|
||||
<field name="phoneNumbers">
|
||||
<collection element-type="java.lang.String" />
|
||||
<element column="phoneNumber" />
|
||||
</field>
|
||||
</class>
|
||||
</package>
|
||||
|
||||
|
||||
</jdo>
|
@ -3,7 +3,9 @@ package com.baeldung.commons.lang3;
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNotSame;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
@ -20,6 +22,7 @@ import org.apache.commons.lang3.ArchUtils;
|
||||
import org.apache.commons.lang3.BooleanUtils;
|
||||
import org.apache.commons.lang3.SystemUtils;
|
||||
import org.apache.commons.lang3.arch.Processor;
|
||||
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
|
||||
import org.apache.commons.lang3.concurrent.ConcurrentException;
|
||||
import org.apache.commons.lang3.concurrent.ConcurrentRuntimeException;
|
||||
import org.apache.commons.lang3.concurrent.ConcurrentUtils;
|
||||
@ -133,4 +136,14 @@ public class Lang3UtilsTest {
|
||||
assertEquals(sampleObjectOne, sampleObjectTwo);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildDefaults() {
|
||||
BasicThreadFactory.Builder builder = new BasicThreadFactory.Builder();
|
||||
BasicThreadFactory factory = builder.build();
|
||||
assertNull("No naming pattern set Yet", factory.getNamingPattern());
|
||||
BasicThreadFactory factory2 = builder.namingPattern("sampleNamingPattern").daemon(true).priority(Thread.MIN_PRIORITY).build();
|
||||
assertNotNull("Got a naming pattern", factory2.getNamingPattern());
|
||||
assertEquals("sampleNamingPattern", factory2.getNamingPattern());
|
||||
|
||||
}
|
||||
}
|
||||
|
1
pom.xml
1
pom.xml
@ -28,6 +28,7 @@
|
||||
</properties>
|
||||
|
||||
<modules>
|
||||
<module>atomix</module>
|
||||
<module>apache-cayenne</module>
|
||||
<module>aws</module>
|
||||
<module>akka-streams</module>
|
||||
|
@ -14,7 +14,7 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.0.0.M1</version>
|
||||
<version>2.0.0.M3</version>
|
||||
<relativePath/>
|
||||
<!-- lookup parent from repository -->
|
||||
</parent>
|
||||
@ -165,14 +165,6 @@
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
@ -183,14 +175,6 @@
|
||||
</repository>
|
||||
</repositories>
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</pluginRepository>
|
||||
<pluginRepository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
|
@ -14,7 +14,7 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.0.0.M1</version>
|
||||
<version>2.0.0.M3</version>
|
||||
<relativePath /> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
@ -143,14 +143,6 @@
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
@ -161,14 +153,6 @@
|
||||
</repository>
|
||||
</repositories>
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</pluginRepository>
|
||||
<pluginRepository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
@ -183,10 +167,10 @@
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<junit.platform.version>1.0.0-M4</junit.platform.version>
|
||||
<junit.jupiter.version>5.0.0-M4</junit.jupiter.version>
|
||||
<junit.platform.version>1.0.0</junit.platform.version>
|
||||
<junit.jupiter.version>5.0.0</junit.jupiter.version>
|
||||
<maven-surefire-plugin.version>2.20</maven-surefire-plugin.version>
|
||||
<spring.version>5.0.0.RC2</spring.version>
|
||||
<spring.version>5.0.0.RELEASE</spring.version>
|
||||
<reactor-spring.version>1.0.1.RELEASE</reactor-spring.version>
|
||||
<johnzon.version>1.1.3</johnzon.version>
|
||||
<jsonb-api.version>1.0</jsonb-api.version>
|
||||
|
@ -33,7 +33,7 @@ public class ExploreSpring5URLPatternUsingRouterFunctions {
|
||||
WebServer start() throws Exception {
|
||||
WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction());
|
||||
HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler)
|
||||
.prependFilter(new IndexRewriteFilter())
|
||||
.filter(new IndexRewriteFilter())
|
||||
.build();
|
||||
|
||||
Tomcat tomcat = new Tomcat();
|
||||
|
@ -1,5 +1,17 @@
|
||||
package com.baeldung.functional;
|
||||
|
||||
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
|
||||
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
|
||||
import static org.springframework.web.reactive.function.server.RequestPredicates.POST;
|
||||
import static org.springframework.web.reactive.function.server.RequestPredicates.path;
|
||||
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
|
||||
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;
|
||||
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.web.servlet.ServletRegistrationBean;
|
||||
@ -17,18 +29,9 @@ import org.springframework.web.reactive.function.server.RouterFunctions;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
import org.springframework.web.server.WebHandler;
|
||||
import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
|
||||
import static org.springframework.web.reactive.function.server.RequestPredicates.*;
|
||||
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
|
||||
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;
|
||||
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
|
||||
|
||||
@SpringBootApplication
|
||||
@ComponentScan(basePackages = { "com.baeldung.functional" })
|
||||
public class FunctionalSpringBootApplication {
|
||||
@ -57,7 +60,7 @@ public class FunctionalSpringBootApplication {
|
||||
@Bean
|
||||
public ServletRegistrationBean servletRegistrationBean() throws Exception {
|
||||
HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction()))
|
||||
.prependFilter(new IndexRewriteFilter())
|
||||
.filter(new IndexRewriteFilter())
|
||||
.build();
|
||||
ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(new RootServlet(httpHandler), "/");
|
||||
registrationBean.setLoadOnStartup(1);
|
||||
|
@ -1,5 +1,17 @@
|
||||
package com.baeldung.functional;
|
||||
|
||||
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
|
||||
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
|
||||
import static org.springframework.web.reactive.function.server.RequestPredicates.POST;
|
||||
import static org.springframework.web.reactive.function.server.RequestPredicates.path;
|
||||
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
|
||||
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;
|
||||
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import org.apache.catalina.Context;
|
||||
import org.apache.catalina.startup.Tomcat;
|
||||
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
|
||||
@ -12,18 +24,9 @@ import org.springframework.web.reactive.function.server.RouterFunctions;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
import org.springframework.web.server.WebHandler;
|
||||
import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
|
||||
import static org.springframework.web.reactive.function.server.RequestPredicates.*;
|
||||
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
|
||||
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;
|
||||
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
|
||||
|
||||
public class FunctionalWebApplication {
|
||||
|
||||
private static final Actor BRAD_PITT = new Actor("Brad", "Pitt");
|
||||
@ -50,7 +53,7 @@ public class FunctionalWebApplication {
|
||||
WebServer start() throws Exception {
|
||||
WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction());
|
||||
HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler)
|
||||
.prependFilter(new IndexRewriteFilter())
|
||||
.filter(new IndexRewriteFilter())
|
||||
.build();
|
||||
|
||||
Tomcat tomcat = new Tomcat();
|
||||
|
@ -1,5 +1,20 @@
|
||||
package com.baeldung.functional;
|
||||
|
||||
import static org.springframework.web.reactive.function.BodyExtractors.toDataBuffers;
|
||||
import static org.springframework.web.reactive.function.BodyExtractors.toFormData;
|
||||
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
|
||||
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
|
||||
import static org.springframework.web.reactive.function.server.RequestPredicates.POST;
|
||||
import static org.springframework.web.reactive.function.server.RequestPredicates.path;
|
||||
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
|
||||
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;
|
||||
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.http.server.reactive.HttpHandler;
|
||||
import org.springframework.http.server.reactive.ServletHttpHandlerAdapter;
|
||||
@ -7,29 +22,17 @@ import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.reactive.function.server.RouterFunction;
|
||||
import org.springframework.web.reactive.function.server.RouterFunctions;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
import org.springframework.web.server.WebHandler;
|
||||
import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import static org.springframework.web.reactive.function.BodyExtractors.toDataBuffers;
|
||||
import static org.springframework.web.reactive.function.BodyExtractors.toFormData;
|
||||
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
|
||||
import static org.springframework.web.reactive.function.server.RequestPredicates.*;
|
||||
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
|
||||
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;
|
||||
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
|
||||
import org.springframework.web.server.WebHandler;
|
||||
|
||||
public class RootServlet extends ServletHttpHandlerAdapter {
|
||||
|
||||
public RootServlet() {
|
||||
this(WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction()))
|
||||
.prependFilter(new IndexRewriteFilter())
|
||||
.filter(new IndexRewriteFilter())
|
||||
.build());
|
||||
}
|
||||
|
||||
|
@ -10,6 +10,7 @@ import javax.json.bind.annotation.JsonbTransient;
|
||||
|
||||
public class Person {
|
||||
|
||||
private int id;
|
||||
@JsonbProperty("person-name")
|
||||
private String name;
|
||||
@JsonbProperty(nillable = true)
|
||||
@ -23,8 +24,9 @@ public class Person {
|
||||
public Person() {
|
||||
}
|
||||
|
||||
public Person(String name, String email, int age, LocalDate registeredDate, BigDecimal salary) {
|
||||
public Person(int id, String name, String email, int age, LocalDate registeredDate, BigDecimal salary) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
this.age = age;
|
||||
@ -32,6 +34,14 @@ public class Person {
|
||||
this.salary = salary;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
@ -76,7 +86,9 @@ public class Person {
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("Person [name=");
|
||||
builder.append("Person [id=");
|
||||
builder.append(id);
|
||||
builder.append(", name=");
|
||||
builder.append(name);
|
||||
builder.append(", email=");
|
||||
builder.append(email);
|
||||
@ -94,11 +106,7 @@ public class Person {
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + age;
|
||||
result = prime * result + ((email == null) ? 0 : email.hashCode());
|
||||
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||
result = prime * result + ((registeredDate == null) ? 0 : registeredDate.hashCode());
|
||||
result = prime * result + ((salary == null) ? 0 : salary.hashCode());
|
||||
result = prime * result + id;
|
||||
return result;
|
||||
}
|
||||
|
||||
@ -111,27 +119,7 @@ public class Person {
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Person other = (Person) obj;
|
||||
if (age != other.age)
|
||||
return false;
|
||||
if (email == null) {
|
||||
if (other.email != null)
|
||||
return false;
|
||||
} else if (!email.equals(other.email))
|
||||
return false;
|
||||
if (name == null) {
|
||||
if (other.name != null)
|
||||
return false;
|
||||
} else if (!name.equals(other.name))
|
||||
return false;
|
||||
if (registeredDate == null) {
|
||||
if (other.registeredDate != null)
|
||||
return false;
|
||||
} else if (!registeredDate.equals(other.registeredDate))
|
||||
return false;
|
||||
if (salary == null) {
|
||||
if (other.salary != null)
|
||||
return false;
|
||||
} else if (!salary.equals(other.salary))
|
||||
if (id != other.id)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
@ -26,12 +26,12 @@ public class PersonController {
|
||||
public void init() {
|
||||
// @formatter:off
|
||||
personRepository = new ArrayList<>(Arrays.asList(
|
||||
new Person("Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)),
|
||||
new Person("Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)),
|
||||
new Person("Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)),
|
||||
new Person("Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)),
|
||||
new Person("Mark", "mark@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1200)),
|
||||
new Person("Julia", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000))));
|
||||
new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)),
|
||||
new Person(2, "Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)),
|
||||
new Person(3, "Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)),
|
||||
new Person(4, "Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)),
|
||||
new Person(5, "Mark", "mark@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1200)),
|
||||
new Person(6, "Julia", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000))));
|
||||
// @formatter:on
|
||||
|
||||
}
|
||||
|
@ -1,28 +1,36 @@
|
||||
package com.baeldung.jupiter;
|
||||
|
||||
import org.junit.jupiter.api.extension.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.core.annotation.AnnotatedElementUtils;
|
||||
import org.springframework.test.context.TestContextManager;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Executable;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Parameter;
|
||||
|
||||
import org.junit.jupiter.api.extension.AfterAllCallback;
|
||||
import org.junit.jupiter.api.extension.AfterEachCallback;
|
||||
import org.junit.jupiter.api.extension.BeforeAllCallback;
|
||||
import org.junit.jupiter.api.extension.BeforeEachCallback;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
import org.junit.jupiter.api.extension.ParameterContext;
|
||||
import org.junit.jupiter.api.extension.ParameterResolutionException;
|
||||
import org.junit.jupiter.api.extension.ParameterResolver;
|
||||
import org.junit.jupiter.api.extension.TestInstancePostProcessor;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.core.annotation.AnnotatedElementUtils;
|
||||
import org.springframework.test.context.TestContextManager;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
public class SpringExtension implements BeforeAllCallback, AfterAllCallback, TestInstancePostProcessor, BeforeEachCallback, AfterEachCallback, ParameterResolver {
|
||||
|
||||
private static final ExtensionContext.Namespace namespace = ExtensionContext.Namespace.create(SpringExtension.class);
|
||||
|
||||
@Override
|
||||
public void beforeAll(ContainerExtensionContext context) throws Exception {
|
||||
public void beforeAll(ExtensionContext context) throws Exception {
|
||||
getTestContextManager(context).beforeTestClass();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterAll(ContainerExtensionContext context) throws Exception {
|
||||
public void afterAll(ExtensionContext context) throws Exception {
|
||||
try {
|
||||
getTestContextManager(context).afterTestClass();
|
||||
} finally {
|
||||
@ -38,7 +46,7 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeEach(TestExtensionContext context) throws Exception {
|
||||
public void beforeEach(ExtensionContext context) throws Exception {
|
||||
Object testInstance = context.getTestInstance();
|
||||
Method testMethod = context.getTestMethod()
|
||||
.get();
|
||||
@ -46,24 +54,24 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterEach(TestExtensionContext context) throws Exception {
|
||||
public void afterEach(ExtensionContext context) throws Exception {
|
||||
Object testInstance = context.getTestInstance();
|
||||
Method testMethod = context.getTestMethod()
|
||||
.get();
|
||||
Throwable testException = context.getTestException()
|
||||
Throwable testException = context.getExecutionException()
|
||||
.orElse(null);
|
||||
getTestContextManager(context).afterTestMethod(testInstance, testMethod, testException);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(ParameterContext parameterContext, ExtensionContext extensionContext) {
|
||||
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
|
||||
Parameter parameter = parameterContext.getParameter();
|
||||
Executable executable = parameter.getDeclaringExecutable();
|
||||
return (executable instanceof Constructor && AnnotatedElementUtils.hasAnnotation(executable, Autowired.class)) || ParameterAutowireUtils.isAutowirable(parameter);
|
||||
return ((executable instanceof Constructor) && AnnotatedElementUtils.hasAnnotation(executable, Autowired.class)) || ParameterAutowireUtils.isAutowirable(parameter);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) {
|
||||
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
|
||||
Parameter parameter = parameterContext.getParameter();
|
||||
Class<?> testClass = extensionContext.getTestClass()
|
||||
.get();
|
||||
|
@ -30,15 +30,14 @@ public class JsonbIntegrationTest {
|
||||
ResponseEntity<Person> response = template.withBasicAuth(username, password)
|
||||
.getForEntity("/person/1", Person.class);
|
||||
Person person = response.getBody();
|
||||
assertTrue(person.equals(new Person("Jhon", "jhon1@test.com", 0, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500.0))));
|
||||
assertTrue(person.equals(new Person(2, "Jhon", "jhon1@test.com", 0, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500.0))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendPostAPerson_thenGetOkStatus() {
|
||||
ResponseEntity<Boolean> response = template.withBasicAuth(username, password)
|
||||
.postForEntity("/person", "{\"birthDate\":\"07-09-2017\",\"email\":\"jhon1@test.com\",\"person-name\":\"Jhon\"}", Boolean.class);
|
||||
boolean value = response.getBody();
|
||||
assertTrue(true == value);
|
||||
.postForEntity("/person", "{\"birthDate\":\"07-09-2017\",\"email\":\"jhon1@test.com\",\"person-name\":\"Jhon\",\"id\":10}", Boolean.class);
|
||||
assertTrue(response.getBody());
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -22,15 +22,15 @@ public class JsonbTest {
|
||||
|
||||
@Test
|
||||
public void givenPersonObject_whenSerializeWithJsonb_thenGetPersonJson() {
|
||||
Person person = new Person("Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000));
|
||||
Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000));
|
||||
String jsonPerson = jsonb.toJson(person);
|
||||
assertTrue("{\"email\":\"jhon@test.com\",\"person-name\":\"Jhon\",\"registeredDate\":\"07-09-2019\",\"salary\":\"1000.0\"}".equals(jsonPerson));
|
||||
assertTrue("{\"email\":\"jhon@test.com\",\"id\":1,\"person-name\":\"Jhon\",\"registeredDate\":\"07-09-2019\",\"salary\":\"1000.0\"}".equals(jsonPerson));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPersonJson_whenDeserializeWithJsonb_thenGetPersonObject() {
|
||||
Person person = new Person("Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));
|
||||
String jsonPerson = "{\"email\":\"jhon@test.com\",\"person-name\":\"Jhon\",\"registeredDate\":\"07-09-2019\",\"salary\":\"1000.0\"}";
|
||||
Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));
|
||||
String jsonPerson = "{\"email\":\"jhon@test.com\",\"id\":1,\"person-name\":\"Jhon\",\"registeredDate\":\"07-09-2019\",\"salary\":\"1000.0\"}";
|
||||
assertTrue(jsonb.fromJson(jsonPerson, Person.class)
|
||||
.equals(person));
|
||||
}
|
||||
|
@ -2,15 +2,9 @@ package com.baeldung.hibernate.immutable.entities;
|
||||
|
||||
import org.hibernate.annotations.Cascade;
|
||||
import org.hibernate.annotations.CascadeType;
|
||||
import org.hibernate.annotations.GenericGenerator;
|
||||
import org.hibernate.annotations.Immutable;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.ElementCollection;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
import javax.persistence.*;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@ -20,8 +14,6 @@ public class Event {
|
||||
|
||||
@Id
|
||||
@Column(name = "event_id")
|
||||
@GeneratedValue(generator = "increment")
|
||||
@GenericGenerator(name = "increment", strategy = "increment")
|
||||
private Long id;
|
||||
|
||||
@Column(name = "title")
|
||||
@ -31,6 +23,14 @@ public class Event {
|
||||
@Immutable
|
||||
private Set<String> guestList;
|
||||
|
||||
public Event() {}
|
||||
|
||||
public Event(Long id, String title, Set<String> guestList) {
|
||||
this.id = id;
|
||||
this.title = title;
|
||||
this.guestList = guestList;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
@ -0,0 +1,55 @@
|
||||
package com.baeldung.hibernate.immutable.entities;
|
||||
|
||||
import org.hibernate.annotations.GenericGenerator;
|
||||
import org.hibernate.annotations.Immutable;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
@Immutable
|
||||
@Table(name = "events_generated")
|
||||
public class EventGeneratedId {
|
||||
|
||||
@Id
|
||||
@Column(name = "event_generated_id")
|
||||
@GeneratedValue(generator = "increment")
|
||||
@GenericGenerator(name = "increment", strategy = "increment")
|
||||
private Long id;
|
||||
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
@Column(name = "description")
|
||||
private String description;
|
||||
|
||||
public EventGeneratedId() {
|
||||
}
|
||||
|
||||
public EventGeneratedId(String name, String description) {
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
}
|
@ -1,6 +1,7 @@
|
||||
package com.baeldung.hibernate.immutable.util;
|
||||
|
||||
import com.baeldung.hibernate.immutable.entities.Event;
|
||||
import com.baeldung.hibernate.immutable.entities.EventGeneratedId;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.cfg.Configuration;
|
||||
@ -14,6 +15,7 @@ public class HibernateUtil {
|
||||
// Create a session factory from immutable.cfg.xml
|
||||
Configuration configuration = new Configuration();
|
||||
configuration.addAnnotatedClass(Event.class);
|
||||
configuration.addAnnotatedClass(EventGeneratedId.class);
|
||||
configuration.configure("immutable.cfg.xml");
|
||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
|
||||
return configuration.buildSessionFactory(serviceRegistry);
|
||||
|
@ -21,7 +21,7 @@
|
||||
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
|
||||
<property name="driverClassName" value="${jdbc.driverClassName}"/>
|
||||
<property name="url" value="${jdbc.url}"/>
|
||||
<property name="username" value="${jdbc.user}"/>
|
||||
<property name="username" value="${jdbc.eventGeneratedId}"/>
|
||||
<property name="password" value="${jdbc.pass}"/>
|
||||
</bean>
|
||||
|
||||
|
@ -1,7 +1,7 @@
|
||||
# jdbc.X
|
||||
jdbc.driverClassName=org.h2.Driver
|
||||
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
|
||||
jdbc.user=sa
|
||||
jdbc.eventGeneratedId=sa
|
||||
jdbc.pass=sa
|
||||
|
||||
# hibernate.X
|
||||
|
@ -1,7 +1,7 @@
|
||||
# jdbc.X
|
||||
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
|
||||
jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate5_01?createDatabaseIfNotExist=true
|
||||
jdbc.user=tutorialuser
|
||||
jdbc.eventGeneratedId=tutorialuser
|
||||
jdbc.pass=tutorialmy5ql
|
||||
|
||||
# hibernate.X
|
||||
|
@ -1,6 +1,7 @@
|
||||
package com.baeldung.hibernate.immutable;
|
||||
|
||||
import com.baeldung.hibernate.immutable.entities.Event;
|
||||
import com.baeldung.hibernate.immutable.entities.EventGeneratedId;
|
||||
import com.baeldung.hibernate.immutable.util.HibernateUtil;
|
||||
import com.google.common.collect.Sets;
|
||||
import org.hibernate.CacheMode;
|
||||
@ -10,6 +11,9 @@ import org.junit.rules.ExpectedException;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.core.IsEqual.equalTo;
|
||||
|
||||
public class HibernateImmutableIntegrationTest {
|
||||
|
||||
private static Session session;
|
||||
@ -22,6 +26,7 @@ public class HibernateImmutableIntegrationTest {
|
||||
session = HibernateUtil.getSessionFactory().getCurrentSession();
|
||||
session.beginTransaction();
|
||||
createEvent();
|
||||
createEventGenerated();
|
||||
session.setCacheMode(CacheMode.REFRESH);
|
||||
}
|
||||
|
||||
@ -35,9 +40,12 @@ public class HibernateImmutableIntegrationTest {
|
||||
HibernateUtil.getSessionFactory().close();
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void addEvent() {
|
||||
Event event = new Event();
|
||||
event.setId(2L);
|
||||
event.setTitle("Public Event");
|
||||
session.save(event);
|
||||
session.getTransaction().commit();
|
||||
@ -47,8 +55,12 @@ public class HibernateImmutableIntegrationTest {
|
||||
public void updateEvent() {
|
||||
Event event = (Event) session.createQuery("FROM Event WHERE title='New Event'").list().get(0);
|
||||
event.setTitle("Private Event");
|
||||
session.saveOrUpdate(event);
|
||||
session.getTransaction().commit();
|
||||
session.update(event);
|
||||
session.flush();
|
||||
session.refresh(event);
|
||||
|
||||
assertThat(event.getTitle(), equalTo("New Event"));
|
||||
assertThat(event.getId(), equalTo(5L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -80,10 +92,29 @@ public class HibernateImmutableIntegrationTest {
|
||||
session.getTransaction().commit();
|
||||
}
|
||||
|
||||
public static void createEvent() {
|
||||
Event event = new Event();
|
||||
event.setTitle("New Event");
|
||||
event.setGuestList(Sets.newHashSet("guest"));
|
||||
@Test
|
||||
public void updateEventGenerated() {
|
||||
EventGeneratedId eventGeneratedId = (EventGeneratedId) session.createQuery("FROM EventGeneratedId WHERE name LIKE '%John%'").list().get(0);
|
||||
eventGeneratedId.setName("Mike");
|
||||
session.update(eventGeneratedId);
|
||||
session.flush();
|
||||
session.refresh(eventGeneratedId);
|
||||
|
||||
assertThat(eventGeneratedId.getName(), equalTo("John"));
|
||||
assertThat(eventGeneratedId.getId(), equalTo(1L));
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
private static void createEvent() {
|
||||
Event event = new Event(5L, "New Event", Sets.newHashSet("guest"));
|
||||
session.save(event);
|
||||
}
|
||||
|
||||
private static void createEventGenerated() {
|
||||
EventGeneratedId eventGeneratedId = new EventGeneratedId("John", "Doe");
|
||||
eventGeneratedId.setId(4L);
|
||||
session.save(eventGeneratedId);
|
||||
}
|
||||
|
||||
}
|
||||
|
11
testing/src/main/java/com/baeldung/junit/Calculator.java
Normal file
11
testing/src/main/java/com/baeldung/junit/Calculator.java
Normal file
@ -0,0 +1,11 @@
|
||||
package com.baeldung.junit;
|
||||
|
||||
public class Calculator {
|
||||
public int add(int a, int b) {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
public int sub(int a, int b) {
|
||||
return a - b;
|
||||
}
|
||||
}
|
14
testing/src/test/java/com/baeldung/junit/AdditionTest.java
Normal file
14
testing/src/test/java/com/baeldung/junit/AdditionTest.java
Normal file
@ -0,0 +1,14 @@
|
||||
package com.baeldung.junit;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class AdditionTest {
|
||||
Calculator calculator = new Calculator();
|
||||
|
||||
@Test
|
||||
public void testAddition() {
|
||||
assertEquals("addition", 8, calculator.add(5, 3));
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.baeldung.junit;
|
||||
|
||||
import org.junit.runners.BlockJUnit4ClassRunner;
|
||||
import org.junit.runners.model.FrameworkMethod;
|
||||
import org.junit.runners.model.InitializationError;
|
||||
import org.junit.runners.model.Statement;
|
||||
|
||||
public class BlockingTestRunner extends BlockJUnit4ClassRunner {
|
||||
public BlockingTestRunner(Class<?> klass) throws InitializationError {
|
||||
super(klass);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Statement methodInvoker(FrameworkMethod method, Object test) {
|
||||
System.out.println("invoking: " + method.getName());
|
||||
return super.methodInvoker(method, test);
|
||||
}
|
||||
}
|
17
testing/src/test/java/com/baeldung/junit/CalculatorTest.java
Normal file
17
testing/src/test/java/com/baeldung/junit/CalculatorTest.java
Normal file
@ -0,0 +1,17 @@
|
||||
package com.baeldung.junit;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class CalculatorTest {
|
||||
Calculator calculator = new Calculator();
|
||||
|
||||
@Test
|
||||
public void testAddition() {
|
||||
assertEquals("addition", 8, calculator.add(5, 3));
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.junit;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class SubstractionTest {
|
||||
Calculator calculator = new Calculator();
|
||||
|
||||
@Test
|
||||
public void substraction() {
|
||||
assertEquals("substraction", 2, calculator.sub(5, 3));
|
||||
}
|
||||
}
|
12
testing/src/test/java/com/baeldung/junit/SuiteTest.java
Normal file
12
testing/src/test/java/com/baeldung/junit/SuiteTest.java
Normal file
@ -0,0 +1,12 @@
|
||||
package com.baeldung.junit;
|
||||
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.Suite;
|
||||
import org.junit.runners.Suite.SuiteClasses;
|
||||
|
||||
@RunWith(Suite.class)
|
||||
@SuiteClasses({
|
||||
AdditionTest.class,
|
||||
SubstractionTest.class})
|
||||
public class SuiteTest {
|
||||
}
|
41
testing/src/test/java/com/baeldung/junit/TestRunner.java
Normal file
41
testing/src/test/java/com/baeldung/junit/TestRunner.java
Normal file
@ -0,0 +1,41 @@
|
||||
package com.baeldung.junit;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.Description;
|
||||
import org.junit.runner.Runner;
|
||||
import org.junit.runner.notification.RunNotifier;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
public class TestRunner extends Runner {
|
||||
|
||||
private Class testClass;
|
||||
public TestRunner(Class testClass) {
|
||||
super();
|
||||
this.testClass = testClass;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Description getDescription() {
|
||||
return Description.createTestDescription(testClass, "My runner description");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(RunNotifier notifier) {
|
||||
System.out.println("running the tests from MyRunner: " + testClass);
|
||||
try {
|
||||
Object testObject = testClass.newInstance();
|
||||
for (Method method : testClass.getMethods()) {
|
||||
if (method.isAnnotationPresent(Test.class)) {
|
||||
notifier.fireTestStarted(Description
|
||||
.createTestDescription(testClass, method.getName()));
|
||||
method.invoke(testObject);
|
||||
notifier.fireTestFinished(Description
|
||||
.createTestDescription(testClass, method.getName()));
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user