diff --git a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationTests.java b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationTests.java new file mode 100644 index 0000000000..ddfe9325d3 --- /dev/null +++ b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationTests.java @@ -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 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 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 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 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 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 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 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 authors = ObjectSelect.query(Author.class) + .where(Author.NAME.contains("Paul")) + .select(context); + + assertEquals(authors.size(), 1); + } + + @Test + public void givenAuthors_whenLikeObjS_thenWeGetTwoAuthors() { + List authors = ObjectSelect.query(Author.class) + .where(Author.NAME.likeIgnoreCase("Paul%")) + .select(context); + + assertEquals(authors.size(), 2); + } + + @Test + public void givenTwoAuthor_whenEndsWithObjS_thenWeGetOrderedAuthors() { + List 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 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 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 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 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 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 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 names = Arrays.asList(args); + EJBQLQuery query = new EJBQLQuery("select a.name FROM Author a"); + List 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 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); + } +} diff --git a/javaxval/src/main/java/org/baeldung/Customer.java b/javaxval/src/main/java/org/baeldung/Customer.java new file mode 100644 index 0000000000..a90fb419de --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/Customer.java @@ -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 getAddresses() { + return addresses; + } + + public void setAddresses(List 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; + } + +} diff --git a/javaxval/src/main/java/org/baeldung/CustomerMap.java b/javaxval/src/main/java/org/baeldung/CustomerMap.java new file mode 100644 index 0000000000..37446cf86e --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/CustomerMap.java @@ -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 getCustomers() { + return customers; + } + + public void setCustomers(Map customers) { + this.customers = customers; + } +} diff --git a/javaxval/src/main/java/org/baeldung/Profile.java b/javaxval/src/main/java/org/baeldung/Profile.java new file mode 100644 index 0000000000..ec73a5c62f --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/Profile.java @@ -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; + } +} diff --git a/javaxval/src/main/java/org/baeldung/valueextractors/ProfileValueExtractor.java b/javaxval/src/main/java/org/baeldung/valueextractors/ProfileValueExtractor.java new file mode 100644 index 0000000000..f192034261 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/valueextractors/ProfileValueExtractor.java @@ -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()); + } + +} diff --git a/javaxval/src/main/resources/META-INF/services/javax.validation.valueextraction.ValueExtractor b/javaxval/src/main/resources/META-INF/services/javax.validation.valueextraction.ValueExtractor new file mode 100644 index 0000000000..e77a30cfe4 --- /dev/null +++ b/javaxval/src/main/resources/META-INF/services/javax.validation.valueextraction.ValueExtractor @@ -0,0 +1 @@ +org.baeldung.valueextractors.ProfileValueExtractor \ No newline at end of file diff --git a/javaxval/src/test/java/org/baeldung/ContainerValidationIntegrationTest.java b/javaxval/src/test/java/org/baeldung/ContainerValidationIntegrationTest.java new file mode 100644 index 0000000000..dff02ff13d --- /dev/null +++ b/javaxval/src/test/java/org/baeldung/ContainerValidationIntegrationTest.java @@ -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> 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> 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> violations = validator.validate(customer); + assertEquals(1, violations.size()); + } + + @Test + public void whenAgeNull_thenValidationSucceeds() { + Customer customer = new Customer(); + customer.setName("John"); + Set> 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> 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> violations = validator.validate(customer); + assertEquals(1, violations.size()); + } + +} diff --git a/libraries/pom.xml b/libraries/pom.xml index 97ddff96ec..15446975f3 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> parent-modules com.baeldung @@ -487,7 +487,7 @@ vavr ${vavr.version} - + com.squareup.retrofit2 @@ -503,7 +503,7 @@ com.squareup.retrofit2 adapter-rxjava ${retrofit.version} - + com.squareup.okhttp3 logging-interceptor @@ -583,7 +583,23 @@ com.atlassian.fugue fugue - 3.0.0-m007 + 2.6.1 + + + + + org.jgrapht + jgrapht-core + 1.0.1 + + + com.netopyr.wurmloch + wurmloch-crdt + ${crdt.version} @@ -606,6 +622,7 @@ + 0.1.0 0.7.0 3.2.4 3.6 @@ -658,6 +675,6 @@ 1.14 1.0.3 1.0.0 - 3.8.4 + 3.8.4 diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java b/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java index c64f7e7511..35cae7426d 100644 --- a/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java +++ b/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java @@ -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{ + + @Override + protected String initialize() throws Exception { + return null; + } + + // Any complex task that takes some time + +} diff --git a/libraries/src/main/java/com/baeldung/jira/JiraClient.java b/libraries/src/main/java/com/baeldung/jira/JiraClient.java deleted file mode 100644 index 26df21c8a9..0000000000 --- a/libraries/src/main/java/com/baeldung/jira/JiraClient.java +++ /dev/null @@ -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(); - } - } -} diff --git a/libraries/src/main/java/com/baeldung/jira/MyJiraClient.java b/libraries/src/main/java/com/baeldung/jira/MyJiraClient.java new file mode 100644 index 0000000000..62cce56532 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jira/MyJiraClient.java @@ -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 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 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); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsTest.java index af70ccecc7..29bcebeb2b 100644 --- a/libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsTest.java +++ b/libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsTest.java @@ -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()); + + } } diff --git a/libraries/src/test/java/com/baeldung/crdt/CRDTTest.java b/libraries/src/test/java/com/baeldung/crdt/CRDTTest.java new file mode 100644 index 0000000000..8309e755ce --- /dev/null +++ b/libraries/src/test/java/com/baeldung/crdt/CRDTTest.java @@ -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 replica1 = crdtStore1.createGSet("ID_1"); + final GSet replica2 = crdtStore2.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 replica1 = crdtStore1.createLWWRegister("ID_1"); + final LWWRegister replica2 = crdtStore2.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"); + } +} diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoExceptionIntegrationTest.java b/mockito/src/test/java/org/baeldung/mockito/MockitoExceptionIntegrationTest.java new file mode 100644 index 0000000000..9a25ccb28c --- /dev/null +++ b/mockito/src/test/java/org/baeldung/mockito/MockitoExceptionIntegrationTest.java @@ -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"); + } +} diff --git a/spring-core/README.md b/spring-core/README.md index 237f8cd4e9..81a7aaa952 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -8,4 +8,3 @@ - [Spring YAML Configuration](http://www.baeldung.com/spring-yaml) - [Introduction to Spring’s StreamUtils](http://www.baeldung.com/spring-stream-utils) - [Using Spring @Value with Defaults](http://www.baeldung.com/spring-value-defaults) - diff --git a/testing/src/main/java/com/baeldung/junit/Calculator.java b/testing/src/main/java/com/baeldung/junit/Calculator.java new file mode 100644 index 0000000000..8ea7b3ed1f --- /dev/null +++ b/testing/src/main/java/com/baeldung/junit/Calculator.java @@ -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; + } +} diff --git a/testing/src/test/java/com/baeldung/junit/AdditionTest.java b/testing/src/test/java/com/baeldung/junit/AdditionTest.java new file mode 100644 index 0000000000..0d492f8058 --- /dev/null +++ b/testing/src/test/java/com/baeldung/junit/AdditionTest.java @@ -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)); + } +} diff --git a/testing/src/test/java/com/baeldung/junit/BlockingTestRunner.java b/testing/src/test/java/com/baeldung/junit/BlockingTestRunner.java new file mode 100644 index 0000000000..432d5cda83 --- /dev/null +++ b/testing/src/test/java/com/baeldung/junit/BlockingTestRunner.java @@ -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); + } +} diff --git a/testing/src/test/java/com/baeldung/junit/CalculatorTest.java b/testing/src/test/java/com/baeldung/junit/CalculatorTest.java new file mode 100644 index 0000000000..d1b35d1442 --- /dev/null +++ b/testing/src/test/java/com/baeldung/junit/CalculatorTest.java @@ -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)); + } +} diff --git a/testing/src/test/java/com/baeldung/junit/SubstractionTest.java b/testing/src/test/java/com/baeldung/junit/SubstractionTest.java new file mode 100644 index 0000000000..9650d83afe --- /dev/null +++ b/testing/src/test/java/com/baeldung/junit/SubstractionTest.java @@ -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)); + } +} diff --git a/testing/src/test/java/com/baeldung/junit/SuiteTest.java b/testing/src/test/java/com/baeldung/junit/SuiteTest.java new file mode 100644 index 0000000000..428319e72e --- /dev/null +++ b/testing/src/test/java/com/baeldung/junit/SuiteTest.java @@ -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 { +} diff --git a/testing/src/test/java/com/baeldung/junit/TestRunner.java b/testing/src/test/java/com/baeldung/junit/TestRunner.java new file mode 100644 index 0000000000..9eb4b3141b --- /dev/null +++ b/testing/src/test/java/com/baeldung/junit/TestRunner.java @@ -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); + } + } +} diff --git a/vavr/pom.xml b/vavr/pom.xml index 2efaf7fd8c..878430611b 100644 --- a/vavr/pom.xml +++ b/vavr/pom.xml @@ -5,12 +5,13 @@ vavr 1.0 vavr - + org.springframework.boot spring-boot-starter-parent - 2.0.0.BUILD-SNAPSHOT - + 1.5.6.RELEASE + + @@ -35,10 +36,11 @@ com.h2database h2 - + org.springframework.boot spring-boot-starter-test + test diff --git a/vavr/src/test/java/com/baeldung/vavr/repositories/VavrRepositoryIntegrationTest.java b/vavr/src/test/java/com/baeldung/vavr/repositories/VavrRepositoryIntegrationTest.java index 63338afc24..7c00d46aa8 100644 --- a/vavr/src/test/java/com/baeldung/vavr/repositories/VavrRepositoryIntegrationTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/repositories/VavrRepositoryIntegrationTest.java @@ -43,5 +43,4 @@ public class VavrRepositoryIntegrationTest { Seq users = userRepository.findByName("John"); assertEquals(2, users.size()); } - }