Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Jose Carvajal 2017-10-08 08:15:44 +02:00
commit 310088914c
24 changed files with 974 additions and 68 deletions

View File

@ -0,0 +1,256 @@
package com.baeldung.apachecayenne;
import com.baeldung.apachecayenne.persistent.Author;
import org.apache.cayenne.ObjectContext;
import org.apache.cayenne.QueryResponse;
import org.apache.cayenne.configuration.server.ServerRuntime;
import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
import org.apache.cayenne.query.*;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class CayenneAdvancedOperationTests {
private static ObjectContext context = null;
@BeforeClass
public static void setupTheCayenneContext() {
ServerRuntime cayenneRuntime = ServerRuntime.builder()
.addConfig("cayenne-project.xml")
.build();
context = cayenneRuntime.newContext();
}
@Before
public void saveThreeAuthors() {
Author authorOne = context.newObject(Author.class);
authorOne.setName("Paul Xavier");
Author authorTwo = context.newObject(Author.class);
authorTwo.setName("pAuL Smith");
Author authorThree = context.newObject(Author.class);
authorThree.setName("Vicky Sarra");
context.commitChanges();
}
@After
public void deleteAllAuthors() {
SQLTemplate deleteAuthors = new SQLTemplate(Author.class, "delete from author");
context.performGenericQuery(deleteAuthors);
}
@Test
public void givenAuthors_whenFindAllSQLTmplt_thenWeGetThreeAuthors() {
SQLTemplate select = new SQLTemplate(Author.class, "select * from Author");
List<Author> authors = context.performQuery(select);
assertEquals(authors.size(), 3);
}
@Test
public void givenAuthors_whenFindByNameSQLTmplt_thenWeGetOneAuthor() {
SQLTemplate select = new SQLTemplate(Author.class, "select * from Author where name = 'Vicky Sarra'");
List<Author> authors = context.performQuery(select);
Author author = authors.get(0);
assertEquals(authors.size(), 1);
assertEquals(author.getName(), "Vicky Sarra");
}
@Test
public void givenAuthors_whenLikeSltQry_thenWeGetOneAuthor() {
Expression qualifier = ExpressionFactory.likeExp(Author.NAME.getName(), "Paul%");
SelectQuery query = new SelectQuery(Author.class, qualifier);
List<Author> authorsTwo = context.performQuery(query);
assertEquals(authorsTwo.size(), 1);
}
@Test
public void givenAuthors_whenCtnsIgnorCaseSltQry_thenWeGetTwoAuthors() {
Expression qualifier = ExpressionFactory.containsIgnoreCaseExp(Author.NAME.getName(), "Paul");
SelectQuery query = new SelectQuery(Author.class, qualifier);
List<Author> authors = context.performQuery(query);
assertEquals(authors.size(), 2);
}
@Test
public void givenAuthors_whenCtnsIgnorCaseEndsWSltQry_thenWeGetTwoAuthors() {
Expression qualifier = ExpressionFactory.containsIgnoreCaseExp(Author.NAME.getName(), "Paul")
.andExp(ExpressionFactory.endsWithExp(Author.NAME.getName(), "h"));
SelectQuery query = new SelectQuery(Author.class, qualifier);
List<Author> authors = context.performQuery(query);
Author author = authors.get(0);
assertEquals(authors.size(), 1);
assertEquals(author.getName(), "pAuL Smith");
}
@Test
public void givenAuthors_whenAscOrderingSltQry_thenWeGetOrderedAuthors() {
SelectQuery query = new SelectQuery(Author.class);
query.addOrdering(Author.NAME.asc());
List<Author> authors = query.select(context);
Author firstAuthor = authors.get(0);
assertEquals(authors.size(), 3);
assertEquals(firstAuthor.getName(), "Paul Xavier");
}
@Test
public void givenAuthors_whenDescOrderingSltQry_thenWeGetOrderedAuthors() {
SelectQuery query = new SelectQuery(Author.class);
query.addOrdering(Author.NAME.desc());
List<Author> authors = query.select(context);
Author firstAuthor = authors.get(0);
assertEquals(authors.size(), 3);
assertEquals(firstAuthor.getName(), "pAuL Smith");
}
@Test
public void givenAuthors_onContainsObjS_thenWeGetOneRecord() {
List<Author> authors = ObjectSelect.query(Author.class)
.where(Author.NAME.contains("Paul"))
.select(context);
assertEquals(authors.size(), 1);
}
@Test
public void givenAuthors_whenLikeObjS_thenWeGetTwoAuthors() {
List<Author> authors = ObjectSelect.query(Author.class)
.where(Author.NAME.likeIgnoreCase("Paul%"))
.select(context);
assertEquals(authors.size(), 2);
}
@Test
public void givenTwoAuthor_whenEndsWithObjS_thenWeGetOrderedAuthors() {
List<Author> authors = ObjectSelect.query(Author.class)
.where(Author.NAME.endsWith("Sarra"))
.select(context);
Author firstAuthor = authors.get(0);
assertEquals(authors.size(), 1);
assertEquals(firstAuthor.getName(), "Vicky Sarra");
}
@Test
public void givenTwoAuthor_whenInObjS_thenWeGetAuthors() {
String [] args = {"Paul Xavier", "pAuL Smith", "Vicky Sarra"};
List<Author> authors = ObjectSelect.query(Author.class)
.where(Author.NAME.in(Arrays.asList(args)))
.select(context);
assertEquals(authors.size(), 3);
}
@Test
public void givenTwoAuthor_whenNinObjS_thenWeGetAuthors() {
String [] args = {"Paul Xavier", "pAuL Smith"};
List<Author> authors = ObjectSelect.query(Author.class)
.where(Author.NAME.nin(Arrays.asList(args)))
.select(context);
Author author = authors.get(0);
assertEquals(authors.size(), 1);
assertEquals(author.getName(), "Vicky Sarra");
}
@Test
public void givenTwoAuthor_whenIsNotNullObjS_thenWeGetAuthors() {
List<Author> authors = ObjectSelect.query(Author.class)
.where(Author.NAME.isNotNull())
.select(context);
assertEquals(authors.size(), 3);
}
@Test
public void givenAuthors_whenFindAllEJBQL_thenWeGetThreeAuthors() {
EJBQLQuery query = new EJBQLQuery("select a FROM Author a");
List<Author> authors = context.performQuery(query);
assertEquals(authors.size(), 3);
}
@Test
public void givenAuthors_whenFindByNameEJBQL_thenWeGetOneAuthor() {
EJBQLQuery query = new EJBQLQuery("select a FROM Author a WHERE a.name = 'Vicky Sarra'");
List<Author> authors = context.performQuery(query);
Author author = authors.get(0);
assertEquals(authors.size(), 1);
assertEquals(author.getName(), "Vicky Sarra");
}
@Test
public void givenAuthors_whenUpdadingByNameEJBQL_thenWeGetTheUpdatedAuthor() {
EJBQLQuery query = new EJBQLQuery("UPDATE Author AS a SET a.name = 'Vicky Edison' WHERE a.name = 'Vicky Sarra'");
QueryResponse queryResponse = context.performGenericQuery(query);
EJBQLQuery queryUpdatedAuthor = new EJBQLQuery("select a FROM Author a WHERE a.name = 'Vicky Edison'");
List<Author> authors = context.performQuery(queryUpdatedAuthor);
Author author = authors.get(0);
assertNotNull(author);
}
@Test
public void givenAuthors_whenSeletingNamesEJBQL_thenWeGetListWithSizeThree() {
String [] args = {"Paul Xavier", "pAuL Smith", "Vicky Sarra"};
List<String> names = Arrays.asList(args);
EJBQLQuery query = new EJBQLQuery("select a.name FROM Author a");
List<String> nameList = context.performQuery(query);
Collections.sort(names);
Collections.sort(nameList);
assertEquals(names.size(), 3);
assertEquals(nameList.size(), 3);
assertEquals(names, nameList);
}
@Test
public void givenAuthors_whenDeletingAllWithEJB_thenWeGetNoAuthor() {
EJBQLQuery deleteQuery = new EJBQLQuery("delete FROM Author");
EJBQLQuery findAllQuery = new EJBQLQuery("select a FROM Author a");
context.performQuery(deleteQuery);
List<Author> objects = context.performQuery(findAllQuery);
assertEquals(objects.size(), 0);
}
@Test
public void givenAuthors_whenInsertingSQLExec_thenWeGetNewAuthor() {
int inserted = SQLExec
.query("INSERT INTO Author (name) VALUES ('Baeldung')")
.update(context);
assertEquals(inserted, 1);
}
@Test
public void givenAuthors_whenUpdatingSQLExec_thenItsUpdated() {
int updated = SQLExec
.query("UPDATE Author SET name = 'Baeldung' WHERE name = 'Vicky Sarra'")
.update(context);
assertEquals(updated, 1);
}
}

