diff --git a/JGit/README.md b/JGit/README.md new file mode 100644 index 0000000000..5c65f1101b --- /dev/null +++ b/JGit/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [A Guide to JGit](http://www.baeldung.com/jgit) diff --git a/algorithms/README.md b/algorithms/README.md new file mode 100644 index 0000000000..4789768fad --- /dev/null +++ b/algorithms/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Dijkstra Algorithm in Java](http://www.baeldung.com/java-dijkstra) diff --git a/algorithms/pom.xml b/algorithms/pom.xml index 0c85a19534..f72457650a 100644 --- a/algorithms/pom.xml +++ b/algorithms/pom.xml @@ -41,4 +41,23 @@ - \ No newline at end of file + + + + org.codehaus.mojo + cobertura-maven-plugin + 2.7 + + + + com/baeldung/algorithms/dijkstra/* + + + com/baeldung/algorithms/dijkstra/* + + + + + + + diff --git a/apache-bval/README.md b/apache-bval/README.md new file mode 100644 index 0000000000..80ea149993 --- /dev/null +++ b/apache-bval/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Intro to Apache BVal](http://www.baeldung.com/apache-bval) diff --git a/apache-bval/pom.xml b/apache-bval/pom.xml new file mode 100644 index 0000000000..5d556af56f --- /dev/null +++ b/apache-bval/pom.xml @@ -0,0 +1,51 @@ + + 4.0.0 + apache-bval + apache-bval + 0.0.1-SNAPSHOT + + + + org.apache.bval + bval-jsr + ${bval.version} + + + javax.validation + validation-api + 1.1.0.Final + + + org.apache.bval + bval-extras + ${bval.version} + + + + junit + junit + ${junit.version} + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + + 3.6.0 + 4.12 + 1.1.2 + + \ No newline at end of file diff --git a/apache-bval/src/main/java/com/baeldung/model/User.java b/apache-bval/src/main/java/com/baeldung/model/User.java new file mode 100644 index 0000000000..477136ddb4 --- /dev/null +++ b/apache-bval/src/main/java/com/baeldung/model/User.java @@ -0,0 +1,120 @@ +package com.baeldung.model; + +import java.io.File; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +import org.apache.bval.constraints.Email; +import org.apache.bval.constraints.NotEmpty; +import org.apache.bval.extras.constraints.checkdigit.IBAN; +import org.apache.bval.extras.constraints.creditcard.Visa; +import org.apache.bval.extras.constraints.file.Directory; +import org.apache.bval.extras.constraints.net.InetAddress; + +import com.baeldung.validation.Password; + +public class User { + @NotNull + @Email + private String email; + + @NotEmpty + @Password + private String password; + + @Size(min = 1, max = 20) + private String name; + + @Min(18) + private int age; + + @Visa + private String cardNumber = ""; + + @IBAN + private String iban = ""; + + @InetAddress + private String website = ""; + + @Directory + private File mainDirectory=new File("."); + + public User() { + } + + public User(String email, String password, String name, int age) { + super(); + this.email = email; + this.password = password; + this.name = name; + this.age = age; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getCardNumber() { + return cardNumber; + } + + public void setCardNumber(String cardNumber) { + this.cardNumber = cardNumber; + } + + public String getIban() { + return iban; + } + + public void setIban(String iban) { + this.iban = iban; + } + + public String getWebsite() { + return website; + } + + public void setWebsite(String website) { + this.website = website; + } + + public File getMainDirectory() { + return mainDirectory; + } + + public void setMainDirectory(File mainDirectory) { + this.mainDirectory = mainDirectory; + } + +} diff --git a/apache-bval/src/main/java/com/baeldung/validation/Password.java b/apache-bval/src/main/java/com/baeldung/validation/Password.java new file mode 100644 index 0000000000..4ae06b2fb0 --- /dev/null +++ b/apache-bval/src/main/java/com/baeldung/validation/Password.java @@ -0,0 +1,25 @@ +package com.baeldung.validation; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import javax.validation.Constraint; +import javax.validation.Payload; + +import static java.lang.annotation.ElementType.*; + +@Constraint(validatedBy = { PasswordValidator.class }) +@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) +@Retention(RetentionPolicy.RUNTIME) +public @interface Password { + String message() default "Invalid password"; + + Class[] groups() default {}; + + Class[] payload() default {}; + + int length() default 6; + + int nonAlpha() default 1; +} diff --git a/apache-bval/src/main/java/com/baeldung/validation/PasswordValidator.java b/apache-bval/src/main/java/com/baeldung/validation/PasswordValidator.java new file mode 100644 index 0000000000..19038d04d5 --- /dev/null +++ b/apache-bval/src/main/java/com/baeldung/validation/PasswordValidator.java @@ -0,0 +1,35 @@ +package com.baeldung.validation; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; + +public class PasswordValidator implements ConstraintValidator { + + private int length; + private int nonAlpha; + + @Override + public void initialize(Password password) { + this.length = password.length(); + this.nonAlpha = password.nonAlpha(); + + } + + @Override + public boolean isValid(String value, ConstraintValidatorContext context) { + if (value.length() < length) { + return false; + } + int nonAlphaNr = 0; + for (int i = 0; i < value.length(); i++) { + if (!Character.isLetterOrDigit(value.charAt(i))) { + nonAlphaNr++; + } + } + if (nonAlphaNr < nonAlpha) { + return false; + } + return true; + } + +} diff --git a/apache-bval/src/test/java/com/baeldung/validation/ValidationTest.java b/apache-bval/src/test/java/com/baeldung/validation/ValidationTest.java new file mode 100644 index 0000000000..cd58d4460a --- /dev/null +++ b/apache-bval/src/test/java/com/baeldung/validation/ValidationTest.java @@ -0,0 +1,97 @@ +package com.baeldung.validation; + +import java.io.File; +import java.util.Set; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + +import org.apache.bval.jsr.ApacheValidationProvider; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.*; + +import com.baeldung.model.User; + +public class ValidationTest { + private static ValidatorFactory validatorFactory; + private static Validator validator; + + @BeforeClass + public static void setup() { + validatorFactory = Validation.byProvider(ApacheValidationProvider.class) + .configure() + .buildValidatorFactory(); + validator = validatorFactory.getValidator(); + } + + @Test + public void givenUser_whenValidate_thenValidationViolations() { + User user = new User("ana@yahoo.com", "pass", "nameTooLong_______________", 15); + + Set> violations = validator.validate(user); + assertTrue("no violations", violations.size() > 0); + } + + @Test + public void givenInvalidAge_whenValidateProperty_thenConstraintViolation() { + User user = new User("ana@yahoo.com", "pass", "Ana", 12); + + Set> propertyViolations = validator.validateProperty(user, "age"); + assertEquals("size is not 1", 1, propertyViolations.size()); + } + + @Test + public void givenValidAge_whenValidateValue_thenNoConstraintViolation() { + User user = new User("ana@yahoo.com", "pass", "Ana", 18); + + Set> valueViolations = validator.validateValue(User.class, "age", 20); + assertEquals("size is not 0", 0, valueViolations.size()); + } + + @Test + public void whenValidateNonJSR_thenCorrect() { + User user = new User("ana@yahoo.com", "pass", "Ana", 20); + user.setCardNumber("1234"); + user.setIban("1234"); + user.setWebsite("10.0.2.50"); + user.setMainDirectory(new File(".")); + + Set> violations = validator.validateProperty(user, "iban"); + assertEquals("size is not 1", 1, violations.size()); + + violations = validator.validateProperty(user, "website"); + assertEquals("size is not 0", 0, violations.size()); + + violations = validator.validateProperty(user, "mainDirectory"); + assertEquals("size is not 0", 0, violations.size()); + } + + @Test + public void givenInvalidPassword_whenValidatePassword_thenConstraintViolation() { + User user = new User("ana@yahoo.com", "password", "Ana", 20); + Set> violations = validator.validateProperty(user, "password"); + assertEquals("message incorrect", "Invalid password", violations.iterator() + .next() + .getMessage()); + } + + @Test + public void givenValidPassword_whenValidatePassword_thenNoConstraintViolation() { + User user = new User("ana@yahoo.com", "password#", "Ana", 20); + + Set> violations = validator.validateProperty(user, "password"); + assertEquals("size is not 0", 0, violations.size()); + } + + @AfterClass + public static void close() { + if (validatorFactory != null) { + validatorFactory.close(); + } + } +} diff --git a/apache-solrj/pom.xml b/apache-solrj/pom.xml new file mode 100644 index 0000000000..74daeae55c --- /dev/null +++ b/apache-solrj/pom.xml @@ -0,0 +1,50 @@ + + 4.0.0 + com.baeldung + apache-solrj + 0.0.1-SNAPSHOT + jar + apache-solrj + + + 4.12 + 2.19.1 + + + + + org.apache.solr + solr-solrj + 6.4.0 + + + junit + junit + ${junit.version} + test + + + + + + + maven-compiler-plugin + 2.3.2 + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 1.8 + 1.8 + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + \ No newline at end of file diff --git a/apache-solrj/src/main/java/com/baeldung/solrjava/SolrJavaIntegration.java b/apache-solrj/src/main/java/com/baeldung/solrjava/SolrJavaIntegration.java new file mode 100644 index 0000000000..f2d21f0993 --- /dev/null +++ b/apache-solrj/src/main/java/com/baeldung/solrjava/SolrJavaIntegration.java @@ -0,0 +1,43 @@ +package com.baeldung.solrjava; + +import java.io.IOException; + +import org.apache.solr.client.solrj.SolrServerException; +import org.apache.solr.client.solrj.impl.HttpSolrClient; +import org.apache.solr.client.solrj.impl.XMLResponseParser; +import org.apache.solr.common.SolrInputDocument; + +public class SolrJavaIntegration { + + private HttpSolrClient solrClient; + + public SolrJavaIntegration(String clientUrl) { + + solrClient = new HttpSolrClient.Builder(clientUrl).build(); + solrClient.setParser(new XMLResponseParser()); + } + + public void addSolrDocument(String documentId, String itemName, String itemPrice) throws SolrServerException, IOException { + + SolrInputDocument document = new SolrInputDocument(); + document.addField("id", documentId); + document.addField("name", itemName); + document.addField("price", itemPrice); + solrClient.add(document); + solrClient.commit(); + } + + public void deleteSolrDocument(String documentId) throws SolrServerException, IOException { + + solrClient.deleteById(documentId); + solrClient.commit(); + } + + protected HttpSolrClient getSolrClient() { + return solrClient; + } + + protected void setSolrClient(HttpSolrClient solrClient) { + this.solrClient = solrClient; + } +} diff --git a/spring-data-solr/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java b/apache-solrj/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java similarity index 64% rename from spring-data-solr/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java rename to apache-solrj/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java index ce90ccaf16..22f9eae8ee 100644 --- a/spring-data-solr/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java +++ b/apache-solrj/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java @@ -6,32 +6,21 @@ import java.io.IOException; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; -import org.apache.solr.client.solrj.impl.HttpSolrClient; -import org.apache.solr.client.solrj.impl.XMLResponseParser; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; -import org.apache.solr.common.SolrInputDocument; import org.junit.Before; import org.junit.Test; public class SolrJavaIntegrationTest { - private HttpSolrClient solr; - private SolrInputDocument document; + private SolrJavaIntegration solrJavaIntegration; @Before public void setUp() throws Exception { - solr = new HttpSolrClient("http://localhost:8983/solr/bigboxstore"); - solr.setParser(new XMLResponseParser()); - - document = new SolrInputDocument(); - document.addField("id", "123456"); - document.addField("name", "Kenmore Dishwasher"); - document.addField("price", "599.99"); - solr.add(document); - solr.commit(); + solrJavaIntegration = new SolrJavaIntegration("http://localhost:8983/solr/bigboxstore"); + solrJavaIntegration.addSolrDocument("123456", "Kenmore Dishwasher", "599.99"); } @Test @@ -41,7 +30,7 @@ public class SolrJavaIntegrationTest { query.set("q", "id:123456"); QueryResponse response = null; - response = solr.query(query); + response = solrJavaIntegration.getSolrClient().query(query); SolrDocumentList docList = response.getResults(); assertEquals(docList.getNumFound(), 1); @@ -55,14 +44,13 @@ public class SolrJavaIntegrationTest { @Test public void whenDelete_thenVerifyDeleted() throws SolrServerException, IOException { - solr.deleteById("123456"); - solr.commit(); + solrJavaIntegration.deleteSolrDocument("123456"); SolrQuery query = new SolrQuery(); query.set("q", "id:123456"); QueryResponse response = null; - response = solr.query(query); + response = solrJavaIntegration.getSolrClient().query(query); SolrDocumentList docList = response.getResults(); assertEquals(docList.getNumFound(), 0); diff --git a/apache-thrift/README.md b/apache-thrift/README.md new file mode 100644 index 0000000000..d8b9195dcc --- /dev/null +++ b/apache-thrift/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Working with Apache Thrift](http://www.baeldung.com/apache-thrift) diff --git a/apache-velocity/README.md b/apache-velocity/README.md new file mode 100644 index 0000000000..53c67f847e --- /dev/null +++ b/apache-velocity/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Introduction to Apache Velocity](http://www.baeldung.com/apache-velocity) diff --git a/core-java-9/README.md b/core-java-9/README.md index 1b44239e40..53ad79e59c 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -6,3 +6,5 @@ ### Relevant Articles: - [Java 9 Stream API Improvements](http://www.baeldung.com/java-9-stream-api) +- [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods) +- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors) diff --git a/core-java/README.md b/core-java/README.md index 341dbdf910..a34908d8ae 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -58,3 +58,24 @@ - [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue) - [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch) - [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm) +- [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map) +- [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue) +- [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector) +- [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception) +- [Guide to WeakHashMap in Java](http://www.baeldung.com/java-weakhashmap) +- [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern) +- [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams) +- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool) +- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings) +- [Spring Security – Cache Control Headers](http://www.baeldung.com/spring-security-cache-control-headers) +- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions) +- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda) +- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn) +- [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions) +- [Guide to the Guava BiMap](http://www.baeldung.com/guava-bimap) +- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream) +- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany) +- [Chained Exceptions in Java](http://www.baeldung.com/java-chained-exceptions) +- [The Java HashMap Under the Hood](http://www.baeldung.com/java-hashmap) +- [A Guide to LinkedHashMap in Java](http://www.baeldung.com/java-linked-hashmap) +- [A Guide to TreeMap in Java](http://www.baeldung.com/java-treemap) diff --git a/core-java/src/test/java/com/baeldung/java/map/README.md b/core-java/src/test/java/com/baeldung/java/map/README.md deleted file mode 100644 index 0bba153763..0000000000 --- a/core-java/src/test/java/com/baeldung/java/map/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [The Java HashMap Under the Hood](http://www.baeldung.com/java-hashmap) diff --git a/core-java/src/test/java/com/baeldung/test/comparison/DivisibilityTest.java b/core-java/src/test/java/com/baeldung/junit4vstestng/DivisibilityTest.java similarity index 74% rename from core-java/src/test/java/com/baeldung/test/comparison/DivisibilityTest.java rename to core-java/src/test/java/com/baeldung/junit4vstestng/DivisibilityTest.java index 9ae13f5934..dec7dbe6aa 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/DivisibilityTest.java +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/DivisibilityTest.java @@ -1,4 +1,4 @@ -package com.baeldung.test.comparison; +package com.baeldung.junit4vstestng; import static org.junit.Assert.assertEquals; @@ -15,7 +15,7 @@ public class DivisibilityTest { } @Test - public void givenNumber_whenDivisiblebyTwo_thenCorrect() { + public void givenNumber_whenDivisibleByTwo_thenCorrect() { assertEquals(number % 2, 0); } } diff --git a/core-java/src/test/java/com/baeldung/junit4vstestng/ParametrizedTests.java b/core-java/src/test/java/com/baeldung/junit4vstestng/ParametrizedTests.java new file mode 100644 index 0000000000..e9a9c6a07a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/ParametrizedTests.java @@ -0,0 +1,34 @@ +package com.baeldung.junit4vstestng; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +import java.util.Arrays; +import java.util.Collection; + +@RunWith(value = Parameterized.class) +public class ParametrizedTests { + + private int value; + private boolean isEven; + + public ParametrizedTests(int value, boolean isEven) { + this.value = value; + this.isEven = isEven; + } + + @Parameters + public static Collection data() { + Object[][] data = new Object[][]{{1, false}, {2, true}, {4, true}}; + return Arrays.asList(data); + } + + @Test + public void givenParametrizedNumber_ifEvenCheckOK_thenCorrect() { + Assert.assertEquals(isEven, value % 2 == 0); + } +} diff --git a/core-java/src/test/java/com/baeldung/junit4vstestng/RegistrationTest.java b/core-java/src/test/java/com/baeldung/junit4vstestng/RegistrationTest.java new file mode 100644 index 0000000000..4aa1fa1a17 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/RegistrationTest.java @@ -0,0 +1,15 @@ +package com.baeldung.junit4vstestng; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class RegistrationTest { + private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationTest.class); + + @Test + public void whenCalledFromSuite_thanOK() { + LOGGER.info("Registration successful"); + } +} diff --git a/core-java/src/test/java/com/baeldung/junit4vstestng/SignInTest.java b/core-java/src/test/java/com/baeldung/junit4vstestng/SignInTest.java new file mode 100644 index 0000000000..bb908ff37e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/SignInTest.java @@ -0,0 +1,14 @@ +package com.baeldung.junit4vstestng; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SignInTest { + private static final Logger LOGGER = LoggerFactory.getLogger(SignInTest.class); + + @Test + public void whenCalledFromSuite_thanOK() { + LOGGER.info("SignIn successful"); + } +} diff --git a/core-java/src/test/java/com/baeldung/test/comparison/StringCaseTest.java b/core-java/src/test/java/com/baeldung/junit4vstestng/StringCaseTest.java similarity index 90% rename from core-java/src/test/java/com/baeldung/test/comparison/StringCaseTest.java rename to core-java/src/test/java/com/baeldung/junit4vstestng/StringCaseTest.java index b4226b82e7..520017e4c1 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/StringCaseTest.java +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/StringCaseTest.java @@ -1,4 +1,4 @@ -package com.baeldung.test.comparison; +package com.baeldung.junit4vstestng; import static org.junit.Assert.assertEquals; diff --git a/core-java/src/test/java/com/baeldung/test/comparison/SuiteTest.java b/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteTest.java similarity index 52% rename from core-java/src/test/java/com/baeldung/test/comparison/SuiteTest.java rename to core-java/src/test/java/com/baeldung/junit4vstestng/SuiteTest.java index a30e5d312a..effd7fa10a 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/SuiteTest.java +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteTest.java @@ -1,10 +1,10 @@ -package com.baeldung.test.comparison; +package com.baeldung.junit4vstestng; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) -@Suite.SuiteClasses({ StringCaseTest.class, DivisibilityTest.class }) +@Suite.SuiteClasses({ RegistrationTest.class, SignInTest.class }) public class SuiteTest { } diff --git a/core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTest.java b/core-java/src/test/java/com/baeldung/junit4vstestng/SummationServiceTest.java similarity index 94% rename from core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTest.java rename to core-java/src/test/java/com/baeldung/junit4vstestng/SummationServiceTest.java index b76a87c0fe..7d1bf3b7af 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTest.java +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/SummationServiceTest.java @@ -1,8 +1,4 @@ -package com.baeldung.test.comparison; - -import java.security.Security; -import java.util.ArrayList; -import java.util.List; +package com.baeldung.junit4vstestng; import org.junit.After; import org.junit.AfterClass; @@ -12,6 +8,9 @@ import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; +import java.util.ArrayList; +import java.util.List; + public class SummationServiceTest { private static List numbers; diff --git a/core-java/src/test/java/com/baeldung/test/comparison/DependentTests.java b/core-java/src/test/java/com/baeldung/test/comparison/DependentTests.java deleted file mode 100644 index 3ef4949067..0000000000 --- a/core-java/src/test/java/com/baeldung/test/comparison/DependentTests.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.test.comparison; - -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -public class DependentTests { - - private EmailValidator emailValidator; - private LoginValidator loginValidator; - private String validEmail = "abc@qwe.com"; - - @BeforeClass - public void setup() { - emailValidator = new EmailValidator(); - loginValidator = new LoginValidator(); - } - - @Test - public void givenEmail_ifValid_thenTrue() { - boolean valid = emailValidator.validate(validEmail); - Assert.assertEquals(valid, true); - } - - @Test(dependsOnMethods = { "givenEmail_ifValid_thenTrue" }) - public void givenValidEmail_whenLoggedin_thenTrue() { - boolean valid = loginValidator.validate(); - Assert.assertEquals(valid, true); - } -} - -class EmailValidator { - - public boolean validate(String validEmail) { - return true; - } - -} - -class LoginValidator { - - public boolean validate() { - return true; - } - -} diff --git a/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTest.java b/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTest.java deleted file mode 100644 index 3372bbb577..0000000000 --- a/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.test.comparison; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -@RunWith(value = Parameterized.class) -public class MyParameterisedUnitTest { - - private String name; - private NameCheck nameCheck; - - @Before - public void initialSetup() { - nameCheck = new NameCheck(); - } - - public MyParameterisedUnitTest(String myName) { - this.name = myName; - } - - @Parameters - public static Collection data() { - Object[][] data = new Object[][] { { "Peter" }, { "Sam" }, { "Tim" }, { "Lucy" } }; - return Arrays.asList(data); - } - - @Test - public void givenName_whenValidLength_thenTrue() { - boolean valid = nameCheck.nameCheck(name); - Assert.assertEquals(valid, true); - } -} - -class NameCheck { - - public boolean nameCheck(String name) { - if (name.length() > 0) - return true; - return false; - } - -} diff --git a/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTestNg.java b/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTestNg.java deleted file mode 100644 index 4096c3fb6f..0000000000 --- a/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTestNg.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.baeldung.test.comparison; - -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Parameters; -import org.testng.annotations.Test; - -public class MyParameterisedUnitTestNg { - - private PrimeNumberCheck primeNumberChecker; - - @BeforeClass - public void intialSetup() { - primeNumberChecker = new PrimeNumberCheck(); - } - - @Test(enabled = false) - @Parameters({ "num", "expectedResult" }) - public void givenNumber_ifPrime_thenCorrect(int number, boolean expectedResult) { - Assert.assertEquals(expectedResult, primeNumberChecker.validate(number)); - } - - @DataProvider(name = "test1") - public static Object[][] primeNumbers() { - return new Object[][] { { 2, true }, { 6, false }, { 19, true }, { 22, false }, { 23, true } }; - } - - @Test(dataProvider = "test1") - public void givenNumber_whenPrime_thenCorrect(Integer inputNumber, Boolean expectedResult) { - Assert.assertEquals(expectedResult, primeNumberChecker.validate(inputNumber)); - } - - @Test(dataProvider = "myDataProvider") - public void parameterCheckTest(User user) { - Assert.assertEquals("sam", user.getName()); - Assert.assertEquals(12, user.getAge()); - } - - @DataProvider(name = "myDataProvider") - public Object[][] parameterProvider() { - User usr = new User(); - usr.setName("sam"); - usr.setAge(12); - return new Object[][] { { usr } }; - } - -} - -class PrimeNumberCheck { - - public Object validate(int number) { - for (int i = 2; i < number; i++) { - if (number % i == 0) - return false; - } - return true; - } - -} - -class User { - private String name; - private int age; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } -} diff --git a/core-java/src/test/java/com/baeldung/test/comparison/RegistrationTest.java b/core-java/src/test/java/com/baeldung/test/comparison/RegistrationTest.java deleted file mode 100644 index 86836425a9..0000000000 --- a/core-java/src/test/java/com/baeldung/test/comparison/RegistrationTest.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.test.comparison; - -import org.testng.annotations.Test; - -public class RegistrationTest { - - @Test - public void givenEmail_ifValid_thenCorrect() { - - } -} diff --git a/core-java/src/test/java/com/baeldung/test/comparison/SignInTest.java b/core-java/src/test/java/com/baeldung/test/comparison/SignInTest.java deleted file mode 100644 index 9669f60b6b..0000000000 --- a/core-java/src/test/java/com/baeldung/test/comparison/SignInTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.test.comparison; - -import org.testng.annotations.Test; - -public class SignInTest { - - @Test - public void givenUsername_ifValid_thenCorrect() { - - } - -} diff --git a/core-java/src/test/resources/parameterised_test.xml b/core-java/src/test/resources/parameterised_test.xml deleted file mode 100644 index 69a2c60460..0000000000 --- a/core-java/src/test/resources/parameterised_test.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/core-java/src/test/resources/test_group.xml b/core-java/src/test/resources/test_group.xml deleted file mode 100644 index 0c9a6c73df..0000000000 --- a/core-java/src/test/resources/test_group.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/core-java/src/test/resources/test_suite.xml b/core-java/src/test/resources/test_suite.xml deleted file mode 100644 index 36305aa5fc..0000000000 --- a/core-java/src/test/resources/test_suite.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/couchbase-sdk/README.md b/couchbase-sdk/README.md index 9cdcdea012..f124a0192c 100644 --- a/couchbase-sdk/README.md +++ b/couchbase-sdk/README.md @@ -4,6 +4,7 @@ - [Introduction to Couchbase SDK for Java](http://www.baeldung.com/java-couchbase-sdk) - [Using Couchbase in a Spring Application](http://www.baeldung.com/couchbase-sdk-spring) - [Asynchronous Batch Opereations in Couchbase](http://www.baeldung.com/async-batch-operations-in-couchbase) +- [Querying Couchbase with MapReduce Views](http://www.baeldung.com/couchbase-query-mapreduce-view) ### Overview This Maven project contains the Java code for the Couchbase entities and Spring services diff --git a/disruptor/README.md b/disruptor/README.md index e69de29bb2..779b1e89c4 100644 --- a/disruptor/README.md +++ b/disruptor/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Concurrency with LMAX Disruptor – An Introduction](http://www.baeldung.com/lmax-disruptor-concurrency) diff --git a/ejb/README.md b/ejb/README.md new file mode 100644 index 0000000000..08392bc80d --- /dev/null +++ b/ejb/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Guide to EJB Set-up](http://www.baeldung.com/ejb-intro) diff --git a/guava/README.md b/guava/README.md index 40e7f19f41..ee224bae5f 100644 --- a/guava/README.md +++ b/guava/README.md @@ -16,3 +16,11 @@ - [Guava – Sets](http://www.baeldung.com/guava-sets) - [Guava – Maps](http://www.baeldung.com/guava-maps) - [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial) +- [Guide to Guava’s Ordering](http://www.baeldung.com/guava-ordering) +- [Guide to Guava’s PreConditions](http://www.baeldung.com/guava-preconditions) +- [Introduction to Guava CacheLoader](http://www.baeldung.com/guava-cacheloader) +- [Guide to Guava’s EventBus](http://www.baeldung.com/guava-eventbus) +- [Guide to Guava Multimap](http://www.baeldung.com/guava-multimap) +- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset) +- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap) +- [Guide to Guava Table](http://www.baeldung.com/guava-table) diff --git a/httpclient/README.md b/httpclient/README.md index a848edfea6..2a98c2feac 100644 --- a/httpclient/README.md +++ b/httpclient/README.md @@ -19,3 +19,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Multipart Upload with HttpClient 4](http://www.baeldung.com/httpclient-multipart-upload) - [HttpAsyncClient Tutorial](http://www.baeldung.com/httpasyncclient-tutorial) - [HttpClient 4 Tutorial](http://www.baeldung.com/httpclient-guide) +- [Advanced HttpClient Configuration](http://www.baeldung.com/httpclient-advanced-config) diff --git a/jackson/README.md b/jackson/README.md index 67a03589a8..d9faa377f1 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -25,3 +25,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [More Jackson Annotations](http://www.baeldung.com/jackson-advanced-annotations) - [Inheritance with Jackson](http://www.baeldung.com/jackson-inheritance) - [Guide to @JsonFormat in Jackson](http://www.baeldung.com/jackson-jsonformat) +- [A Guide to Optional with Jackson](http://www.baeldung.com/jackson-optional) diff --git a/java-mongodb/README.md b/java-mongodb/README.md new file mode 100644 index 0000000000..01245ac6cf --- /dev/null +++ b/java-mongodb/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [A Guide to MongoDB with Java](http://www.baeldung.com/java-mongodb) diff --git a/javaslang/README.md b/javaslang/README.md index 334ac02f60..e451883516 100644 --- a/javaslang/README.md +++ b/javaslang/README.md @@ -1,2 +1,4 @@ ### Relevant Articles: - [Introduction to Javaslang](http://www.baeldung.com/javaslang) +- [Guide to Try in Javaslang](http://www.baeldung.com/javaslang-try) +- [Guide to Pattern Matching in Javaslang](http://www.baeldung.com/javaslang-pattern-matching) diff --git a/jee7/README.md b/jee7/README.md index 44ca9c2f6e..bc242c3340 100644 --- a/jee7/README.md +++ b/jee7/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: - [Scheduling in Java EE](http://www.baeldung.com/scheduling-in-java-enterprise-edition) +- [JSON Processing in Java EE 7](http://www.baeldung.com/jee7-json) diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java b/jee7/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java new file mode 100644 index 0000000000..e3f1667595 --- /dev/null +++ b/jee7/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java @@ -0,0 +1,57 @@ +package com.baeldung.javaeeannotations; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.HttpMethodConstraint; +import javax.servlet.annotation.ServletSecurity; +import javax.servlet.annotation.WebInitParam; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@WebServlet( + name = "BankAccountServlet", + description = "Represents a Bank Account and it's transactions", + urlPatterns = {"/account", "/bankAccount" }, + initParams = { @WebInitParam(name = "type", value = "savings") } + ) +@ServletSecurity( + value = @HttpConstraint(rolesAllowed = {"admin"}), + httpMethodConstraints = {@HttpMethodConstraint(value = "POST", rolesAllowed = {"admin"})} + ) +public class AccountServlet extends javax.servlet.http.HttpServlet { + + String accountType = null; + + @Override + public void init(ServletConfig config) throws ServletException { + accountType = config.getInitParameter("type"); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + PrintWriter writer = response.getWriter(); + writer.println("Hello, I am an AccountServlet!"); + writer.flush(); + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { + double accountBalance = 1000d; + double interestRate = Double.parseDouble(request.getAttribute("interest").toString()); + + String paramDepositAmt = request.getParameter("dep"); + double depositAmt = Double.parseDouble(paramDepositAmt); + + accountBalance = accountBalance + depositAmt; + + PrintWriter writer = response.getWriter(); + writer.println(" Balance of " + accountType + " account is: " + + accountBalance + "
This account bares an interest rate of " + interestRate + + " % "); + writer.flush(); + + } +} diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java b/jee7/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java new file mode 100644 index 0000000000..6b43dd8a84 --- /dev/null +++ b/jee7/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java @@ -0,0 +1,17 @@ +package com.baeldung.javaeeannotations; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.annotation.WebListener; + +@WebListener +public class BankAppServletContextListener implements ServletContextListener { + + public void contextInitialized(ServletContextEvent sce) { + sce.getServletContext().setAttribute("ATTR_DEFAULT_LANGUAGE", "english"); + } + + public void contextDestroyed(ServletContextEvent sce) { + System.out.println("CONTEXT DESTROYED"); + } +} diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/LoggingFilter.java b/jee7/src/main/java/com/baeldung/javaeeannotations/LoggingFilter.java new file mode 100644 index 0000000000..97de5ec0de --- /dev/null +++ b/jee7/src/main/java/com/baeldung/javaeeannotations/LoggingFilter.java @@ -0,0 +1,36 @@ +package com.baeldung.javaeeannotations; + +import java.io.IOException; + +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.annotation.WebFilter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@WebFilter( + urlPatterns = "/bankAccount/*", + filterName = "LoggingFilter", + description = "Filter all account transaction URLs" + ) +public class LoggingFilter implements javax.servlet.Filter { + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } + + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletRequest req = (HttpServletRequest) request; + HttpServletResponse res = (HttpServletResponse) response; + + res.sendRedirect(req.getContextPath() + "/login.jsp"); + chain.doFilter(request, response); + } + + @Override + public void destroy() { + } + +} diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java b/jee7/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java new file mode 100644 index 0000000000..8a6c709b81 --- /dev/null +++ b/jee7/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java @@ -0,0 +1,29 @@ +package com.baeldung.javaeeannotations; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.annotation.MultipartConfig; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.Part; + +@WebServlet(urlPatterns = { "/uploadCustDocs" }) +@MultipartConfig( + fileSizeThreshold = 1024 * 1024 * 20, + maxFileSize = 1024 * 1024 * 20, + maxRequestSize = 1024 * 1024 * 25, + location = "D:/custDocs" + ) +public class UploadCustomerDocumentsServlet extends HttpServlet { + + protected void doPost( + HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + for (Part part : request.getParts()) { + part.write("myFile"); + } + } + +} diff --git a/jee7/src/main/webapp/WEB-INF/web.xml b/jee7/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..0a3d84d2d4 --- /dev/null +++ b/jee7/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,11 @@ + + + + BASIC + default + + + \ No newline at end of file diff --git a/jee7/src/main/webapp/index.jsp b/jee7/src/main/webapp/index.jsp new file mode 100644 index 0000000000..0c389ef5b1 --- /dev/null +++ b/jee7/src/main/webapp/index.jsp @@ -0,0 +1,16 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +My Account + + +
+ Width: +    + +
+ + \ No newline at end of file diff --git a/jee7/src/main/webapp/login.jsp b/jee7/src/main/webapp/login.jsp new file mode 100644 index 0000000000..885df0c3d9 --- /dev/null +++ b/jee7/src/main/webapp/login.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Login + + +Login Here... + + \ No newline at end of file diff --git a/jee7/src/main/webapp/upload.jsp b/jee7/src/main/webapp/upload.jsp new file mode 100644 index 0000000000..020483b99f --- /dev/null +++ b/jee7/src/main/webapp/upload.jsp @@ -0,0 +1,16 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Insert title here + + +
+ +
+ +
+ + \ No newline at end of file diff --git a/kotlin/README.md b/kotlin/README.md new file mode 100644 index 0000000000..6447a26f5c --- /dev/null +++ b/kotlin/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Introduction to the Kotlin Language](http://www.baeldung.com/kotlin) diff --git a/log4j2/pom.xml b/log4j2/pom.xml index 893c79be72..a4c8f19f69 100644 --- a/log4j2/pom.xml +++ b/log4j2/pom.xml @@ -1,105 +1,104 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - log4j2 + log4j2 - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - .. - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + - - - - org.apache.logging.log4j - log4j-core - ${log4j-core.version} - + + + + org.apache.logging.log4j + log4j-core + ${log4j-core.version} + - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - ${jackson.version} - + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + ${jackson.version} + - - - com.h2database - h2 - ${h2.version} - - - org.apache.commons - commons-dbcp2 - ${commons-dbcp2.version} - + + + com.h2database + h2 + ${h2.version} + + + org.apache.commons + commons-dbcp2 + ${commons-dbcp2.version} + - - - org.apache.logging.log4j - log4j-core - ${log4j-core.version} - test-jar - test - - - junit - junit - ${junit.version} - test - - + + + org.apache.logging.log4j + log4j-core + ${log4j-core.version} + test-jar + test + + + junit + junit + ${junit.version} + test + + - - + + - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - **/*IntegrationTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - - true - - + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + + true + + - - + + - - 2.8.5 - 1.4.193 - 2.1.1 - 2.7 - 4.12 - - 3.6.0 - 2.19.1 - + + 2.8.5 + 1.4.193 + 2.1.1 + 2.7 + 4.12 + 3.6.0 + 2.19.1 + diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/AsyncFileAppenderUsingJsonLayoutTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/AsyncFileAppenderUsingJsonLayoutTest.java deleted file mode 100644 index 0472c2219e..0000000000 --- a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/AsyncFileAppenderUsingJsonLayoutTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.logging.log4j2.tests; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.junit.LoggerContextRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.nio.file.Files; -import java.nio.file.Paths; - -import static org.junit.Assert.assertTrue; - -@RunWith(JUnit4.class) -public class AsyncFileAppenderUsingJsonLayoutTest { - @Rule - public LoggerContextRule contextRule = - new LoggerContextRule("log4j2-async-file-appender_json-layout.xml"); - - @Test - public void givenLoggerWithAsyncConfig_shouldLogToJsonFile() - throws Exception { - Logger logger = contextRule.getLogger(getClass().getSimpleName()); - final int count = 88; - for (int i = 0; i < count; i++) { - logger.info("This is async JSON message #{} at INFO level.", count); - } - long logEventsCount = Files.lines(Paths.get("target/logfile.json")).count(); - assertTrue(logEventsCount > 0 && logEventsCount <= count); - } -} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingDefaultLayoutTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingDefaultLayoutTest.java deleted file mode 100644 index 9831030d02..0000000000 --- a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingDefaultLayoutTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.logging.log4j2.tests; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -@RunWith(JUnit4.class) -public class ConsoleAppenderUsingDefaultLayoutTest { - @Test - public void givenLoggerWithDefaultConfig_shouldLogToConsole() - throws Exception { - Logger logger = LogManager.getLogger(getClass()); - Exception e = new RuntimeException("This is only a test!"); - logger.info("This is a simple message at INFO level. " + - "It will be hidden."); - logger.error("This is a simple message at ERROR level. " + - "This is the minimum visible level.", e); - } -} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingPatternLayoutWithColorsTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingPatternLayoutWithColorsTest.java deleted file mode 100644 index 86b005538f..0000000000 --- a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingPatternLayoutWithColorsTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.logging.log4j2.tests; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.Marker; -import org.apache.logging.log4j.MarkerManager; -import org.apache.logging.log4j.ThreadContext; -import org.apache.logging.log4j.junit.LoggerContextRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -@RunWith(JUnit4.class) -public class ConsoleAppenderUsingPatternLayoutWithColorsTest { - @Rule - public LoggerContextRule contextRule = - new LoggerContextRule("log4j2-console-appender_pattern-layout.xml"); - - @Test - public void givenLoggerWithConsoleConfig_shouldLogToConsoleInColors() - throws Exception { - Logger logger = contextRule.getLogger(getClass().getSimpleName()); - logger.trace("This is a colored message at TRACE level."); - logger.debug("This is a colored message at DEBUG level. " + - "This is the minimum visible level."); - logger.info("This is a colored message at INFO level."); - logger.warn("This is a colored message at WARN level."); - Exception e = new RuntimeException("This is only a test!"); - logger.error("This is a colored message at ERROR level.", e); - logger.fatal("This is a colored message at FATAL level."); - } - - @Test - public void givenLoggerWithConsoleConfig_shouldFilterByMarker() throws Exception { - Logger logger = contextRule.getLogger("ConnTrace"); - Marker appError = MarkerManager.getMarker("APP_ERROR"); - logger.error(appError, "This marker message at ERROR level should be hidden."); - Marker connectionTrace = MarkerManager.getMarker("CONN_TRACE"); - logger.trace(connectionTrace, "This is a marker message at TRACE level."); - } - - @Test - public void givenLoggerWithConsoleConfig_shouldFilterByThreadContext() throws Exception { - Logger logger = contextRule.getLogger("UserAudit"); - ThreadContext.put("userId", "1000"); - logger.info("This is a log-visible user login. Maybe from an admin account?"); - ThreadContext.put("userId", "1001"); - logger.info("This is a log-invisible user login."); - boolean b = true; - } -} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingTest.java new file mode 100644 index 0000000000..1562b67068 --- /dev/null +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingTest.java @@ -0,0 +1,122 @@ +package com.baeldung.logging.log4j2.tests; + +import static org.junit.Assert.assertTrue; + +import java.nio.file.Files; +import java.nio.file.Paths; +import java.sql.Connection; +import java.sql.ResultSet; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; +import org.apache.logging.log4j.ThreadContext; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import com.baeldung.logging.log4j2.tests.jdbc.ConnectionFactory; + +@RunWith(JUnit4.class) +public class CustomLoggingTest { + + @BeforeClass + public static void setup() throws Exception { + Connection connection = ConnectionFactory.getConnection(); + connection.createStatement() + .execute("CREATE TABLE logs(" + "when TIMESTAMP," + "logger VARCHAR(255)," + "level VARCHAR(255)," + "message VARCHAR(4096)," + "throwable TEXT)"); + connection.commit(); + } + + @Test + public void givenLoggerWithDefaultConfig_shouldLogToConsole() throws Exception { + Logger logger = LogManager.getLogger(getClass()); + Exception e = new RuntimeException("This is only a test!"); + logger.info("This is a simple message at INFO level. " + "It will be hidden."); + logger.error("This is a simple message at ERROR level. " + "This is the minimum visible level.", e); + } + + @Test + public void givenLoggerWithConsoleConfig_shouldLogToConsoleInColors() throws Exception { + Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_MARKER"); + logger.trace("This is a colored message at TRACE level."); + logger.debug("This is a colored message at DEBUG level. " + "This is the minimum visible level."); + logger.info("This is a colored message at INFO level."); + logger.warn("This is a colored message at WARN level."); + Exception e = new RuntimeException("This is only a test!"); + logger.error("This is a colored message at ERROR level.", e); + logger.fatal("This is a colored message at FATAL level."); + } + + @Test + public void givenLoggerWithConsoleConfig_shouldFilterByMarker() throws Exception { + Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_MARKER"); + Marker appError = MarkerManager.getMarker("APP_ERROR"); + logger.error(appError, "This marker message at ERROR level should be hidden."); + Marker connectionTrace = MarkerManager.getMarker("CONN_TRACE"); + logger.trace(connectionTrace, "This is a marker message at TRACE level."); + } + + @Test + public void givenLoggerWithConsoleConfig_shouldFilterByThreadContext() throws Exception { + Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_THREAD_CONTEXT"); + ThreadContext.put("userId", "1000"); + logger.info("This is a log-visible user login. Maybe from an admin account?"); + ThreadContext.put("userId", "1001"); + logger.info("This is a log-invisible user login."); + + } + + @Test + public void givenLoggerWithAsyncConfig_shouldLogToJsonFile() throws Exception { + Logger logger = LogManager.getLogger("ASYNC_JSON_FILE_APPENDER"); + final int count = 88; + for (int i = 0; i < count; i++) { + logger.info("This is async JSON message #{} at INFO level.", count); + } + long logEventsCount = Files.lines(Paths.get("target/logfile.json")) + .count(); + assertTrue(logEventsCount > 0 && logEventsCount <= count); + } + + @Test + public void givenLoggerWithFailoverConfig_shouldLog() throws Exception { + Logger logger = LogManager.getLogger("FAIL_OVER_SYSLOG_APPENDER"); + logger.trace("This is a syslog message at TRACE level."); + logger.debug("This is a syslog message at DEBUG level."); + logger.info("This is a syslog message at INFO level. This is the minimum visible level."); + logger.warn("This is a syslog message at WARN level."); + Exception e = new RuntimeException("This is only a test!"); + logger.error("This is a syslog message at ERROR level.", e); + logger.fatal("This is a syslog message at FATAL level."); + } + + @Test + public void givenLoggerWithJdbcConfig_shouldLogToDataSource() throws Exception { + Logger logger = LogManager.getLogger("JDBC_APPENDER"); + final int count = 88; + for (int i = 0; i < count; i++) { + logger.info("This is JDBC message #{} at INFO level.", count); + } + Connection connection = ConnectionFactory.getConnection(); + ResultSet resultSet = connection.createStatement() + .executeQuery("SELECT COUNT(*) AS ROW_COUNT FROM logs"); + int logCount = 0; + if (resultSet.next()) { + logCount = resultSet.getInt("ROW_COUNT"); + } + assertTrue(logCount == count); + } + + @Test + public void givenLoggerWithRollingFileConfig_shouldLogToXMLFile() throws Exception { + Logger logger = LogManager.getLogger("XML_ROLLING_FILE_APPENDER"); + final int count = 88; + for (int i = 0; i < count; i++) { + logger.info("This is rolling file XML message #{} at INFO level.", i); + } + } + +} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/FailoverSyslogConsoleAppenderTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/FailoverSyslogConsoleAppenderTest.java deleted file mode 100644 index 0653394e5a..0000000000 --- a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/FailoverSyslogConsoleAppenderTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.logging.log4j2.tests; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.junit.LoggerContextRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -@RunWith(JUnit4.class) -public class FailoverSyslogConsoleAppenderTest { - @Rule - public LoggerContextRule contextRule = - new LoggerContextRule("log4j2-failover-syslog-console-appender_pattern-layout.xml"); - - @Test - public void givenLoggerWithFailoverConfig_shouldLog() throws Exception { - Logger logger = contextRule.getLogger(getClass().getSimpleName()); - logger.trace("This is a syslog message at TRACE level."); - logger.debug("This is a syslog message at DEBUG level."); - logger.info("This is a syslog message at INFO level. This is the minimum visible level."); - logger.warn("This is a syslog message at WARN level."); - Exception e = new RuntimeException("This is only a test!"); - logger.error("This is a syslog message at ERROR level.", e); - logger.fatal("This is a syslog message at FATAL level."); - } -} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JDBCAppenderTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JDBCAppenderTest.java deleted file mode 100644 index 1b8d33e2bf..0000000000 --- a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JDBCAppenderTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.logging.log4j2.tests; - -import com.baeldung.logging.log4j2.tests.jdbc.ConnectionFactory; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.junit.LoggerContextRule; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.sql.Connection; -import java.sql.ResultSet; - -import static org.junit.Assert.assertTrue; - -@RunWith(JUnit4.class) -public class JDBCAppenderTest { - @Rule - public LoggerContextRule contextRule = new LoggerContextRule("log4j2-jdbc-appender.xml"); - - @BeforeClass - public static void setup() throws Exception { - Connection connection = ConnectionFactory.getConnection(); - connection.createStatement() - .execute("CREATE TABLE logs(" + - "when TIMESTAMP," + - "logger VARCHAR(255)," + - "level VARCHAR(255)," + - "message VARCHAR(4096)," + - "throwable TEXT)"); - //connection.commit(); - } - - @Test - public void givenLoggerWithJdbcConfig_shouldLogToDataSource() throws Exception { - Logger logger = contextRule.getLogger(getClass().getSimpleName()); - final int count = 88; - for (int i = 0; i < count; i++) { - logger.info("This is JDBC message #{} at INFO level.", count); - } - Connection connection = ConnectionFactory.getConnection(); - ResultSet resultSet = connection.createStatement() - .executeQuery("SELECT COUNT(*) AS ROW_COUNT FROM logs"); - int logCount = 0; - if (resultSet.next()) { - logCount = resultSet.getInt("ROW_COUNT"); - } - assertTrue(logCount == count); - } -} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/RollingFileAppenderUsingXMLLayoutTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/RollingFileAppenderUsingXMLLayoutTest.java deleted file mode 100644 index 3ab69d263c..0000000000 --- a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/RollingFileAppenderUsingXMLLayoutTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.logging.log4j2.tests; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.junit.LoggerContextRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.stream.Collectors; - -import static org.junit.Assert.assertTrue; - -@RunWith(JUnit4.class) -public class RollingFileAppenderUsingXMLLayoutTest { - @Rule - public LoggerContextRule contextRule = - new LoggerContextRule("log4j2-rolling-file-appender_xml-layout.xml"); - - @Test - public void givenLoggerWithRollingFileConfig_shouldLogToXMLFile() throws Exception { - Logger logger = contextRule.getLogger(getClass().getSimpleName()); - final int count = 88; - for (int i = 0; i < count; i++) { - logger.info("This is rolling file XML message #{} at INFO level.", i); - } - String[] logEvents = Files.readAllLines(Paths.get("target/logfile.xml")).stream() - .collect(Collectors.joining(System.lineSeparator())) - .split("\\n\\n+"); - assertTrue(logEvents.length == 39); - } -} diff --git a/log4j2/src/test/resources/log4j2-async-file-appender_json-layout.xml b/log4j2/src/test/resources/log4j2-async-file-appender_json-layout.xml deleted file mode 100644 index c291eacd59..0000000000 --- a/log4j2/src/test/resources/log4j2-async-file-appender_json-layout.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/log4j2/src/test/resources/log4j2-console-appender_pattern-layout.xml b/log4j2/src/test/resources/log4j2-console-appender_pattern-layout.xml deleted file mode 100644 index d6621f9166..0000000000 --- a/log4j2/src/test/resources/log4j2-console-appender_pattern-layout.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/log4j2/src/test/resources/log4j2-failover-syslog-console-appender_pattern-layout.xml b/log4j2/src/test/resources/log4j2-failover-syslog-console-appender_pattern-layout.xml deleted file mode 100644 index 62ba37f28c..0000000000 --- a/log4j2/src/test/resources/log4j2-failover-syslog-console-appender_pattern-layout.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml b/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml index c2b9c65430..fd61e4581f 100644 --- a/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml +++ b/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml @@ -1,4 +1,5 @@ - + diff --git a/log4j2/src/test/resources/log4j2-jdbc-appender.xml b/log4j2/src/test/resources/log4j2-jdbc-appender.xml deleted file mode 100644 index 6b50f7d5a4..0000000000 --- a/log4j2/src/test/resources/log4j2-jdbc-appender.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/log4j2/src/test/resources/log4j2-rolling-file-appender_xml-layout.xml b/log4j2/src/test/resources/log4j2-rolling-file-appender_xml-layout.xml deleted file mode 100644 index 9de1a29186..0000000000 --- a/log4j2/src/test/resources/log4j2-rolling-file-appender_xml-layout.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/log4j2/src/test/resources/log4j2.xml b/log4j2/src/test/resources/log4j2.xml index 8f7608aa78..83c1184f1f 100644 --- a/log4j2/src/test/resources/log4j2.xml +++ b/log4j2/src/test/resources/log4j2.xml @@ -1,13 +1,69 @@ - + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + - + \ No newline at end of file diff --git a/metrics/README.md b/metrics/README.md new file mode 100644 index 0000000000..c98024c479 --- /dev/null +++ b/metrics/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Intro to Dropwizard Metrics](http://www.baeldung.com/dropwizard-metrics) diff --git a/pdf/README.md b/pdf/README.md index 7160df4081..5454d2b2de 100644 --- a/pdf/README.md +++ b/pdf/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: - [PDF Conversions in Java](http://www.baeldung.com/pdf-conversions-java) +- [Creating PDF Files in Java](http://www.baeldung.com/java-pdf-creation) diff --git a/pom.xml b/pom.xml index 52e00edbb4..ad60436151 100644 --- a/pom.xml +++ b/pom.xml @@ -110,6 +110,7 @@ spring-autowire spring-batch spring-boot + spring-boot-servlet spring-cloud-data-flow spring-cloud spring-core @@ -183,6 +184,7 @@ spring-reactor testing + testng video-tutorials @@ -194,7 +196,7 @@ struts2 apache-velocity - + apache-solrj diff --git a/rxjava/README.md b/rxjava/README.md new file mode 100644 index 0000000000..7670dd4ed3 --- /dev/null +++ b/rxjava/README.md @@ -0,0 +1,4 @@ +## Relevant articles: + +- [Dealing with Backpressure with RxJava](http://www.baeldung.com/rxjava-backpressure) +- [How to Test RxJava?](http://www.baeldung.com/rxjava-testing) diff --git a/spring-all/README.md b/spring-all/README.md index 90ae69300a..a8ea7c58c7 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -16,3 +16,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Quick Guide to Spring Controllers](http://www.baeldung.com/spring-controllers) - [Quick Guide to Spring Bean Scopes](http://www.baeldung.com/spring-bean-scopes) - [Introduction To Ehcache](http://www.baeldung.com/ehcache) +- [A Guide to the Spring Task Scheduler](http://www.baeldung.com/spring-task-scheduler) +- [Guide to Spring Retry](http://www.baeldung.com/spring-retry) diff --git a/spring-amqp/README.md b/spring-amqp/README.md new file mode 100644 index 0000000000..b0d16c9305 --- /dev/null +++ b/spring-amqp/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Messaging With Spring AMQP](http://www.baeldung.com/spring-amqp) diff --git a/spring-boot-servlet/.gitignore b/spring-boot-servlet/.gitignore new file mode 100644 index 0000000000..60be5b80aa --- /dev/null +++ b/spring-boot-servlet/.gitignore @@ -0,0 +1,4 @@ +/target/ +.settings/ +.classpath +.project diff --git a/spring-boot-servlet/README.md b/spring-boot-servlet/README.md new file mode 100644 index 0000000000..262a11fc36 --- /dev/null +++ b/spring-boot-servlet/README.md @@ -0,0 +1,2 @@ +###Relevant Articles: +- [How to Register a Servlet in a Java Web Application](http://www.baeldung.com/how-to-register-a-servlet-in-a-java-web-application/) \ No newline at end of file diff --git a/spring-boot-servlet/pom.xml b/spring-boot-servlet/pom.xml new file mode 100644 index 0000000000..3818e3468f --- /dev/null +++ b/spring-boot-servlet/pom.xml @@ -0,0 +1,55 @@ + + 4.0.0 + com.baeldung + spring-boot-servlet + 0.0.1-SNAPSHOT + war + spring-boot-servlet + + + org.springframework.boot + spring-boot-dependencies + 1.5.1.RELEASE + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.apache.tomcat.embed + tomcat-embed-core + ${tomcat.version} + + + org.apache.tomcat.embed + tomcat-embed-jasper + ${tomcat.version} + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + 1.8 + 8.5.11 + + + diff --git a/spring-boot-servlet/src/main/java/META-INF/MANIFEST.MF b/spring-boot-servlet/src/main/java/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..69ebae1751 --- /dev/null +++ b/spring-boot-servlet/src/main/java/META-INF/MANIFEST.MF @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 +Main-Class: com.baeldung.ApplicationMain diff --git a/spring-boot-servlet/src/main/java/com/baeldung/ApplicationMain.java b/spring-boot-servlet/src/main/java/com/baeldung/ApplicationMain.java new file mode 100644 index 0000000000..66f2e85999 --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/ApplicationMain.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.support.SpringBootServletInitializer; + +@SpringBootApplication +public class ApplicationMain extends SpringBootServletInitializer { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(ApplicationMain.class); + } +} \ No newline at end of file diff --git a/spring-boot-servlet/src/main/java/com/baeldung/configuration/WebAppInitializer.java b/spring-boot-servlet/src/main/java/com/baeldung/configuration/WebAppInitializer.java new file mode 100644 index 0000000000..b7e22500f4 --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/configuration/WebAppInitializer.java @@ -0,0 +1,32 @@ +package com.baeldung.configuration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.context.support.XmlWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +public class WebAppInitializer implements WebApplicationInitializer { + + public void onStartup(ServletContext container) throws ServletException { + + AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); + ctx.register(WebMvcConfigure.class); + ctx.setServletContext(container); + + ServletRegistration.Dynamic servletOne = container.addServlet("SpringProgrammaticDispatcherServlet", new DispatcherServlet(ctx)); + servletOne.setLoadOnStartup(1); + servletOne.addMapping("/"); + + XmlWebApplicationContext xctx = new XmlWebApplicationContext(); + xctx.setConfigLocation("/WEB-INF/context.xml"); + xctx.setServletContext(container); + + ServletRegistration.Dynamic servletTwo = container.addServlet("SpringProgrammaticXMLDispatcherServlet", new DispatcherServlet(xctx)); + servletTwo.setLoadOnStartup(1); + servletTwo.addMapping("/"); + } + +} \ No newline at end of file diff --git a/spring-boot-servlet/src/main/java/com/baeldung/configuration/WebMvcConfigure.java b/spring-boot-servlet/src/main/java/com/baeldung/configuration/WebMvcConfigure.java new file mode 100644 index 0000000000..de9067de6e --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/configuration/WebMvcConfigure.java @@ -0,0 +1,40 @@ +package com.baeldung.configuration; + +import org.springframework.boot.web.support.ErrorPageFilter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.resource.PathResourceResolver; +import org.springframework.web.servlet.view.InternalResourceViewResolver; + +@Configuration +public class WebMvcConfigure extends WebMvcConfigurerAdapter { + + @Bean + public ViewResolver getViewResolver() { + InternalResourceViewResolver resolver = new InternalResourceViewResolver(); + resolver.setPrefix("/WEB-INF/"); + resolver.setSuffix(".jsp"); + return resolver; + } + + @Override + public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver()); + } + + @Bean + public ErrorPageFilter errorPageFilter() { + return new ErrorPageFilter(); + } +} + diff --git a/spring-boot-servlet/src/main/java/com/baeldung/props/Constants.java b/spring-boot-servlet/src/main/java/com/baeldung/props/Constants.java new file mode 100644 index 0000000000..421401eec7 --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/props/Constants.java @@ -0,0 +1,20 @@ +package com.baeldung.props; + +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.Properties; + +public final class Constants { + + @Autowired + PropertySourcesLoader psl; + + public static final String breakLine = System.getProperty("line.separator"); + private static final PropertyLoader pl = new PropertyLoader(); + private static final Properties mainProps = pl.getProperties("custom.properties"); + public static final String DISPATCHER_SERVLET_NAME = mainProps.getProperty("dispatcher.servlet.name"); + public static final String DISPATCHER_SERVLET_MAPPING = mainProps.getProperty("dispatcher.servlet.mapping"); + private final String EXAMPLE_SERVLET_NAME = psl.getProperty("example.servlet.name"); + private final String EXAMPLE_SERVLET_MAPPING = psl.getProperty("example.servlet.mapping"); + +} diff --git a/spring-boot-servlet/src/main/java/com/baeldung/props/PropertyLoader.java b/spring-boot-servlet/src/main/java/com/baeldung/props/PropertyLoader.java new file mode 100644 index 0000000000..5d890d96fa --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/props/PropertyLoader.java @@ -0,0 +1,27 @@ +package com.baeldung.props; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +public class PropertyLoader { + private static final Logger log = LoggerFactory.getLogger(PropertyLoader.class); + + public Properties getProperties(String file) { + Properties prop = new Properties(); + InputStream input = null; + try { + input = getClass().getResourceAsStream(file); + prop.load(input); + if (input != null) { + input.close(); + } + } catch (IOException ex) { + log.error("IOException: " + ex); + } + return prop; + } +} diff --git a/spring-boot-servlet/src/main/java/com/baeldung/props/PropertySourcesLoader.java b/spring-boot-servlet/src/main/java/com/baeldung/props/PropertySourcesLoader.java new file mode 100644 index 0000000000..8c7b3a4af5 --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/props/PropertySourcesLoader.java @@ -0,0 +1,23 @@ +package com.baeldung.props; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.ConfigurableEnvironment; + +@Configuration +@ComponentScan(basePackages = { "com.baeldung.*" }) +@PropertySource("classpath:custom.properties") public class PropertySourcesLoader { + + private static final Logger log = LoggerFactory.getLogger(PropertySourcesLoader.class); + + @Autowired + ConfigurableEnvironment env; + + public String getProperty(String key) { + return env.getProperty(key); + } +} diff --git a/spring-boot-servlet/src/main/java/com/baeldung/servlets/GenericCustomServlet.java b/spring-boot-servlet/src/main/java/com/baeldung/servlets/GenericCustomServlet.java new file mode 100644 index 0000000000..c6543c9eef --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/servlets/GenericCustomServlet.java @@ -0,0 +1,18 @@ +package com.baeldung.servlets; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +public class GenericCustomServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.println("

Hello World

"); + } +} diff --git a/spring-boot-servlet/src/main/java/com/baeldung/servlets/javaee/AnnotationServlet.java b/spring-boot-servlet/src/main/java/com/baeldung/servlets/javaee/AnnotationServlet.java new file mode 100644 index 0000000000..d971e68cfa --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/servlets/javaee/AnnotationServlet.java @@ -0,0 +1,20 @@ +package com.baeldung.servlets.javaee; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@WebServlet(name = "AnnotationServlet", + description = "Example Servlet Using Annotations", + urlPatterns = { "/annotationservlet" }) +public class AnnotationServlet extends HttpServlet { + private static final long serialVersionUID = 1L; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + request.getRequestDispatcher("/annotationservlet.jsp").forward(request, response); + } +} diff --git a/spring-boot-servlet/src/main/java/com/baeldung/servlets/javaee/EEWebXmlServlet.java b/spring-boot-servlet/src/main/java/com/baeldung/servlets/javaee/EEWebXmlServlet.java new file mode 100644 index 0000000000..4209e815cd --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/servlets/javaee/EEWebXmlServlet.java @@ -0,0 +1,20 @@ +package com.baeldung.servlets.javaee; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +public class EEWebXmlServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.println("

Hello World

"); + } +} \ No newline at end of file diff --git a/spring-boot-servlet/src/main/java/com/baeldung/servlets/springboot/SpringRegistrationBeanServlet.java b/spring-boot-servlet/src/main/java/com/baeldung/servlets/springboot/SpringRegistrationBeanServlet.java new file mode 100644 index 0000000000..4a34465894 --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/servlets/springboot/SpringRegistrationBeanServlet.java @@ -0,0 +1,19 @@ +package com.baeldung.servlets.springboot; + +import com.baeldung.servlets.GenericCustomServlet; +import org.springframework.boot.web.servlet.ServletRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SpringRegistrationBeanServlet { + + @Bean + public ServletRegistrationBean genericCustomServlet() { + ServletRegistrationBean bean = new ServletRegistrationBean(new GenericCustomServlet(), "/springregistrationbeanservlet/*"); + bean.setLoadOnStartup(1); + return bean; + } +} + + diff --git a/spring-boot-servlet/src/main/java/com/baeldung/servlets/springboot/embedded/EmbeddedTomcatExample.java b/spring-boot-servlet/src/main/java/com/baeldung/servlets/springboot/embedded/EmbeddedTomcatExample.java new file mode 100644 index 0000000000..b2458f33c7 --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/servlets/springboot/embedded/EmbeddedTomcatExample.java @@ -0,0 +1,16 @@ +package com.baeldung.servlets.springboot.embedded; + +import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; +import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class EmbeddedTomcatExample { + + @Bean + public EmbeddedServletContainerFactory servletContainer() { + TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory(); + return tomcat; + } +} diff --git a/spring-boot-servlet/src/main/resources/application.properties b/spring-boot-servlet/src/main/resources/application.properties new file mode 100644 index 0000000000..4e9e2b4cf1 --- /dev/null +++ b/spring-boot-servlet/src/main/resources/application.properties @@ -0,0 +1,10 @@ +#Server Configuration +#server.port=8080 +#server.context-path=/javabootdata +#Resource Handling +#spring.resources.static-locations=classpath:/WEB-INF/resources +#spring.mvc.view.prefix=/WEB-INF/ +#spring.mvc.view.suffix=.jsp +#spring.resources.cache-period=3600 +servlet.name=dispatcherExample +servlet.mapping=/dispatcherExampleURL \ No newline at end of file diff --git a/spring-boot-servlet/src/main/resources/custom.properties b/spring-boot-servlet/src/main/resources/custom.properties new file mode 100644 index 0000000000..34f31bcd50 --- /dev/null +++ b/spring-boot-servlet/src/main/resources/custom.properties @@ -0,0 +1,4 @@ +dispatcher.servlet.name=dispatcherExample +dispatcher.servlet.mapping=/dispatcherExampleURL +example.servlet.name=dispatcherExample +example.servlet.mapping=/dispatcherExampleURL \ No newline at end of file diff --git a/spring-boot-servlet/src/main/webapp/WEB-INF/context.xml b/spring-boot-servlet/src/main/webapp/WEB-INF/context.xml new file mode 100644 index 0000000000..263bed4430 --- /dev/null +++ b/spring-boot-servlet/src/main/webapp/WEB-INF/context.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/spring-boot-servlet/src/main/webapp/WEB-INF/dispatcher.xml b/spring-boot-servlet/src/main/webapp/WEB-INF/dispatcher.xml new file mode 100644 index 0000000000..ade8e66777 --- /dev/null +++ b/spring-boot-servlet/src/main/webapp/WEB-INF/dispatcher.xml @@ -0,0 +1,16 @@ + + + + + + + + + \ No newline at end of file diff --git a/spring-boot-servlet/src/main/webapp/WEB-INF/web.xml b/spring-boot-servlet/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..60a4b079de --- /dev/null +++ b/spring-boot-servlet/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,40 @@ + + + JSP + + index.html + index.htm + index.jsp + + + + + EEWebXmlServlet + com.baeldung.servlets.javaee.EEWebXmlServlet + + + + EEWebXmlServlet + /eewebxmlservlet + + + + + SpringBootWebXmlServlet + org.springframework.web.servlet.DispatcherServlet + + contextConfigLocation + /WEB-INF/dispatcher.xml + + 1 + + + + SpringBootWebXmlServlet + / + + + + diff --git a/spring-boot-servlet/src/main/webapp/annotationservlet.jsp b/spring-boot-servlet/src/main/webapp/annotationservlet.jsp new file mode 100644 index 0000000000..f21748df50 --- /dev/null +++ b/spring-boot-servlet/src/main/webapp/annotationservlet.jsp @@ -0,0 +1 @@ +

Annotation Servlet!

\ No newline at end of file diff --git a/spring-boot-servlet/src/main/webapp/index.jsp b/spring-boot-servlet/src/main/webapp/index.jsp new file mode 100644 index 0000000000..e534282777 --- /dev/null +++ b/spring-boot-servlet/src/main/webapp/index.jsp @@ -0,0 +1 @@ +

Hello!

\ No newline at end of file diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 05173ef318..d0a02c69fc 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -7,3 +7,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Guide to Spring in Eclipse STS](http://www.baeldung.com/eclipse-sts-spring) - [Introduction to WebJars](http://www.baeldung.com/maven-webjars) - [Create a Fat Jar App with Spring Boot](http://www.baeldung.com/deployable-fat-jar-spring-boot) +- [The @ServletComponentScan Annotation in Spring Boot](http://www.baeldung.com/spring-servletcomponentscan) +- [A Custom Data Binder in Spring MVC](http://www.baeldung.com/spring-mvc-custom-data-binder) +- [Intro to Building an Application with Spring Boot](http://www.baeldung.com/intro-to-spring-boot) diff --git a/spring-boot/src/main/java/com/baeldung/utils/Application.java b/spring-boot/src/main/java/com/baeldung/utils/Application.java index 1f637eec11..a3d9f9130c 100644 --- a/spring-boot/src/main/java/com/baeldung/utils/Application.java +++ b/spring-boot/src/main/java/com/baeldung/utils/Application.java @@ -12,7 +12,7 @@ public class Application { @RolesAllowed("*") public static void main(String[] args) { - SpringApplication.run(Application.class, args); + SpringApplication.run(Application.class, args); } } diff --git a/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java b/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java index a14d0b26c6..7b4827cdf2 100644 --- a/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java +++ b/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java @@ -35,7 +35,7 @@ public class UtilsController { // } WebUtils.setSessionAttribute(request, "parameter", param); - model.addAttribute("parameter", "You set: "+(String) WebUtils.getSessionAttribute(request, "parameter")); + model.addAttribute("parameter", "You set: "+(String) WebUtils.getSessionAttribute(request, "parameter")); return "utils"; } diff --git a/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerTest.java b/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerTest.java new file mode 100644 index 0000000000..7aed45dbb0 --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerTest.java @@ -0,0 +1,41 @@ +package com.baeldung.utils; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.MockitoAnnotations; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +import com.baeldung.utils.controller.UtilsController; + +public class UtilsControllerTest { + + @InjectMocks + private UtilsController utilsController; + + private MockMvc mockMvc; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController) + .build(); + + } + + @Test + public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception { + String param = "testparam"; + this.mockMvc.perform( + post("/setParam") + .param("param", param) + .sessionAttr("parameter", param)) + .andExpect(status().isOk()); + } + +} diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplicationLiveTest.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplicationLiveTest.java deleted file mode 100644 index aa39232bb2..0000000000 --- a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplicationLiveTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.spring.cloud.bootstrap.gateway; - -import org.junit.Assert; -import org.junit.Test; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.*; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; - -public class GatewayApplicationLiveTest { - - @Test - public void testAccess() throws Exception { - TestRestTemplate testRestTemplate = new TestRestTemplate(); - String testUrl = "http://localhost:8080"; - - ResponseEntity response = testRestTemplate.getForEntity(testUrl + "/book-service/books", String.class); - Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); - Assert.assertNotNull(response.getBody()); - - //try the protected resource and confirm the redirect to login - response = testRestTemplate.getForEntity(testUrl + "/book-service/books/1", String.class); - Assert.assertEquals(HttpStatus.FOUND, response.getStatusCode()); - Assert.assertEquals("http://localhost:8080/login", response.getHeaders().get("Location").get(0)); - - //login as user/password - MultiValueMap form = new LinkedMultiValueMap<>(); - form.add("username", "user"); - form.add("password", "password"); - response = testRestTemplate.postForEntity(testUrl + "/login", form, String.class); - - //extract the session from the cookie and propagate it to the next request - String sessionCookie = response.getHeaders().get("Set-Cookie").get(0).split(";")[0]; - HttpHeaders headers = new HttpHeaders(); - headers.add("Cookie", sessionCookie); - HttpEntity httpEntity = new HttpEntity<>(headers); - - //request the protected resource - response = testRestTemplate.exchange(testUrl + "/book-service/books/1", HttpMethod.GET, httpEntity, String.class); - Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); - Assert.assertNotNull(response.getBody()); - - //request the admin protected resource to determine it is still protected - response = testRestTemplate.exchange(testUrl + "/rating-service/ratings/all", HttpMethod.GET, httpEntity, String.class); - Assert.assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); - - //login as the admin - form.clear(); - form.add("username", "admin"); - form.add("password", "admin"); - response = testRestTemplate.postForEntity(testUrl + "/login", form, String.class); - - //extract the session from the cookie and propagate it to the next request - sessionCookie = response.getHeaders().get("Set-Cookie").get(0).split(";")[0]; - headers = new HttpHeaders(); - headers.add("Cookie", sessionCookie); - httpEntity = new HttpEntity<>(headers); - - //request the protected resource - response = testRestTemplate.exchange(testUrl + "/rating-service/ratings/all", HttpMethod.GET, httpEntity, String.class); - Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); - Assert.assertNotNull(response.getBody()); - - //request the discovery resources as the admin - response = testRestTemplate.exchange(testUrl + "/discovery", HttpMethod.GET, httpEntity, String.class); - Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); - } - -} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/IntegrationLiveTest.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/IntegrationLiveTest.java new file mode 100644 index 0000000000..47a4b744eb --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/IntegrationLiveTest.java @@ -0,0 +1,201 @@ +package com.baeldung.spring.cloud.bootstrap.gateway; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.http.entity.ContentType; +import org.junit.Assert; +import org.junit.Test; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.*; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; + +public class IntegrationLiveTest { + + private TestRestTemplate testRestTemplate = new TestRestTemplate(); + private String testUrl = "http://localhost:8080"; + + @Test + public void testAccess() throws Exception { + ResponseEntity response = testRestTemplate.getForEntity(testUrl + "/book-service/books", String.class); + Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); + Assert.assertNotNull(response.getBody()); + + //try the protected resource and confirm the redirect to login + response = testRestTemplate.getForEntity(testUrl + "/book-service/books/1", String.class); + Assert.assertEquals(HttpStatus.FOUND, response.getStatusCode()); + Assert.assertEquals("http://localhost:8080/login", response.getHeaders().get("Location").get(0)); + + //login as user/password + MultiValueMap form = new LinkedMultiValueMap<>(); + form.add("username", "user"); + form.add("password", "password"); + response = testRestTemplate.postForEntity(testUrl + "/login", form, String.class); + + //extract the session from the cookie and propagate it to the next request + String sessionCookie = response.getHeaders().get("Set-Cookie").get(0).split(";")[0]; + HttpHeaders headers = new HttpHeaders(); + headers.add("Cookie", sessionCookie); + HttpEntity httpEntity = new HttpEntity<>(headers); + + addBook(); + + //request the protected resource + response = testRestTemplate.exchange(testUrl + "/book-service/books/1", HttpMethod.GET, httpEntity, String.class); + Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); + Assert.assertNotNull(response.getBody()); + + addRatings(); + + //request the admin protected resource to determine it is still protected + response = testRestTemplate.exchange(testUrl + "/rating-service/ratings", HttpMethod.GET, httpEntity, String.class); + Assert.assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); + + //login as the admin + form.clear(); + form.add("username", "admin"); + form.add("password", "admin"); + response = testRestTemplate.postForEntity(testUrl + "/login", form, String.class); + + //extract the session from the cookie and propagate it to the next request + sessionCookie = response.getHeaders().get("Set-Cookie").get(0).split(";")[0]; + headers = new HttpHeaders(); + headers.add("Cookie", sessionCookie); + httpEntity = new HttpEntity<>(headers); + + //request the protected resource + response = testRestTemplate.exchange(testUrl + "/rating-service/ratings", HttpMethod.GET, httpEntity, String.class); + Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); + Assert.assertNotNull(response.getBody()); + + //request the discovery resources as the admin + response = testRestTemplate.exchange(testUrl + "/discovery", HttpMethod.GET, httpEntity, String.class); + Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); + } + + private void addRatings() { + //login as user/password + MultiValueMap form = new LinkedMultiValueMap<>(); + form.add("username", "user"); + form.add("password", "password"); + ResponseEntity response = testRestTemplate.postForEntity(testUrl + "/login", form, String.class); + + //extract the session from the cookie and propagate it to the next request + String sessionCookie = response.getHeaders().get("Set-Cookie").get(0).split(";")[0]; + HttpHeaders headers = new HttpHeaders(); + headers.add("Cookie", sessionCookie); + headers.add("ContentType", ContentType.APPLICATION_JSON.getMimeType()); + Rating rating = new Rating(1L, 4); + + HttpEntity httpEntity = new HttpEntity<>(rating, headers); + + //request the protected resource + ResponseEntity bookResponse = testRestTemplate.postForEntity(testUrl + "/rating-service/ratings", httpEntity, Rating.class); + Assert.assertEquals(HttpStatus.OK, bookResponse.getStatusCode()); + Assert.assertEquals(rating.getBookId(), bookResponse.getBody().getBookId()); + Assert.assertEquals(rating.getStars(), bookResponse.getBody().getStars()); + } + + private void addBook(){ + //login as user/password + MultiValueMap form = new LinkedMultiValueMap<>(); + form.add("username", "admin"); + form.add("password", "admin"); + ResponseEntity response = testRestTemplate.postForEntity(testUrl + "/login", form, String.class); + + //extract the session from the cookie and propagate it to the next request + String sessionCookie = response.getHeaders().get("Set-Cookie").get(0).split(";")[0]; + HttpHeaders headers = new HttpHeaders(); + headers.add("Cookie", sessionCookie); + headers.add("ContentType", ContentType.APPLICATION_JSON.getMimeType()); + Book book = new Book("Baeldung", "How to spring cloud"); + + HttpEntity httpEntity = new HttpEntity<>(book, headers); + + //request the protected resource + ResponseEntity bookResponse = testRestTemplate.postForEntity(testUrl + "/book-service/books", httpEntity, Book.class); + Assert.assertEquals(HttpStatus.OK, bookResponse.getStatusCode()); + Assert.assertEquals(book.getAuthor(), bookResponse.getBody().getAuthor()); + Assert.assertEquals(book.getTitle(), bookResponse.getBody().getTitle()); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Book { + + private Long id; + private String author; + private String title; + + public Book() { + } + + public Book(String author, String title) { + this.author = author; + this.title = title; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Rating { + private Long id; + private Long bookId; + private int stars; + + public Rating() { + } + + public Rating(Long bookId, int stars) { + this.bookId = bookId; + this.stars = stars; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getBookId() { + return bookId; + } + + public void setBookId(Long bookId) { + this.bookId = bookId; + } + + public int getStars() { + return stars; + } + + public void setStars(int stars) { + this.stars = stars; + } + } + + +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml b/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml index 9a99054ed5..c351c444f6 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml @@ -42,6 +42,17 @@ spring-boot-starter-data-redis + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + runtime + + org.springframework.boot spring-boot-starter-test diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java index 25ad2a83b2..c5499cd924 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java @@ -3,35 +3,11 @@ package com.baeldung.spring.cloud.bootstrap.svcbook; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.util.Arrays; -import java.util.List; @SpringBootApplication @EnableEurekaClient -@RestController -@RequestMapping("/books") public class BookServiceApplication { public static void main(String[] args) { SpringApplication.run(BookServiceApplication.class, args); } - - private List bookList = Arrays.asList( - new Book(1L, "Baeldung goes to the market", "Tim Schimandle"), - new Book(2L, "Baeldung goes to the park", "Slavisa") - ); - - @GetMapping("") - public List findAllBooks() { - return bookList; - } - - @GetMapping("/{bookId}") - public Book findBook(@PathVariable Long bookId) { - return bookList.stream().filter(b -> b.getId().equals(bookId)).findFirst().orElse(null); - } } diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java index 300b4d7c5a..6aa996c575 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java @@ -2,6 +2,7 @@ package com.baeldung.spring.cloud.bootstrap.svcbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @@ -22,8 +23,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { http.httpBasic() .disable() .authorizeRequests() - .antMatchers("/books").permitAll() - .antMatchers("/books/*").hasAnyRole("USER", "ADMIN") + .antMatchers(HttpMethod.GET, "/books").permitAll() + .antMatchers(HttpMethod.GET, "/books/*").permitAll() + .antMatchers(HttpMethod.POST, "/books").hasRole("ADMIN") + .antMatchers(HttpMethod.PATCH, "/books/*").hasRole("ADMIN") + .antMatchers(HttpMethod.DELETE, "/books/*").hasRole("ADMIN") .anyRequest().authenticated() .and() .csrf() diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/Book.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/Book.java similarity index 57% rename from spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/Book.java rename to spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/Book.java index e652437454..33ea8dcb81 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/Book.java +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/Book.java @@ -1,16 +1,21 @@ -package com.baeldung.spring.cloud.bootstrap.svcbook; +package com.baeldung.spring.cloud.bootstrap.svcbook.book; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +@JsonIgnoreProperties(ignoreUnknown = true) public class Book { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String author; private String title; - public Book(Long id, String title, String author) { - this.id = id; - this.author = author; - this.title = title; - } - public Book() { } diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookController.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookController.java new file mode 100644 index 0000000000..d00f114b8c --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookController.java @@ -0,0 +1,40 @@ +package com.baeldung.spring.cloud.bootstrap.svcbook.book; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/books") +public class BookController { + + @Autowired + private BookService bookService; + + @GetMapping("") + public List findAllBooks() { + return bookService.findAllBooks(); + } + + @GetMapping("/{bookId}") + public Book findBook(@PathVariable Long bookId) { + return bookService.findBookById(bookId); + } + + @PostMapping("") + public Book createBook(@RequestBody Book book) { + return bookService.createBook(book); + } + + @DeleteMapping("/{bookId}") + public void deleteBook(@PathVariable Long bookId) { + bookService.deleteBook(bookId); + } + + @PatchMapping("/{bookId") + public Book updateBook(@RequestBody Map updates, @PathVariable Long bookId) { + return bookService.updateBook(updates, bookId); + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookNotFoundException.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookNotFoundException.java new file mode 100644 index 0000000000..f0a4797387 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookNotFoundException.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.cloud.bootstrap.svcbook.book; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(HttpStatus.NOT_FOUND) +class BookNotFoundException extends RuntimeException { + BookNotFoundException(String message) { + super(message); + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookRepository.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookRepository.java new file mode 100644 index 0000000000..66fd3880c5 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookRepository.java @@ -0,0 +1,6 @@ +package com.baeldung.spring.cloud.bootstrap.svcbook.book; + +import org.springframework.data.jpa.repository.JpaRepository; + +interface BookRepository extends JpaRepository{ +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookService.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookService.java new file mode 100644 index 0000000000..cfcbf15757 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookService.java @@ -0,0 +1,55 @@ +package com.baeldung.spring.cloud.bootstrap.svcbook.book; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@Service +@Transactional(readOnly = true) +public class BookService { + + @Autowired + private BookRepository bookRepository; + + public List findAllBooks() { + return bookRepository.findAll(); + } + + public Book findBookById(Long bookId) { + return Optional.ofNullable(bookRepository.findOne(bookId)) + .orElseThrow(() -> new BookNotFoundException("Book not found. ID: " + bookId)); + } + + @Transactional(propagation = Propagation.REQUIRED) + public Book createBook(Book book) { + Book newBook = new Book(); + newBook.setTitle(book.getTitle()); + newBook.setAuthor(book.getAuthor()); + return bookRepository.save(newBook); + } + + @Transactional(propagation = Propagation.REQUIRED) + public void deleteBook(Long bookId) { + bookRepository.delete(bookId); + } + + @Transactional(propagation = Propagation.REQUIRED) + public Book updateBook(Map updates, Long bookId) { + Book book = findBookById(bookId); + updates.keySet().forEach(key -> { + switch (key) { + case "author": + book.setAuthor(updates.get(key)); + break; + case "title": + book.setTitle(updates.get(key)); + } + }); + return bookRepository.save(book); + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml b/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml index 35da8beba8..2285286812 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml @@ -42,6 +42,17 @@ spring-boot-starter-data-redis + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + runtime + + org.springframework.boot spring-boot-starter-test diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java index 11fb5f06b6..61074e0bcc 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java @@ -3,39 +3,11 @@ package com.baeldung.spring.cloud.bootstrap.svcrating; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; @SpringBootApplication @EnableEurekaClient -@RestController -@RequestMapping("/ratings") public class RatingServiceApplication { public static void main(String[] args) { SpringApplication.run(RatingServiceApplication.class, args); } - - private List ratingList = Arrays.asList( - new Rating(1L, 1L, 2), - new Rating(2L, 1L, 3), - new Rating(3L, 2L, 4), - new Rating(4L, 2L, 5) - ); - - @GetMapping("") - public List findRatingsByBookId(@RequestParam Long bookId) { - return bookId == null || bookId.equals(0L) ? Collections.EMPTY_LIST : ratingList.stream().filter(r -> r.getBookId().equals(bookId)).collect(Collectors.toList()); - } - - @GetMapping("/all") - public List findAllRatings() { - return ratingList; - } } \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java index 371dc810d5..171fbba7af 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java @@ -2,6 +2,7 @@ package com.baeldung.spring.cloud.bootstrap.svcrating; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @@ -22,8 +23,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { http.httpBasic() .disable() .authorizeRequests() - .antMatchers("/ratings").hasRole("USER") - .antMatchers("/ratings/all").hasRole("ADMIN") + .regexMatchers("^/ratings\\?bookId.*$").authenticated() + .antMatchers(HttpMethod.POST,"/ratings").authenticated() + .antMatchers(HttpMethod.PATCH,"/ratings/*").hasRole("ADMIN") + .antMatchers(HttpMethod.DELETE,"/ratings/*").hasRole("ADMIN") + .antMatchers(HttpMethod.GET,"/ratings").hasRole("ADMIN") .anyRequest().authenticated() .and() .csrf() diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/Rating.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/Rating.java similarity index 62% rename from spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/Rating.java rename to spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/Rating.java index 5dd3572098..ae44f9ae2e 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/Rating.java +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/Rating.java @@ -1,6 +1,18 @@ -package com.baeldung.spring.cloud.bootstrap.svcrating; +package com.baeldung.spring.cloud.bootstrap.svcrating.rating; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +@JsonIgnoreProperties(ignoreUnknown = true) public class Rating { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private Long bookId; private int stars; diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingController.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingController.java new file mode 100644 index 0000000000..83452ad747 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingController.java @@ -0,0 +1,38 @@ +package com.baeldung.spring.cloud.bootstrap.svcrating.rating; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/ratings") +public class RatingController { + + @Autowired + private RatingService ratingService; + + @GetMapping("") + public List findRatingsByBookId(@RequestParam(required = false, defaultValue = "0") Long bookId) { + if (bookId.equals(0L)) { + return ratingService.findAllRatings(); + } + return ratingService.findRatingsByBookId(bookId); + } + + @PostMapping("") + public Rating createRating(@RequestBody Rating rating) { + return ratingService.createRating(rating); + } + + @DeleteMapping("/{ratingId}") + public void deleteRating(@PathVariable Long ratingId) { + ratingService.deleteRating(ratingId); + } + + @PatchMapping("/{ratingId") + public Rating updateRating(@RequestBody Map updates, @PathVariable Long ratingId) { + return ratingService.updateRating(updates, ratingId); + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingNotFoundException.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingNotFoundException.java new file mode 100644 index 0000000000..473d636a71 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingNotFoundException.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.cloud.bootstrap.svcrating.rating; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(HttpStatus.NOT_FOUND) +class RatingNotFoundException extends RuntimeException { + RatingNotFoundException(String message) { + super(message); + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingRepository.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingRepository.java new file mode 100644 index 0000000000..08d781b5a3 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.cloud.bootstrap.svcrating.rating; + +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +interface RatingRepository extends JpaRepository{ + List findRatingsByBookId(Long bookId); +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingService.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingService.java new file mode 100644 index 0000000000..a2360b7be5 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingService.java @@ -0,0 +1,57 @@ +package com.baeldung.spring.cloud.bootstrap.svcrating.rating; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@Service +@Transactional(readOnly = true) +public class RatingService { + + @Autowired + private RatingRepository ratingRepository; + + public Rating findRatingById(Long ratingId) { + return Optional.ofNullable(ratingRepository.findOne(ratingId)) + .orElseThrow(() -> new RatingNotFoundException("Rating not found. ID: " + ratingId)); + } + + public List findRatingsByBookId(Long bookId) { + return ratingRepository.findRatingsByBookId(bookId); + } + + public List findAllRatings() { + return ratingRepository.findAll(); + } + + @Transactional(propagation = Propagation.REQUIRED) + public Rating createRating(Rating rating) { + Rating newRating = new Rating(); + newRating.setBookId(rating.getBookId()); + newRating.setStars(rating.getStars()); + return ratingRepository.save(newRating); + } + + @Transactional(propagation = Propagation.REQUIRED) + public void deleteRating(Long ratingId) { + ratingRepository.delete(ratingId); + } + + @Transactional(propagation = Propagation.REQUIRED) + public Rating updateRating(Map updates, Long ratingId) { + Rating rating = findRatingById(ratingId); + updates.keySet().forEach(key -> { + switch (key) { + case "stars": + rating.setStars(Integer.parseInt(updates.get(key))); + break; + } + }); + return ratingRepository.save(rating); + } +} diff --git a/spring-core/src/main/java/com/baeldung/Ebook.java b/spring-core/src/main/java/com/baeldung/Ebook.java new file mode 100644 index 0000000000..fc29ddfcf5 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/Ebook.java @@ -0,0 +1,20 @@ +package com.baeldung; + +public class Ebook { + + private int bookId; + private String bookTitle; + + public int getBookId() { + return bookId; + } + public void setBookId(int bookId) { + this.bookId = bookId; + } + public String getBookTitle() { + return bookTitle; + } + public void setBookTitle(String bookTitle) { + this.bookTitle = bookTitle; + } +} diff --git a/spring-core/src/main/java/com/baeldung/EbookRepository.java b/spring-core/src/main/java/com/baeldung/EbookRepository.java new file mode 100644 index 0000000000..661283c355 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/EbookRepository.java @@ -0,0 +1,5 @@ +package com.baeldung; + +public interface EbookRepository { + String titleById(int id); +} diff --git a/spring-core/src/main/java/com/baeldung/LibraryUtils.java b/spring-core/src/main/java/com/baeldung/LibraryUtils.java new file mode 100644 index 0000000000..49af60c89d --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/LibraryUtils.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.beans.factory.annotation.Autowired; + +public class LibraryUtils { + @Autowired + private EbookRepository eBookRepository; + + public String findBook(int id) { + return eBookRepository.titleById(id); + } +} diff --git a/spring-core/src/main/java/com/baeldung/Member.java b/spring-core/src/main/java/com/baeldung/Member.java new file mode 100644 index 0000000000..ceebb32017 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/Member.java @@ -0,0 +1,20 @@ +package com.baeldung; + +public class Member { + + private int memberId; + private String memberName; + + public int getMemberId() { + return memberId; + } + public void setMemberId(int memberId) { + this.memberId = memberId; + } + public String getMemberName() { + return memberName; + } + public void setMemberName(String memberName) { + this.memberName = memberName; + } +} diff --git a/spring-core/src/main/java/com/baeldung/Reservation.java b/spring-core/src/main/java/com/baeldung/Reservation.java new file mode 100644 index 0000000000..ed33bb6464 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/Reservation.java @@ -0,0 +1,14 @@ +package com.baeldung; + +import org.springframework.beans.factory.annotation.Autowired; + +public class Reservation { + private Member member; + private Ebook eBook; + + @Autowired + public Reservation(Member member, Ebook eBook) { + this.member = member; + this.eBook = eBook; + } +} diff --git a/spring-data-mongodb/README.md b/spring-data-mongodb/README.md index d656bc897c..c2a1f703b5 100644 --- a/spring-data-mongodb/README.md +++ b/spring-data-mongodb/README.md @@ -9,3 +9,4 @@ - [Custom Cascading in Spring Data MongoDB](http://www.baeldung.com/cascading-with-dbref-and-lifecycle-events-in-spring-data-mongodb) - [GridFS in Spring Data MongoDB](http://www.baeldung.com/spring-data-mongodb-gridfs) - [Introduction to Spring Data MongoDB](http://www.baeldung.com/spring-data-mongodb-tutorial) +- [Spring Data MongoDB: Projections and Aggregations](http://www.baeldung.com/spring-data-mongodb-projections-aggregations) diff --git a/spring-data-neo4j/README.md b/spring-data-neo4j/README.md index 0f13d9dbc9..03c9ed333d 100644 --- a/spring-data-neo4j/README.md +++ b/spring-data-neo4j/README.md @@ -2,6 +2,7 @@ ### Relevant Articles: - [Introduction to Spring Data Neo4j](http://www.baeldung.com/spring-data-neo4j-intro) +- [A Guide to Neo4J with Java](http://www.baeldung.com/java-neo4j) ### Build the Project with Tests Running ``` diff --git a/spring-data-rest/src/main/test/com/baeldung/validator/SpringDataRestValidatorTest.java b/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorTest.java similarity index 75% rename from spring-data-rest/src/main/test/com/baeldung/validator/SpringDataRestValidatorTest.java rename to spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorTest.java index b185c6d5ab..300fc081d3 100644 --- a/spring-data-rest/src/main/test/com/baeldung/validator/SpringDataRestValidatorTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorTest.java @@ -1,100 +1,86 @@ -package com.baeldung.validator; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.ResultActions; -import org.springframework.test.web.servlet.ResultMatcher; -import org.springframework.web.context.WebApplicationContext; - -import com.baeldung.SpringDataRestApplication; -import com.baeldung.models.WebsiteUser; -import com.fasterxml.jackson.databind.ObjectMapper; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = SpringDataRestApplication.class) -@WebAppConfiguration -public class SpringDataRestValidatorTest { - public static final String URL = "http://localhost"; - - private MockMvc mockMvc; - - @Autowired - protected WebApplicationContext wac; - - @Before - public void setup() { - mockMvc = webAppContextSetup(wac).build(); - } - - @Test - public void whenStartingApplication_thenCorrectStatusCode() throws Exception { - mockMvc.perform(get("/users")).andExpect(status().is2xxSuccessful()); - }; - - @Test - public void whenAddingNewCorrectUser_thenCorrectStatusCodeAndResponse() throws Exception { - WebsiteUser user = new WebsiteUser(); - user.setEmail("john.doe@john.com"); - user.setName("John Doe"); - - mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) - .andExpect(status().is2xxSuccessful()) - .andExpect(redirectedUrl("http://localhost/users/1")); - } - - @Test - public void whenAddingNewUserWithoutName_thenErrorStatusCodeAndResponse() throws Exception { - WebsiteUser user = new WebsiteUser(); - user.setEmail("john.doe@john.com"); - - mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) - .andExpect(status().isNotAcceptable()) - .andExpect(redirectedUrl(null)); - } - - @Test - public void whenAddingNewUserWithEmptyName_thenErrorStatusCodeAndResponse() throws Exception { - WebsiteUser user = new WebsiteUser(); - user.setEmail("john.doe@john.com"); - user.setName(""); - mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) - .andExpect(status().isNotAcceptable()) - .andExpect(redirectedUrl(null)); - } - - @Test - public void whenAddingNewUserWithoutEmail_thenErrorStatusCodeAndResponse() throws Exception { - WebsiteUser user = new WebsiteUser(); - user.setName("John Doe"); - - mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) - .andExpect(status().isNotAcceptable()) - .andExpect(redirectedUrl(null)); - } - - @Test - public void whenAddingNewUserWithEmptyEmail_thenErrorStatusCodeAndResponse() throws Exception { - WebsiteUser user = new WebsiteUser(); - user.setName("John Doe"); - user.setEmail(""); - mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) - .andExpect(status().isNotAcceptable()) - .andExpect(redirectedUrl(null)); - } - -} +package com.baeldung.validator; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.SpringDataRestApplication; +import com.baeldung.models.WebsiteUser; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = SpringDataRestApplication.class) +@WebAppConfiguration +public class SpringDataRestValidatorTest { + public static final String URL = "http://localhost"; + + private MockMvc mockMvc; + + @Autowired + protected WebApplicationContext wac; + + @Before + public void setup() { + mockMvc = webAppContextSetup(wac).build(); + } + + @Test + public void whenStartingApplication_thenCorrectStatusCode() throws Exception { + mockMvc.perform(get("/users")).andExpect(status().is2xxSuccessful()); + }; + + @Test + public void whenAddingNewCorrectUser_thenCorrectStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setEmail("john.doe@john.com"); + user.setName("John Doe"); + + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))).andExpect(status().is2xxSuccessful()).andExpect(redirectedUrl("http://localhost/users/1")); + } + + @Test + public void whenAddingNewUserWithoutName_thenErrorStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setEmail("john.doe@john.com"); + + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))).andExpect(status().isNotAcceptable()).andExpect(redirectedUrl(null)); + } + + @Test + public void whenAddingNewUserWithEmptyName_thenErrorStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setEmail("john.doe@john.com"); + user.setName(""); + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))).andExpect(status().isNotAcceptable()).andExpect(redirectedUrl(null)); + } + + @Test + public void whenAddingNewUserWithoutEmail_thenErrorStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setName("John Doe"); + + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))).andExpect(status().isNotAcceptable()).andExpect(redirectedUrl(null)); + } + + @Test + public void whenAddingNewUserWithEmptyEmail_thenErrorStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setName("John Doe"); + user.setEmail(""); + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))).andExpect(status().isNotAcceptable()).andExpect(redirectedUrl(null)); + } + +} diff --git a/spring-data-solr/pom.xml b/spring-data-solr/pom.xml index 2aa9f86a96..e43b3ff774 100644 --- a/spring-data-solr/pom.xml +++ b/spring-data-solr/pom.xml @@ -51,12 +51,6 @@ ${spring.version} test - diff --git a/spring-hibernate4/README.md b/spring-hibernate4/README.md index 7888e8b4ee..02888c4ad0 100644 --- a/spring-hibernate4/README.md +++ b/spring-hibernate4/README.md @@ -12,6 +12,7 @@ - [Hibernate: save, persist, update, merge, saveOrUpdate](http://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate/) - [Eager/Lazy Loading In Hibernate](http://www.baeldung.com/hibernate-lazy-eager-loading) - [Hibernate Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries) +- [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) ### Quick Start @@ -22,3 +23,4 @@ mvn install mvn cargo:run ``` - **note**: starts on port `8082` + diff --git a/spring-jersey/README.md b/spring-jersey/README.md index 2767ceb9a7..8b2eecc0e1 100644 --- a/spring-jersey/README.md +++ b/spring-jersey/README.md @@ -1,3 +1,5 @@ ========= ## REST API with Jersey & Spring Example Project +- [REST API with Jersey and Spring](http://www.baeldung.com/jersey-rest-api-with-spring) +- [JAX-RS Client with Jersey](http://www.baeldung.com/jersey-jax-rs-client) diff --git a/spring-mobile/README.md b/spring-mobile/README.md new file mode 100644 index 0000000000..e3d23bcda6 --- /dev/null +++ b/spring-mobile/README.md @@ -0,0 +1,4 @@ +## Relevant articles: + +- [A Guide to Spring Mobile](http://www.baeldung.com/spring-mobile) + diff --git a/spring-mvc-email/README.md b/spring-mvc-email/README.md index 0de6532393..aa880188d7 100644 --- a/spring-mvc-email/README.md +++ b/spring-mvc-email/README.md @@ -1,3 +1,7 @@ +## Relevant articles: + +- [Guide to Spring Email](http://www.baeldung.com/spring-email) + ## Spring MVC Email Example Spring MVC project to send email from web form. @@ -10,4 +14,4 @@ Type http://localhost:8080 in your browser to open the application. ### Sending test emails -Follow UI links to send simple email, email using template or email with attachment. \ No newline at end of file +Follow UI links to send simple email, email using template or email with attachment. diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 0f267c5ec9..4d3e58558b 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -18,3 +18,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) - [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) - [Introduction to HtmlUnit](http://www.baeldung.com/htmlunit) +- [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) +- [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) +- [Uploading and Displaying Excel Files with Spring MVC](http://www.baeldung.com/spring-mvc-excel-files) diff --git a/spring-mvc-java/persons.xls b/spring-mvc-java/persons.xls new file mode 100644 index 0000000000..ea270f69cc Binary files /dev/null and b/spring-mvc-java/persons.xls differ diff --git a/spring-mvc-java/persons.xlsx b/spring-mvc-java/persons.xlsx new file mode 100644 index 0000000000..1f58606532 Binary files /dev/null and b/spring-mvc-java/persons.xlsx differ diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 9513c81064..ef18cef3e0 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -161,26 +161,11 @@ - - org.apache.poi - poi - ${poi.version} - org.apache.poi poi-ooxml ${poi.version} - - org.apache.poi - poi-ooxml-schemas - ${poi.version} - - - org.jxls - jxls-jexcel - ${jexcel.version} - @@ -395,7 +380,6 @@ 3.16-beta1 - 1.0.6 diff --git a/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java b/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java index 5cf74aff63..0519a8f3c7 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java +++ b/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java @@ -1,140 +1,185 @@ package com.baeldung.excel; import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFCellStyle; +import org.apache.poi.xssf.usermodel.XSSFColor; import org.apache.poi.xssf.usermodel.XSSFFont; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFCellStyle; +import org.apache.poi.hssf.usermodel.HSSFFont; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.FillPatternType; + import java.io.File; -import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.IOException; -import java.io.InputStream; import java.util.Map; import java.util.HashMap; import java.util.ArrayList; -import org.springframework.stereotype.Service; +import java.util.List; +import java.util.stream.IntStream; -@Service public class ExcelPOIHelper { - public Map> readExcel(String fileLocation) throws IOException { + public Map> readExcel(String fileLocation) throws IOException { - Map> data = new HashMap>(); - FileInputStream file = new FileInputStream(new File(fileLocation)); - Workbook workbook = new XSSFWorkbook(file); - Sheet sheet = workbook.getSheetAt(0); - int i = 0; - for (Row row : sheet) { - data.put(i, new ArrayList()); - for (Cell cell : row) { - switch (cell.getCellTypeEnum()) { - case STRING: - data.get(i) - .add(cell.getRichStringCellValue() - .getString()); - break; - case NUMERIC: - if (DateUtil.isCellDateFormatted(cell)) { - data.get(i) - .add(cell.getDateCellValue() + ""); - } else { - data.get(i) - .add(cell.getNumericCellValue() + ""); + Map> data = new HashMap<>(); + FileInputStream fis = new FileInputStream(new File(fileLocation)); + + if (fileLocation.endsWith(".xls")) { + data = readHSSFWorkbook(fis); + } else if (fileLocation.endsWith(".xlsx")) { + data = readXSSFWorkbook(fis); + } + + int maxNrCols = data.values().stream() + .mapToInt(List::size) + .max() + .orElse(0); + + data.values().stream() + .filter(ls -> ls.size() < maxNrCols) + .forEach(ls -> { + IntStream.range(ls.size(), maxNrCols) + .forEach(i -> ls.add(new MyCell(""))); + }); + + return data; + } + + private String readCellContent(Cell cell) { + String content; + switch (cell.getCellTypeEnum()) { + case STRING: + content = cell.getStringCellValue(); + break; + case NUMERIC: + if (DateUtil.isCellDateFormatted(cell)) { + content = cell.getDateCellValue() + ""; + } else { + content = cell.getNumericCellValue() + ""; + } + break; + case BOOLEAN: + content = cell.getBooleanCellValue() + ""; + break; + case FORMULA: + content = cell.getCellFormula() + ""; + break; + default: + content = ""; + } + return content; + } + + private Map> readHSSFWorkbook(FileInputStream fis) throws IOException { + Map> data = new HashMap<>(); + HSSFWorkbook workbook = null; + try { + workbook = new HSSFWorkbook(fis); + + HSSFSheet sheet = workbook.getSheetAt(0); + for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) { + HSSFRow row = sheet.getRow(i); + data.put(i, new ArrayList<>()); + if (row != null) { + for (int j = 0; j < row.getLastCellNum(); j++) { + HSSFCell cell = row.getCell(j); + if (cell != null) { + HSSFCellStyle cellStyle = cell.getCellStyle(); + + MyCell myCell = new MyCell(); + + HSSFColor bgColor = cellStyle.getFillForegroundColorColor(); + if (bgColor != null) { + short[] rgbColor = bgColor.getTriplet(); + myCell.setBgColor("rgb(" + rgbColor[0] + "," + rgbColor[1] + "," + rgbColor[2] + ")"); + } + HSSFFont font = cell.getCellStyle() + .getFont(workbook); + myCell.setTextSize(font.getFontHeightInPoints() + ""); + if (font.getBold()) { + myCell.setTextWeight("bold"); + } + HSSFColor textColor = font.getHSSFColor(workbook); + if (textColor != null) { + short[] rgbColor = textColor.getTriplet(); + myCell.setTextColor("rgb(" + rgbColor[0] + "," + rgbColor[1] + "," + rgbColor[2] + ")"); + } + myCell.setContent(readCellContent(cell)); + data.get(i) + .add(myCell); + } else { + data.get(i) + .add(new MyCell("")); + } } - break; - case BOOLEAN: - data.get(i) - .add(cell.getBooleanCellValue() + ""); - break; - case FORMULA: - data.get(i) - .add(cell.getCellFormula() + ""); - break; - default: - data.get(i) - .add(" "); } } - i++; - } - if (workbook != null){ - workbook.close(); + } finally { + if (workbook != null) { + workbook.close(); + } } return data; } - public void writeExcel() throws IOException { - Workbook workbook = new XSSFWorkbook(); - + private Map> readXSSFWorkbook(FileInputStream fis) throws IOException { + XSSFWorkbook workbook = null; + Map> data = new HashMap<>(); try { - Sheet sheet = workbook.createSheet("Persons"); - sheet.setColumnWidth(0, 6000); - sheet.setColumnWidth(1, 4000); - Row header = sheet.createRow(0); + workbook = new XSSFWorkbook(fis); + XSSFSheet sheet = workbook.getSheetAt(0); - CellStyle headerStyle = workbook.createCellStyle(); + for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) { + XSSFRow row = sheet.getRow(i); + data.put(i, new ArrayList<>()); + if (row != null) { + for (int j = 0; j < row.getLastCellNum(); j++) { + XSSFCell cell = row.getCell(j); + if (cell != null) { + XSSFCellStyle cellStyle = cell.getCellStyle(); - headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex()); - headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - - XSSFFont font = ((XSSFWorkbook) workbook).createFont(); - font.setFontName("Arial"); - font.setFontHeightInPoints((short) 16); - font.setBold(true); - headerStyle.setFont(font); - - Cell headerCell = header.createCell(0); - headerCell.setCellValue("Name"); - headerCell.setCellStyle(headerStyle); - - headerCell = header.createCell(1); - headerCell.setCellValue("Age"); - headerCell.setCellStyle(headerStyle); - - CellStyle style = workbook.createCellStyle(); - style.setWrapText(true); - - Row row = sheet.createRow(2); - Cell cell = row.createCell(0); - cell.setCellValue("John Smith"); - cell.setCellStyle(style); - - cell = row.createCell(1); - cell.setCellValue(20); - cell.setCellStyle(style); - - row = sheet.createRow(3); - cell = row.createCell(0); - cell.setCellValue("Ana Johnson"); - cell.setCellStyle(style); - - cell = row.createCell(1); - cell.setCellValue(30); - cell.setCellStyle(style); - - File currDir = new File("."); - String path = currDir.getAbsolutePath(); - String fileLocation = path.substring(0, path.length() - 1) + "temp.xlsx"; - - FileOutputStream outputStream = new FileOutputStream(fileLocation); - workbook.write(outputStream); - } finally { - if (workbook != null) { - try { - workbook.close(); - } catch (IOException e) { - e.printStackTrace(); + MyCell myCell = new MyCell(); + XSSFColor bgColor = cellStyle.getFillForegroundColorColor(); + if (bgColor != null) { + byte[] rgbColor = bgColor.getRGB(); + myCell.setBgColor("rgb(" + (rgbColor[0] < 0 ? (rgbColor[0] + 0xff) : rgbColor[0]) + "," + (rgbColor[1] < 0 ? (rgbColor[1] + 0xff) : rgbColor[1]) + "," + (rgbColor[2] < 0 ? (rgbColor[2] + 0xff) : rgbColor[2]) + ")"); + } + XSSFFont font = cellStyle.getFont(); + myCell.setTextSize(font.getFontHeightInPoints() + ""); + if (font.getBold()) { + myCell.setTextWeight("bold"); + } + XSSFColor textColor = font.getXSSFColor(); + if (textColor != null) { + byte[] rgbColor = textColor.getRGB(); + myCell.setTextColor("rgb(" + (rgbColor[0] < 0 ? (rgbColor[0] + 0xff) : rgbColor[0]) + "," + (rgbColor[1] < 0 ? (rgbColor[1] + 0xff) : rgbColor[1]) + "," + (rgbColor[2] < 0 ? (rgbColor[2] + 0xff) : rgbColor[2]) + ")"); + } + myCell.setContent(readCellContent(cell)); + data.get(i) + .add(myCell); + } else { + data.get(i) + .add(new MyCell("")); + } + } } } + } finally { + if (workbook != null) { + workbook.close(); + } } + return data; } } \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/excel/JExcelHelper.java b/spring-mvc-java/src/main/java/com/baeldung/excel/JExcelHelper.java deleted file mode 100644 index d0e33bf471..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/excel/JExcelHelper.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.baeldung.excel; - -import jxl.Sheet; -import jxl.Workbook; -import jxl.format.Colour; -import jxl.read.biff.BiffException; -import jxl.write.*; -import jxl.write.Number; -import org.springframework.stereotype.Service; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -@Service -public class JExcelHelper { - - public Map> readJExcel(String fileLocation) throws IOException, BiffException { - Map> data = new HashMap<>(); - - Workbook workbook = Workbook.getWorkbook(new File(fileLocation)); - Sheet sheet = workbook.getSheet(0); - int rows = sheet.getRows(); - int columns = sheet.getColumns(); - - for (int i = 0; i < rows; i++) { - data.put(i, new ArrayList<>()); - for (int j = 0; j < columns; j++) { - data.get(i).add(sheet.getCell(j, i).getContents()); - } - } - return data; - } - - public void writeJExcel() throws IOException, WriteException { - WritableWorkbook workbook = null; - try { - File currDir = new File("."); - String path = currDir.getAbsolutePath(); - String fileLocation = path.substring(0, path.length() - 1) + "temp.xls"; - - workbook = Workbook.createWorkbook(new File(fileLocation)); - - WritableSheet sheet = workbook.createSheet("Sheet 1", 0); - - WritableCellFormat headerFormat = new WritableCellFormat(); - WritableFont font = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD); - headerFormat.setFont(font); - headerFormat.setBackground(Colour.LIGHT_BLUE); - headerFormat.setWrap(true); - Label headerLabel = new Label(0, 0, "Name", headerFormat); - sheet.setColumnView(0, 60); - sheet.addCell(headerLabel); - - headerLabel = new Label(1, 0, "Age", headerFormat); - sheet.setColumnView(0, 40); - sheet.addCell(headerLabel); - - WritableCellFormat cellFormat = new WritableCellFormat(); - cellFormat.setWrap(true); - - Label cellLabel = new Label(0, 2, "John Smith", cellFormat); - sheet.addCell(cellLabel); - Number cellNumber = new Number(1, 2, 20, cellFormat); - sheet.addCell(cellNumber); - - cellLabel = new Label(0, 3, "Ana Johnson", cellFormat); - sheet.addCell(cellLabel); - cellNumber = new Number(1, 3, 30, cellFormat); - sheet.addCell(cellNumber); - - workbook.write(); - } finally { - if (workbook != null) { - workbook.close(); - } - } - - } -} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/excel/MyCell.java b/spring-mvc-java/src/main/java/com/baeldung/excel/MyCell.java new file mode 100644 index 0000000000..409829bc35 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/excel/MyCell.java @@ -0,0 +1,57 @@ +package com.baeldung.excel; + +public class MyCell { + private String content; + private String textColor; + private String bgColor; + private String textSize; + private String textWeight; + + public MyCell() { + } + + public MyCell(String content) { + this.content = content; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public String getTextColor() { + return textColor; + } + + public void setTextColor(String textColor) { + this.textColor = textColor; + } + + public String getBgColor() { + return bgColor; + } + + public void setBgColor(String bgColor) { + this.bgColor = bgColor; + } + + public String getTextSize() { + return textSize; + } + + public void setTextSize(String textSize) { + this.textSize = textSize; + } + + public String getTextWeight() { + return textWeight; + } + + public void setTextWeight(String textWeight) { + this.textWeight = textWeight; + } + +} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 9578303554..11be08a79d 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -108,11 +108,6 @@ public class WebConfig extends WebMvcConfigurerAdapter { configurer.setUrlPathHelper(urlPathHelper); } - @Bean - public JExcelHelper jExcelHelper() { - return new JExcelHelper(); - } - @Bean public ExcelPOIHelper excelPOIHelper() { return new ExcelPOIHelper(); diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/ExcelController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/ExcelController.java index 810282dd65..f76f7441a5 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/ExcelController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/ExcelController.java @@ -10,20 +10,15 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import com.baeldung.excel.*; -import jxl.read.biff.BiffException; import java.util.Map; -import java.util.ArrayList; +import java.util.List; import javax.annotation.Resource; -import jxl.write.WriteException; @Controller public class ExcelController { private String fileLocation; - @Resource(name = "jExcelHelper") - private JExcelHelper jExcelHelper; - @Resource(name = "excelPOIHelper") private ExcelPOIHelper excelPOIHelper; @@ -45,36 +40,19 @@ public class ExcelController { } f.flush(); f.close(); - System.out.println(fileLocation); model.addAttribute("message", "File: " + file.getOriginalFilename() + " has been uploaded successfully!"); return "excel"; } - @RequestMapping(method = RequestMethod.GET, value = "/readJExcel") - public String readJExcel(Model model) throws IOException, BiffException { - - if (fileLocation != null) { - if (fileLocation.endsWith(".xls")) { - Map> data = jExcelHelper.readJExcel(fileLocation); - model.addAttribute("data", data); - } else { - model.addAttribute("message", "Not a valid .xls file!"); - } - } else { - model.addAttribute("message", "File missing! Please upload an excel file."); - } - return "excel"; - } - @RequestMapping(method = RequestMethod.GET, value = "/readPOI") public String readPOI(Model model) throws IOException { if (fileLocation != null) { - if (fileLocation.endsWith(".xlsx")) { - Map> data = excelPOIHelper.readExcel(fileLocation); + if (fileLocation.endsWith(".xlsx") || fileLocation.endsWith(".xls")) { + Map> data = excelPOIHelper.readExcel(fileLocation); model.addAttribute("data", data); } else { - model.addAttribute("message", "Not a valid .xlsx file!"); + model.addAttribute("message", "Not a valid excel file!"); } } else { model.addAttribute("message", "File missing! Please upload an excel file."); @@ -82,24 +60,4 @@ public class ExcelController { return "excel"; } - @RequestMapping(method = RequestMethod.POST, value = "/writeJExcel") - public String writeJExcel(Model model) throws IOException, BiffException, WriteException { - - jExcelHelper.writeJExcel(); - - model.addAttribute("message", "Write successful!"); - - return "excel"; - } - - @RequestMapping(method = RequestMethod.POST, value = "/writePOI") - public String writePOI(Model model) throws IOException { - - excelPOIHelper.writeExcel(); - - model.addAttribute("message", "Write successful!"); - - return "excel"; - } - } \ No newline at end of file diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/excel.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/view/excel.jsp index b50687df15..bcb5a31371 100644 --- a/spring-mvc-java/src/main/webapp/WEB-INF/view/excel.jsp +++ b/spring-mvc-java/src/main/webapp/WEB-INF/view/excel.jsp @@ -1,6 +1,6 @@ <%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> -<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> + pageEncoding="ISO-8859-1"%> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> @@ -8,49 +8,43 @@ Excel Processing - - - - - - + + + -
- - -
-
-${message } -

-
- -
-

-Read file using JExcel     -Read file using Apache POI -

+
+ + +
+
+
+ +
+
${message } +
+
-File content: - - - - - - - - - -
${cell}
-
-

-
- -
-
-
- -
+
+ +
+
+
+ + + + + + + + + + +
+ ${cell.content} +
+
- \ No newline at end of file diff --git a/spring-mvc-simple/README.md b/spring-mvc-simple/README.md new file mode 100644 index 0000000000..ffb02c846a --- /dev/null +++ b/spring-mvc-simple/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [HandlerAdapters in Spring MVC](http://www.baeldung.com/spring-mvc-handler-adapters) diff --git a/spring-reactor/README.md b/spring-reactor/README.md new file mode 100644 index 0000000000..0da2d6be51 --- /dev/null +++ b/spring-reactor/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Introduction to Spring Reactor](http://www.baeldung.com/spring-reactor) diff --git a/spring-remoting/pom.xml b/spring-remoting/pom.xml index a43dd52a3e..52d670a726 100644 --- a/spring-remoting/pom.xml +++ b/spring-remoting/pom.xml @@ -3,16 +3,17 @@ 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"> 4.0.0 + com.baeldung + spring-remoting + pom + 1.0-SNAPSHOT + spring-remoting + Parent for all projects related to Spring Remoting. org.springframework.boot spring-boot-starter-parent 1.4.3.RELEASE - com.baeldung - spring-remoting - 1.0-SNAPSHOT - Parent for all projects related to Spring Remoting. - pom 1.8 @@ -34,6 +35,7 @@ remoting-http + remoting-hessian-burlap \ No newline at end of file diff --git a/spring-remoting/remoting-hessian-burlap/client/pom.xml b/spring-remoting/remoting-hessian-burlap/client/pom.xml new file mode 100644 index 0000000000..11250e63d2 --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/client/pom.xml @@ -0,0 +1,35 @@ + + + + remoting-hessian-burlap + com.baeldung + 1.0-SNAPSHOT + + 4.0.0 + + spring-remoting-hessian-burlap-client + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + ${project.groupId} + api + + + com.caucho + hessian + 4.0.38 + + + \ No newline at end of file diff --git a/spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/BurlapClient.java b/spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/BurlapClient.java new file mode 100644 index 0000000000..477c29eb26 --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/BurlapClient.java @@ -0,0 +1,28 @@ +package com.baeldung.client; + +import com.baeldung.api.BookingException; +import com.baeldung.api.CabBookingService; +import org.springframework.boot.SpringApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.remoting.caucho.BurlapProxyFactoryBean; + +import static java.lang.System.out; + +@Configuration +public class BurlapClient { + + @Bean + public BurlapProxyFactoryBean burlapInvoker() { + BurlapProxyFactoryBean invoker = new BurlapProxyFactoryBean(); + invoker.setServiceUrl("http://localhost:8080/b_booking"); + invoker.setServiceInterface(CabBookingService.class); + return invoker; + } + + public static void main(String[] args) throws BookingException { + CabBookingService service = SpringApplication.run(BurlapClient.class, args).getBean(CabBookingService.class); + out.println(service.bookRide("13 Seagate Blvd, Key Largo, FL 33037")); + } + +} diff --git a/spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/HessianClient.java b/spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/HessianClient.java new file mode 100644 index 0000000000..b5f366094e --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/HessianClient.java @@ -0,0 +1,28 @@ +package com.baeldung.client; + +import com.baeldung.api.BookingException; +import com.baeldung.api.CabBookingService; +import org.springframework.boot.SpringApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.remoting.caucho.HessianProxyFactoryBean; + +import static java.lang.System.out; + +@Configuration +public class HessianClient { + + @Bean + public HessianProxyFactoryBean hessianInvoker() { + HessianProxyFactoryBean invoker = new HessianProxyFactoryBean(); + invoker.setServiceUrl("http://localhost:8080/booking"); + invoker.setServiceInterface(CabBookingService.class); + return invoker; + } + + public static void main(String[] args) throws BookingException { + CabBookingService service = SpringApplication.run(HessianClient.class, args).getBean(CabBookingService.class); + out.println(service.bookRide("13 Seagate Blvd, Key Largo, FL 33037")); + } + +} diff --git a/spring-remoting/remoting-hessian-burlap/pom.xml b/spring-remoting/remoting-hessian-burlap/pom.xml new file mode 100644 index 0000000000..682e460880 --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/pom.xml @@ -0,0 +1,20 @@ + + + + spring-remoting + com.baeldung + 1.0-SNAPSHOT + + pom + + server + client + + 4.0.0 + + remoting-hessian-burlap + + + \ No newline at end of file diff --git a/spring-remoting/remoting-hessian-burlap/server/pom.xml b/spring-remoting/remoting-hessian-burlap/server/pom.xml new file mode 100644 index 0000000000..c97092b247 --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/server/pom.xml @@ -0,0 +1,30 @@ + + + + remoting-hessian-burlap + com.baeldung + 1.0-SNAPSHOT + + 4.0.0 + + remoting-hessian-burlap-server + + + + com.baeldung + spring-remoting-http-server + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-web + + + com.caucho + hessian + 4.0.38 + + + \ No newline at end of file diff --git a/spring-remoting/remoting-hessian-burlap/server/src/main/java/com/baeldung/server/Server.java b/spring-remoting/remoting-hessian-burlap/server/src/main/java/com/baeldung/server/Server.java new file mode 100644 index 0000000000..9b7e463871 --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/server/src/main/java/com/baeldung/server/Server.java @@ -0,0 +1,37 @@ +package com.baeldung.server; + +import com.baeldung.api.CabBookingService; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.remoting.caucho.BurlapServiceExporter; +import org.springframework.remoting.caucho.HessianServiceExporter; +import org.springframework.remoting.support.RemoteExporter; + +@Configuration @ComponentScan @EnableAutoConfiguration public class Server { + + @Bean CabBookingService bookingService() { + return new CabBookingServiceImpl(); + } + + @Bean(name = "/booking") RemoteExporter hessianService(CabBookingService service) { + HessianServiceExporter exporter = new HessianServiceExporter(); + exporter.setService(bookingService()); + exporter.setServiceInterface(CabBookingService.class); + return exporter; + } + + @Bean(name = "/b_booking") RemoteExporter burlapService(CabBookingService service) { + BurlapServiceExporter exporter = new BurlapServiceExporter(); + exporter.setService(bookingService()); + exporter.setServiceInterface(CabBookingService.class); + return exporter; + } + + public static void main(String[] args) { + SpringApplication.run(Server.class, args); + } + +} \ No newline at end of file diff --git a/spring-security-rest/README.md b/spring-security-rest/README.md index a1dfa32c6d..92b759a66a 100644 --- a/spring-security-rest/README.md +++ b/spring-security-rest/README.md @@ -13,3 +13,4 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Custom Error Message Handling for REST API](http://www.baeldung.com/global-error-handler-in-a-spring-rest-api) - [An Intro to Spring HATEOAS](http://www.baeldung.com/spring-hateoas-tutorial) - [Spring Security Context Propagation with @Async](http://www.baeldung.com/spring-security-async-principal-propagation) +- [Servlet 3 Async Support with Spring MVC and Spring Security](http://www.baeldung.com/spring-mvc-async-security) diff --git a/spring-sleuth/README.md b/spring-sleuth/README.md new file mode 100644 index 0000000000..47aa126939 --- /dev/null +++ b/spring-sleuth/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Spring Cloud Sleuth in a Monolith Application](http://www.baeldung.com/spring-cloud-sleuth-single-application) diff --git a/static-analysis/README.md b/static-analysis/README.md new file mode 100644 index 0000000000..74cc64b90d --- /dev/null +++ b/static-analysis/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Introduction to PMD](http://www.baeldung.com/pmd) diff --git a/testng/pom.xml b/testng/pom.xml new file mode 100644 index 0000000000..272b1d316d --- /dev/null +++ b/testng/pom.xml @@ -0,0 +1,115 @@ + + + 4.0.0 + com.baeldung + testng + 0.1.0-SNAPSHOT + jar + testng + + + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + + + org.testng + testng + ${testng.version} + test + + + + + + testng + + + src/main/resources + true + + + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + + true + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + prepare-package + + copy-dependencies + + + ${project.build.directory}/libs + + + + + + + + + + + + 1.7.21 + 1.1.7 + + + 6.10 + + + 3.6.0 + 2.19.1 + + + + + \ No newline at end of file diff --git a/testng/src/test/java/baeldung/com/DependentTests.java b/testng/src/test/java/baeldung/com/DependentTests.java new file mode 100644 index 0000000000..b60f8a6c0d --- /dev/null +++ b/testng/src/test/java/baeldung/com/DependentTests.java @@ -0,0 +1,25 @@ +package baeldung.com; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class DependentTests { + + private static final Logger LOGGER = LoggerFactory.getLogger(DependentTests.class); + + private String email = "abc@qwe.com"; + + @Test + public void givenEmail_ifValid_thenTrue() { + boolean valid = email.contains("@"); + Assert.assertEquals(valid, true); + } + + @Test(dependsOnMethods = {"givenEmail_ifValid_thenTrue"}) + public void givenValidEmail_whenLoggedIn_thenTrue() { + LOGGER.info("Email {} valid >> logging in", email); + } +} + diff --git a/testng/src/test/java/baeldung/com/ParametrizedTests.java b/testng/src/test/java/baeldung/com/ParametrizedTests.java new file mode 100644 index 0000000000..d3813f5382 --- /dev/null +++ b/testng/src/test/java/baeldung/com/ParametrizedTests.java @@ -0,0 +1,77 @@ +package baeldung.com; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Parameters; +import org.testng.annotations.Test; + +public class ParametrizedTests { + + private static final Logger LOGGER = LoggerFactory.getLogger(ParametrizedTests.class); + + @Test + @Parameters({"value", "isEven"}) + public void givenNumberFromXML_ifEvenCheckOK_thenCorrect(int value, boolean isEven) { + Assert.assertEquals(isEven, value % 2 == 0); + } + + @DataProvider(name = "numbers") + public static Object[][] evenNumbers() { + return new Object[][]{{1, false}, {2, true}, {4, true}}; + } + + @Test(dataProvider = "numbers") + public void givenNumberFromDataProvider_ifEvenCheckOK_thenCorrect(Integer number, boolean expected) { + Assert.assertEquals(expected, number % 2 == 0); + } + + @Test(dataProvider = "numbersObject") + public void givenNumberObjectFromDataProvider_ifEvenCheckOK_thenCorrect(EvenNumber number) { + Assert.assertEquals(number.isEven(), number.getValue() % 2 == 0); + } + + @DataProvider(name = "numbersObject") + public Object[][] parameterProvider() { + return new Object[][]{{new EvenNumber(1, false)}, {new EvenNumber(2, true)}, {new EvenNumber(4, true),}}; + } + +} + + +class EvenNumber { + private int value; + private boolean isEven; + + public EvenNumber(int number, boolean isEven) { + this.value = number; + this.isEven = isEven; + } + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + public boolean isEven() { + return isEven; + } + + public void setEven(boolean even) { + isEven = even; + } + + @Override + public String toString() { + return "EvenNumber{" + + "value=" + value + + ", isEven=" + isEven + + '}'; + } +} + + diff --git a/testng/src/test/java/baeldung/com/RegistrationTest.java b/testng/src/test/java/baeldung/com/RegistrationTest.java new file mode 100644 index 0000000000..ec551d9c27 --- /dev/null +++ b/testng/src/test/java/baeldung/com/RegistrationTest.java @@ -0,0 +1,14 @@ +package baeldung.com; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.Test; + +public class RegistrationTest { + private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationTest.class); + + @Test + public void whenCalledFromSuite_thanOK() { + LOGGER.info("Registration successful"); + } +} diff --git a/testng/src/test/java/baeldung/com/SignInTest.java b/testng/src/test/java/baeldung/com/SignInTest.java new file mode 100644 index 0000000000..f0547374d1 --- /dev/null +++ b/testng/src/test/java/baeldung/com/SignInTest.java @@ -0,0 +1,14 @@ +package baeldung.com; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.Test; + +public class SignInTest { + private static final Logger LOGGER = LoggerFactory.getLogger(SignInTest.class); + + @Test + public void whenCalledFromSuite_thanOK() { + LOGGER.info("SignIn successful"); + } +} diff --git a/core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTestTestNg.java b/testng/src/test/java/baeldung/com/SummationServiceTest.java similarity index 77% rename from core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTestTestNg.java rename to testng/src/test/java/baeldung/com/SummationServiceTest.java index fb02f28d06..f377a009df 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTestTestNg.java +++ b/testng/src/test/java/baeldung/com/SummationServiceTest.java @@ -1,19 +1,16 @@ -package com.baeldung.test.comparison; +package baeldung.com; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.TestNG; +import org.testng.annotations.*; import java.util.ArrayList; import java.util.List; -import org.testng.Assert; -import org.testng.TestNG; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterGroups; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeGroups; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -public class SummationServiceTestTestNg extends TestNG { +public class SummationServiceTest extends TestNG { + private static final Logger LOGGER = LoggerFactory.getLogger(DependentTests.class); private List numbers; @@ -29,14 +26,16 @@ public class SummationServiceTestTestNg extends TestNG { numbers = null; } - @BeforeMethod - public void runBeforeEachTest() { - testCount++; + @BeforeSuite(groups = "regression") + public void runBeforeRegressionSuite() { + numbers = new ArrayList<>(); + numbers.add(-11); + numbers.add(2); } - @AfterMethod - public void runAfterEachTest() { - + @AfterSuite(groups = "regression") + public void runAfterRegressionSuite() { + numbers = null; } @BeforeGroups("negative_tests") @@ -62,6 +61,17 @@ public class SummationServiceTestTestNg extends TestNG { numbers.clear(); } + @BeforeMethod + public void runBeforeEachTest() { + testCount++; + } + + @AfterMethod + public void runAfterEachTest() { + + } + + @Test(groups = "positive_tests", enabled = false) public void givenNumbers_sumEquals_thenCorrect() { int sum = numbers.stream().reduce(0, Integer::sum); @@ -78,12 +88,6 @@ public class SummationServiceTestTestNg extends TestNG { public void givenNegativeNumber_sumLessthanZero_thenCorrect() { int sum = numbers.stream().reduce(0, Integer::sum); Assert.assertTrue(sum < 0); - ; - } - - @Test(groups = "sanity") - public void givenNumbers_doSum() { - } @Test(expectedExceptions = ArithmeticException.class) diff --git a/testng/src/test/java/baeldung/com/TestGroup.java b/testng/src/test/java/baeldung/com/TestGroup.java new file mode 100644 index 0000000000..08bb5c996e --- /dev/null +++ b/testng/src/test/java/baeldung/com/TestGroup.java @@ -0,0 +1,44 @@ +package baeldung.com; + +import org.testng.annotations.AfterGroups; +import org.testng.annotations.BeforeGroups; +import org.testng.annotations.Test; + +public class TestGroup { + + @BeforeGroups("database") + public void setupDB() { + System.out.println("setupDB()"); + } + + @AfterGroups("database") + public void cleanDB() { + System.out.println("cleanDB()"); + } + + @Test(groups= "selenium-test") + public void runSelenium() { + System.out.println("runSelenium()"); + } + + @Test(groups= "selenium-test") + public void runSelenium1() { + System.out.println("runSelenium()1"); + } + + @Test(groups = "database") + public void testConnectOracle() { + System.out.println("testConnectOracle()"); + } + + @Test(groups = "database") + public void testConnectMsSQL() { + System.out.println("testConnectMsSQL"); + } + + @Test(dependsOnGroups = {"database","selenium-test"}) + public void runFinal() { + System.out.println("runFinal"); + } + +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/test/comparison/TimeOutTest.java b/testng/src/test/java/baeldung/com/TimeOutTest.java similarity index 70% rename from core-java/src/test/java/com/baeldung/test/comparison/TimeOutTest.java rename to testng/src/test/java/baeldung/com/TimeOutTest.java index 6e06132009..d54a914e08 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/TimeOutTest.java +++ b/testng/src/test/java/baeldung/com/TimeOutTest.java @@ -1,11 +1,11 @@ -package com.baeldung.test.comparison; +package baeldung.com; import org.testng.annotations.Test; public class TimeOutTest { + @Test(timeOut = 1000, enabled = false) public void givenExecution_takeMoreTime_thenFail() { - while (true) - ; + while (true) ; } } diff --git a/testng/src/test/resources/logback.xml b/testng/src/test/resources/logback.xml new file mode 100644 index 0000000000..e9ae1894a6 --- /dev/null +++ b/testng/src/test/resources/logback.xml @@ -0,0 +1,14 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + \ No newline at end of file diff --git a/testng/src/test/resources/parametrized_test.xml b/testng/src/test/resources/parametrized_test.xml new file mode 100644 index 0000000000..932af30e4e --- /dev/null +++ b/testng/src/test/resources/parametrized_test.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/testng/src/test/resources/test_group.xml b/testng/src/test/resources/test_group.xml new file mode 100644 index 0000000000..26868375f2 --- /dev/null +++ b/testng/src/test/resources/test_group.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/testng/src/test/resources/test_setup.xml b/testng/src/test/resources/test_setup.xml new file mode 100644 index 0000000000..7d9708193e --- /dev/null +++ b/testng/src/test/resources/test_setup.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/testng/src/test/resources/test_suite.xml b/testng/src/test/resources/test_suite.xml new file mode 100644 index 0000000000..0fe5d1cc40 --- /dev/null +++ b/testng/src/test/resources/test_suite.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file