View 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;
}
}

View 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;
}
}

View 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;
}
}

View File

@ -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());
}
}

View File

@ -0,0 +1 @@
org.baeldung.valueextractors.ProfileValueExtractor

View File

@ -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());
}
}

View File

@ -1,6 +1,6 @@
<?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">
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>
@ -583,7 +583,23 @@
<dependency>
<groupId>com.atlassian.fugue</groupId>
<artifactId>fugue</artifactId>
<version>3.0.0-m007</version>
<version>2.6.1</version>
</dependency>
<!-- Uncomment this in order to use the jira-rest-java-client-core API -->
<!-- <dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency> -->
<dependency>
<groupId>org.jgrapht</groupId>
<artifactId>jgrapht-core</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>com.netopyr.wurmloch</groupId>
<artifactId>wurmloch-crdt</artifactId>
<version>${crdt.version}</version>
</dependency>
</dependencies>
<repositories>
@ -606,6 +622,7 @@
</repository>
</repositories>
<properties>
<crdt.version>0.1.0</crdt.version>
<multiverse.version>0.7.0</multiverse.version>
<cglib.version>3.2.4</cglib.version>
<commons-lang.version>3.6</commons-lang.version>
@ -658,6 +675,6 @@
<protonpack.version>1.14</protonpack.version>
<unit-ri.version>1.0.3</unit-ri.version>
<cache.version>1.0.0</cache.version>
<hazelcast.version>3.8.4</hazelcast.version>
<hazelcast.version>3.8.4</hazelcast.version>
</properties>
</project>

View File

@ -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
}

View File

@ -1,57 +0,0 @@
package com.baeldung.jira;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.JiraRestClientFactory;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class JiraClient {
private static final String USERNAME = "jira.user";
private static final String PASSWORD = "secret";
private static final String JIRA_URL = "http://jira.company.com";
public static void main(String[] args) {
final Issue issue = new JiraClient().getIssue("MYKEY-1234");
System.out.println(issue.getDescription());
}
private Issue getIssue(String issueKey) {
JiraRestClient restClient = getJiraRestClient();
Issue issue = restClient.getIssueClient().getIssue(issueKey).claim();
closeRestClient(restClient);
return issue;
}
private JiraRestClient getJiraRestClient() {
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
URI jiraServerUri = getJiraUri();
return factory
.createWithBasicHttpAuthentication(jiraServerUri, USERNAME, PASSWORD);
}
private URI getJiraUri() {
URI jiraServerUri = null;
try {
jiraServerUri = new URI(JIRA_URL);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return jiraServerUri;
}
private void closeRestClient(JiraRestClient restClient) {
try {
restClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,103 @@
package com.baeldung.jira;
import com.atlassian.jira.rest.client.api.IssueRestClient;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.domain.BasicVotes;
import com.atlassian.jira.rest.client.api.domain.Comment;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.api.domain.input.IssueInput;
import com.atlassian.jira.rest.client.api.domain.input.IssueInputBuilder;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
public class MyJiraClient {
private String username;
private String password;
private String jiraUrl;
private JiraRestClient restClient;
private MyJiraClient(String username, String password, String jiraUrl) {
this.username = username;
this.password = password;
this.jiraUrl = jiraUrl;
this.restClient = getJiraRestClient();
}
public static void main(String[] args) throws IOException {
MyJiraClient myJiraClient = new MyJiraClient("user.name", "pass", "http://jira.company.com");
final String issueKey = myJiraClient.createIssue("ABCD", 1L, "Issue created from JRJC");
myJiraClient.updateIssueDescription(issueKey, "This is description from my Jira Client");
Issue issue = myJiraClient.getIssue(issueKey);
System.out.println(issue.getDescription());
myJiraClient.voteForAnIssue(issue);
System.out.println(myJiraClient.getTotalVotesCount(issueKey));
myJiraClient.addComment(issue, "This is comment from my Jira Client");
List<Comment> comments = myJiraClient.getAllComments(issueKey);
comments.forEach(c -> System.out.println(c.getBody()));
myJiraClient.deleteIssue(issueKey, true);
myJiraClient.restClient.close();
}
public String createIssue(String projectKey, Long issueType, String issueSummary) {
IssueRestClient issueClient = restClient.getIssueClient();
IssueInput newIssue = new IssueInputBuilder(projectKey, issueType, issueSummary).build();
return issueClient.createIssue(newIssue).claim().getKey();
}
private Issue getIssue(String issueKey) {
return restClient.getIssueClient().getIssue(issueKey).claim();
}
public void voteForAnIssue(Issue issue) {
restClient.getIssueClient().vote(issue.getVotesUri()).claim();
}
public int getTotalVotesCount(String issueKey) {
BasicVotes votes = getIssue(issueKey).getVotes();
return votes == null ? 0 : votes.getVotes();
}
public void addComment(Issue issue, String commentBody) {
restClient.getIssueClient().addComment(issue.getCommentsUri(), Comment.valueOf(commentBody));
}
public List<Comment> getAllComments(String issueKey) {
return StreamSupport.stream(getIssue(issueKey).getComments().spliterator(), false)
.collect(Collectors.toList());
}
public void updateIssueDescription(String issueKey, String newDescription) {
IssueInput input = new IssueInputBuilder().setDescription(newDescription).build();
restClient.getIssueClient().updateIssue(issueKey, input).claim();
}
public void deleteIssue(String issueKey, boolean deleteSubtasks) {
restClient.getIssueClient().deleteIssue(issueKey, deleteSubtasks).claim();
}
private JiraRestClient getJiraRestClient() {
return new AsynchronousJiraRestClientFactory()
.createWithBasicHttpAuthentication(getJiraUri(), this.username, this.password);
}
private URI getJiraUri() {
return URI.create(this.jiraUrl);
}
}

View File

@ -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());
}
}

View File

@ -0,0 +1,153 @@
package com.baeldung.crdt;
import com.netopyr.wurmloch.crdt.GCounter;
import com.netopyr.wurmloch.crdt.GSet;
import com.netopyr.wurmloch.crdt.LWWRegister;
import com.netopyr.wurmloch.crdt.PNCounter;
import com.netopyr.wurmloch.store.LocalCrdtStore;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class CRDTTest {
@Test
public void givenGrowOnlySet_whenTwoReplicasDiverge_thenShouldMergeItWithoutAConflict() {
//given
final LocalCrdtStore crdtStore1 = new LocalCrdtStore();
final LocalCrdtStore crdtStore2 = new LocalCrdtStore();
crdtStore1.connect(crdtStore2);
final GSet<String> replica1 = crdtStore1.createGSet("ID_1");
final GSet<String> replica2 = crdtStore2.<String>findGSet("ID_1").get();
//when
replica1.add("apple");
replica2.add("banana");
//then
assertThat(replica1).contains("apple", "banana");
assertThat(replica2).contains("apple", "banana");
//when
crdtStore1.disconnect(crdtStore2);
replica1.add("strawberry");
replica2.add("pear");
assertThat(replica1).contains("apple", "banana", "strawberry");
assertThat(replica2).contains("apple", "banana", "pear");
crdtStore1.connect(crdtStore2);
//then
assertThat(replica1).contains("apple", "banana", "strawberry", "pear");
assertThat(replica2).contains("apple", "banana", "strawberry", "pear");
}
@Test
public void givenIncrementOnlyCounter_whenTwoReplicasDiverge_thenShouldMergeIt() {
//given
final LocalCrdtStore crdtStore1 = new LocalCrdtStore();
final LocalCrdtStore crdtStore2 = new LocalCrdtStore();
crdtStore1.connect(crdtStore2);
final GCounter replica1 = crdtStore1.createGCounter("ID_1");
final GCounter replica2 = crdtStore2.findGCounter("ID_1").get();
//when
replica1.increment();
replica2.increment(2L);
//then
assertThat(replica1.get()).isEqualTo(3L);
assertThat(replica2.get()).isEqualTo(3L);
//when
crdtStore1.disconnect(crdtStore2);
replica1.increment(3L);
replica2.increment(5L);
assertThat(replica1.get()).isEqualTo(6L);
assertThat(replica2.get()).isEqualTo(8L);
crdtStore1.connect(crdtStore2);
// then
assertThat(replica1.get()).isEqualTo(11L);
assertThat(replica2.get()).isEqualTo(11L);
}
@Test
public void givenPNCounter_whenReplicasDiverge_thenShouldMergeWithoutAConflict() {
// given
final LocalCrdtStore crdtStore1 = new LocalCrdtStore();
final LocalCrdtStore crdtStore2 = new LocalCrdtStore();
crdtStore1.connect(crdtStore2);
final PNCounter replica1 = crdtStore1.createPNCounter("ID_1");
final PNCounter replica2 = crdtStore2.findPNCounter("ID_1").get();
//when
replica1.increment();
replica2.decrement(2L);
//then
assertThat(replica1.get()).isEqualTo(-1L);
assertThat(replica2.get()).isEqualTo(-1L);
//when
crdtStore1.disconnect(crdtStore2);
replica1.decrement(3L);
replica2.increment(5L);
assertThat(replica1.get()).isEqualTo(-4L);
assertThat(replica2.get()).isEqualTo(4L);
crdtStore1.connect(crdtStore2);
//then
assertThat(replica1.get()).isEqualTo(1L);
assertThat(replica2.get()).isEqualTo(1L);
}
@Test
public void givenLastWriteWinsStrategy_whenReplicasDiverge_thenAfterMergeShouldKeepOnlyLastValue() {
//given
final LocalCrdtStore crdtStore1 = new LocalCrdtStore("N_1");
final LocalCrdtStore crdtStore2 = new LocalCrdtStore("N_2");
crdtStore1.connect(crdtStore2);
final LWWRegister<String> replica1 = crdtStore1.createLWWRegister("ID_1");
final LWWRegister<String> replica2 = crdtStore2.<String>findLWWRegister("ID_1").get();
//when
replica1.set("apple");
replica2.set("banana");
// then
assertThat(replica1.get()).isEqualTo("banana");
assertThat(replica2.get()).isEqualTo("banana");
// when
crdtStore1.disconnect(crdtStore2);
replica1.set("strawberry");
replica2.set("pear");
assertThat(replica1.get()).isEqualTo("strawberry");
assertThat(replica2.get()).isEqualTo("pear");
crdtStore1.connect(crdtStore2);
//then
assertThat(replica1.get()).isEqualTo("pear");
assertThat(replica2.get()).isEqualTo("pear");
}
}

View File

@ -0,0 +1,57 @@
package org.baeldung.mockito;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.mockito.Mockito;
public class MockitoExceptionIntegrationTest {
@Test(expected = NullPointerException.class)
public void whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class);
dictMock.getMeaning("word");
}
@Test(expected = IllegalStateException.class)
public void whenConfigVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
doThrow(IllegalStateException.class).when(dictMock)
.add(anyString(), anyString());
dictMock.add("word", "meaning");
}
@Test(expected = NullPointerException.class)
public void whenConfigNonVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred"));
dictMock.getMeaning("word");
}
@Test(expected = IllegalStateException.class)
public void whenConfigVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
doThrow(new IllegalStateException("Error occurred")).when(dictMock)
.add(anyString(), anyString());
dictMock.add("word", "meaning");
}
// =====
@Test(expected = NullPointerException.class)
public void givenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dict = new MyDictionary();
MyDictionary spy = Mockito.spy(dict);
when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class);
spy.getMeaning("word");
}
}

View File

@ -8,4 +8,3 @@
- [Spring YAML Configuration](http://www.baeldung.com/spring-yaml)
- [Introduction to Springs StreamUtils](http://www.baeldung.com/spring-stream-utils)
- [Using Spring @Value with Defaults](http://www.baeldung.com/spring-value-defaults)

View 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;
}
}

View 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));
}
}

View File

@ -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);
}
}

View 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));
}
}

View File

@ -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));
}
}

View 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 {
}

View 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);
}
}
}

View File

@ -9,8 +9,9 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
<relativePath />
<version>1.5.6.RELEASE</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<dependencies>
@ -39,6 +40,7 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>

View File

@ -43,5 +43,4 @@ public class VavrRepositoryIntegrationTest {
Seq<User> users = userRepository.findByName("John");
assertEquals(2, users.size());
}
}