diff --git a/apache-velocity/pom.xml b/apache-velocity/pom.xml new file mode 100644 index 0000000000..08f0e96a58 --- /dev/null +++ b/apache-velocity/pom.xml @@ -0,0 +1,101 @@ + + + 4.0.0 + com.baeldung + 0.1-SNAPSHOT + apache-velocity + + war + apache-velocity + + + 1.8 + 1.2 + 4.11 + 1.0.13 + 1.7.5 + 3.6.0 + 2.6 + 2.19.1 + 4.5.2 + 1.7 + 2.0 + + + + + junit + junit + ${junit.version} + test + + + org.apache.velocity + velocity + ${velocity-version} + + + org.apache.velocity + velocity-tools + ${velocity-tools-version} + + + org.slf4j + jcl-over-slf4j + ${jcl-over-slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + org.apache.httpcomponents + httpclient + ${org.apache.httpcomponents.version} + test + + + + apache-velocity + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${jdk.version} + ${jdk.version} + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*LiveTest.java + + + + + + + + diff --git a/apache-velocity/src/main/java/com/baeldung/apache/velocity/model/Product.java b/apache-velocity/src/main/java/com/baeldung/apache/velocity/model/Product.java new file mode 100644 index 0000000000..c215223181 --- /dev/null +++ b/apache-velocity/src/main/java/com/baeldung/apache/velocity/model/Product.java @@ -0,0 +1,33 @@ +package com.baeldung.apache.velocity.model; + +public class Product { + + private String name; + private double price; + + public Product(String name, double price) { + this.name = name; + this.price = price; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } + + @Override + public String toString() { + return "Product{" + "name='" + name + '\'' + ", price=" + price + '}'; + } +} diff --git a/apache-velocity/src/main/java/com/baeldung/apache/velocity/service/ProductService.java b/apache-velocity/src/main/java/com/baeldung/apache/velocity/service/ProductService.java new file mode 100644 index 0000000000..0a623d4d65 --- /dev/null +++ b/apache-velocity/src/main/java/com/baeldung/apache/velocity/service/ProductService.java @@ -0,0 +1,20 @@ +package com.baeldung.apache.velocity.service; + +import com.baeldung.apache.velocity.model.Product; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; +import java.util.List; + +public class ProductService { + + Logger logger = LoggerFactory.getLogger(ProductService.class); + + public List getProducts() { + logger.debug("Product service returning list of products"); + + return Arrays.asList(new Product("Laptop", 31000.00), new Product("Mobile", 16000.00), + new Product("Tablet", 15000.00), new Product("Camera", 23000.00)); + } +} diff --git a/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/LayoutServlet.java b/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/LayoutServlet.java new file mode 100644 index 0000000000..d4208a3880 --- /dev/null +++ b/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/LayoutServlet.java @@ -0,0 +1,41 @@ +package com.baeldung.apache.velocity.servlet; + +import com.baeldung.apache.velocity.model.Product; +import com.baeldung.apache.velocity.service.ProductService; +import org.apache.velocity.Template; +import org.apache.velocity.context.Context; +import org.apache.velocity.tools.view.VelocityLayoutServlet; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +public class LayoutServlet extends VelocityLayoutServlet { + ProductService service = new ProductService(); + + @Override + public Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) { + + Logger logger= LoggerFactory.getLogger(LayoutServlet.class); + + List products = service.getProducts(); + + context.put("products", products); + + Template template = null; + + try { + template = getTemplate("templates/layoutdemo.vm"); + + response.setHeader("Template Returned", "Success"); + } catch (Exception e) { + logger.error("Error while reading the template ",e); + } + + return template; + + } + +} diff --git a/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/ProductServlet.java b/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/ProductServlet.java new file mode 100644 index 0000000000..60c9169fce --- /dev/null +++ b/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/ProductServlet.java @@ -0,0 +1,40 @@ +package com.baeldung.apache.velocity.servlet; + +import com.baeldung.apache.velocity.model.Product; +import com.baeldung.apache.velocity.service.ProductService; +import org.apache.velocity.Template; +import org.apache.velocity.context.Context; +import org.apache.velocity.tools.view.VelocityViewServlet; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +public class ProductServlet extends VelocityViewServlet { + + ProductService service = new ProductService(); + + @Override + public Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) { + + Logger logger= LoggerFactory.getLogger(ProductServlet.class); + + List products = service.getProducts(); + + context.put("products", products); + + Template template = null; + + try { + template = getTemplate("templates/index.vm"); + response.setHeader("Template Returned", "Success"); + } catch (Exception e) { + logger.error("Error while reading the template ", e); + } + + return template; + + } +} diff --git a/apache-velocity/src/main/resources/logback.xml b/apache-velocity/src/main/resources/logback.xml new file mode 100644 index 0000000000..70a420a57a --- /dev/null +++ b/apache-velocity/src/main/resources/logback.xml @@ -0,0 +1,23 @@ + + + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/apache-velocity/src/main/webapp/WEB-INF/velocity.properties b/apache-velocity/src/main/webapp/WEB-INF/velocity.properties new file mode 100644 index 0000000000..00e0b7e410 --- /dev/null +++ b/apache-velocity/src/main/webapp/WEB-INF/velocity.properties @@ -0,0 +1,4 @@ +resource.loader=webapp +webapp.resource.loader.class=org.apache.velocity.tools.view.WebappResourceLoader +webapp.resource.loader.path = . +webapp.resource.loader.cache = true \ No newline at end of file diff --git a/apache-velocity/src/main/webapp/WEB-INF/web.xml b/apache-velocity/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..95b41b36dd --- /dev/null +++ b/apache-velocity/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,49 @@ + + + + apache-velocity + + ProductServlet + com.baeldung.apache.velocity.servlet.ProductServlet + + + + LayoutServlet + com.baeldung.apache.velocity.servlet.LayoutServlet + + + velocityLayout + org.apache.velocity.tools.view.VelocityLayoutServlet + + + org.apache.velocity.properties + /WEB-INF/velocity.properties + + + + ProductServlet + / + + + + LayoutServlet + /layout + + + velocityLayout + *.vm + + + + + 30 + + + + + + index.html + + diff --git a/apache-velocity/src/main/webapp/fragments/footer.vm b/apache-velocity/src/main/webapp/fragments/footer.vm new file mode 100644 index 0000000000..41bb36ce5e --- /dev/null +++ b/apache-velocity/src/main/webapp/fragments/footer.vm @@ -0,0 +1,4 @@ +
+ @Copyright baeldung.com +
\ No newline at end of file diff --git a/apache-velocity/src/main/webapp/fragments/header.vm b/apache-velocity/src/main/webapp/fragments/header.vm new file mode 100644 index 0000000000..96700d3baf --- /dev/null +++ b/apache-velocity/src/main/webapp/fragments/header.vm @@ -0,0 +1,5 @@ +
+
+

Layout Demo Page

+
+
\ No newline at end of file diff --git a/apache-velocity/src/main/webapp/layout/Default.vm b/apache-velocity/src/main/webapp/layout/Default.vm new file mode 100644 index 0000000000..39a8b277a5 --- /dev/null +++ b/apache-velocity/src/main/webapp/layout/Default.vm @@ -0,0 +1,22 @@ + + + Velocity + + +
+ #parse("/fragments/header.vm") +
+ + +
+ + + $screen_content + +
+ +
+ #parse("/fragments/footer.vm") +
+ + \ No newline at end of file diff --git a/apache-velocity/src/main/webapp/templates/index.vm b/apache-velocity/src/main/webapp/templates/index.vm new file mode 100644 index 0000000000..0ca07caf42 --- /dev/null +++ b/apache-velocity/src/main/webapp/templates/index.vm @@ -0,0 +1,63 @@ + + + Online Electronic Store + + + + +
+

Today's Offers

+
+
+

$products.size() Products on Sale!

+
+ We are proud to offer these fine products + at these amazing prices. +
+
+ #set( $count = 1 ) + + + + + #foreach( $product in $products ) + + + + + + #set( $count = $count + 1 ) + #end +
Serial #Product NamePrice
$count)$product.getName()$product.getPrice()
+
+
+ + + diff --git a/apache-velocity/src/main/webapp/templates/layoutdemo.vm b/apache-velocity/src/main/webapp/templates/layoutdemo.vm new file mode 100644 index 0000000000..0626b655c9 --- /dev/null +++ b/apache-velocity/src/main/webapp/templates/layoutdemo.vm @@ -0,0 +1,27 @@ +#set( $layout = "layout.vm" ) +
+

Today's Offers

+
+
+

$products.size() Products on Sale!

+
+ We are proud to offer these fine products + at these amazing prices. +
+
+ #set( $count = 1 ) + + + + + #foreach( $product in $products ) + + + + + + #set( $count = $count + 1 ) + #end +
Serial #Product NamePrice
$count)$product.getName()$product.getPrice()
+
+
\ No newline at end of file diff --git a/apache-velocity/src/test/java/com/baeldung/apache/velocity/servlet/LayoutServletLiveTest.java b/apache-velocity/src/test/java/com/baeldung/apache/velocity/servlet/LayoutServletLiveTest.java new file mode 100644 index 0000000000..f1f166b119 --- /dev/null +++ b/apache-velocity/src/test/java/com/baeldung/apache/velocity/servlet/LayoutServletLiveTest.java @@ -0,0 +1,26 @@ +package com.baeldung.apache.velocity.servlet; + +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.DefaultHttpClient; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + + +public class LayoutServletLiveTest { + + @Test + public void whenRequestUsingHttpClient_thenCorrectResponse() throws Exception { + + HttpClient client = new DefaultHttpClient(); + HttpGet method= new HttpGet("http://localhost:8080/layout"); + + HttpResponse httpResponse = client.execute(method); + + assertEquals("Success", httpResponse.getHeaders("Template Returned")[0].getValue()); + + } + +} diff --git a/apache-velocity/src/test/java/com/baeldung/apache/velocity/servlet/ProductServletLiveTest.java b/apache-velocity/src/test/java/com/baeldung/apache/velocity/servlet/ProductServletLiveTest.java new file mode 100644 index 0000000000..397e575d4d --- /dev/null +++ b/apache-velocity/src/test/java/com/baeldung/apache/velocity/servlet/ProductServletLiveTest.java @@ -0,0 +1,24 @@ +package com.baeldung.apache.velocity.servlet; + +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.DefaultHttpClient; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class ProductServletLiveTest { + + @Test + public void whenRequestUsingHttpClient_thenCorrectResponse() throws Exception { + + HttpClient client = new DefaultHttpClient(); + HttpGet method= new HttpGet("http://localhost:8080/"); + + HttpResponse httpResponse = client.execute(method); + + assertEquals("Success", httpResponse.getHeaders("Template Returned")[0].getValue()); + + } +} diff --git a/core-java/0.5633433244738808 b/core-java/0.5633433244738808 deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/core-java/0.004102810554955205 b/core-java/0.5967303215007616 similarity index 100% rename from core-java/0.004102810554955205 rename to core-java/0.5967303215007616 diff --git a/core-java/0.6256429734439612 b/core-java/0.6256429734439612 deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/core-java/0.04832801936270381 b/core-java/0.9252611327674576 similarity index 100% rename from core-java/0.04832801936270381 rename to core-java/0.9252611327674576 diff --git a/core-java/0.9799201796740292 b/core-java/0.9799201796740292 deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/core-java/README.md b/core-java/README.md index cd16935864..341dbdf910 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -57,3 +57,4 @@ - [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future) - [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) diff --git a/core-java/pom.xml b/core-java/pom.xml index 2b6f065c85..b2c59989f1 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -9,45 +9,7 @@ core-java - - - org.neo4j - neo4j - 3.1.0 - - - - org.neo4j.driver - neo4j-java-driver - 1.1.1 - - - - org.neo4j - neo4j-jdbc-driver - 3.0.1 - - - - org.neo4j - neo4j-ogm-core - 2.1.1 - - - - org.neo4j - neo4j-ogm-embedded-driver - 2.1.1 - - - - com.google.inject - guice - 4.1.0 - no_aop - test - - + net.sourceforge.collections diff --git a/core-java/src/main/java/com/baeldung/java_8_features/Person.java b/core-java/src/main/java/com/baeldung/java_8_features/Person.java new file mode 100644 index 0000000000..83b5530ee8 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java_8_features/Person.java @@ -0,0 +1,27 @@ +package com.baeldung.java_8_features; + +public class Person { + private String name; + private Integer age; + + public Person(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } +} diff --git a/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java b/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java new file mode 100644 index 0000000000..097b516f8c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java @@ -0,0 +1,27 @@ +package com.baeldung.stream; + + +import java.util.stream.Stream; + +public class InfiniteStreams { + public static void main(String[] args) { + doWhileOldWay(); + + doWhileStreamWay(); + + } + + private static void doWhileOldWay() { + + int i = 0; + while (i < 10) { + System.out.println(i); + i++; + } + } + + private static void doWhileStreamWay() { + Stream integers = Stream.iterate(0, i -> i + 1); + integers.limit(10).forEach(System.out::println); + } +} diff --git a/core-java/src/main/java/com/baeldung/streamApi/JoinerSplitter.java b/core-java/src/main/java/com/baeldung/streamApi/JoinerSplitter.java deleted file mode 100644 index 52ffc61799..0000000000 --- a/core-java/src/main/java/com/baeldung/streamApi/JoinerSplitter.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.streamApi; - -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -public class JoinerSplitter { - - public static String join(String[] arrayOfString) { - return Arrays - .asList(arrayOfString) - .stream() - .map(x -> x) - .collect(Collectors.joining(",")); - } - - public static String joinWithPrefixPostFix(String[] arrayOfString) { - return Arrays - .asList(arrayOfString) - .stream() - .map(x -> x) - .collect(Collectors.joining(",", "[", "]")); - } - - public static List split(String str) { - return Stream - .of(str.split(",")) - .map(elem -> new String(elem)) - .collect(Collectors.toList()); - } - - public static List splitToListOfChar(String str) { - return str - .chars() - .mapToObj(item -> (char) item) - .collect(Collectors.toList()); - } - -} diff --git a/core-java/src/main/java/com/baeldung/string/JoinerSplitter.java b/core-java/src/main/java/com/baeldung/string/JoinerSplitter.java new file mode 100644 index 0000000000..085be66801 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/string/JoinerSplitter.java @@ -0,0 +1,36 @@ +package com.baeldung.string; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class JoinerSplitter { + + public static String join ( String[] arrayOfString ) { + return Arrays.asList(arrayOfString) + .stream() + .map(x -> x) + .collect(Collectors.joining(",")); + } + + public static String joinWithPrefixPostFix ( String[] arrayOfString ) { + return Arrays.asList(arrayOfString) + .stream() + .map(x -> x) + .collect(Collectors.joining(",","[","]")); + } + + public static List split ( String str ) { + return Stream.of(str.split(",")) + .map (elem -> new String(elem)) + .collect(Collectors.toList()); + } + + public static List splitToListOfChar ( String str ) { + return str.chars() + .mapToObj(item -> (char) item) + .collect(Collectors.toList()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java8/Java8MaxMinTest.java b/core-java/src/test/java/com/baeldung/java8/Java8MaxMinTest.java new file mode 100644 index 0000000000..b0e514124d --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java8/Java8MaxMinTest.java @@ -0,0 +1,47 @@ +package com.baeldung.java8; + +import com.baeldung.java_8_features.Person; +import org.junit.Test; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.NoSuchElementException; + +import static org.junit.Assert.assertEquals; + +public class Java8MaxMinTest { + + @Test + public void whenListIsOfIntegerThenMaxCanBeDoneUsingIntegerComparator() { + //given + final List listOfIntegers = Arrays.asList(1, 2, 3, 4, 56, 7, 89, 10); + final Integer expectedResult = 89; + + //then + final Integer max = listOfIntegers + .stream() + .mapToInt(v -> v) + .max().orElseThrow(NoSuchElementException::new); + + assertEquals("Should be 89", expectedResult, max); + } + + @Test + public void whenListIsOfPersonObjectThenMinCanBeDoneUsingCustomComparatorThroughLambda() { + //given + final Person alex = new Person("Alex", 23); + final Person john = new Person("John", 40); + final Person peter = new Person("Peter", 32); + final List people = Arrays.asList(alex, john, peter); + + //then + final Person minByAge = people + .stream() + .min(Comparator.comparing(Person::getAge)) + .orElseThrow(NoSuchElementException::new); + + assertEquals("Should be Alex", alex, minByAge); + } + +} diff --git a/core-java/src/test/java/com/baeldung/stream/InfiniteStreamTest.java b/core-java/src/test/java/com/baeldung/stream/InfiniteStreamTest.java new file mode 100644 index 0000000000..a1537a1735 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stream/InfiniteStreamTest.java @@ -0,0 +1,48 @@ +package com.baeldung.stream; + + +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Random; +import java.util.UUID; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; + +public class InfiniteStreamTest { + + @Test + public void givenInfiniteStream_whenUseIntermediateLimitMethod_thenShouldTerminateInFiniteTime() { + //given + Stream infiniteStream = Stream.iterate(0, i -> i + 2); + + //when + List collect = infiniteStream + .limit(10) + .collect(Collectors.toList()); + + //then + assertEquals(collect, Arrays.asList(0, 2, 4, 6, 8, 10, 12, 14, 16, 18)); + } + + @Test + public void givenInfiniteStreamOfRandomInts_whenUseLimit_shouldTerminateInFiniteTime() { + //given + Supplier randomUUIDSupplier = UUID::randomUUID; + Stream infiniteStreamOfRandomUUID = Stream.generate(randomUUIDSupplier); + + //when + List randomInts = infiniteStreamOfRandomUUID + .skip(10) + .limit(10) + .collect(Collectors.toList()); + + //then + assertEquals(randomInts.size(), 10); + } + +} diff --git a/core-java/src/test/java/com/baeldung/stream/JoinerSplitterTest.java b/core-java/src/test/java/com/baeldung/string/JoinerSplitterTest.java similarity index 78% rename from core-java/src/test/java/com/baeldung/stream/JoinerSplitterTest.java rename to core-java/src/test/java/com/baeldung/string/JoinerSplitterTest.java index b995976b2c..9ccff40558 100644 --- a/core-java/src/test/java/com/baeldung/stream/JoinerSplitterTest.java +++ b/core-java/src/test/java/com/baeldung/string/JoinerSplitterTest.java @@ -1,4 +1,4 @@ -package com.baeldung.stream; +package com.baeldung.string; import static org.junit.Assert.*; @@ -7,12 +7,12 @@ import java.util.List; import org.junit.Test; -import com.baeldung.streamApi.JoinerSplitter; +import com.baeldung.string.JoinerSplitter; public class JoinerSplitterTest { @Test - public void provided_array_convert_to_stream_and_convert_to_string() { + public void givenArray_transformedToStream_convertToString() { String[] programming_languages = {"java", "python", "nodejs", "ruby"}; @@ -23,7 +23,7 @@ public class JoinerSplitterTest { } @Test - public void provided_array_convert_to_stream_and_convert_to_prefixPostfixString() { + public void givenArray_transformedToStream_convertToPrefixPostfixString() { String[] programming_languages = {"java", "python", "nodejs", "ruby"}; String expectation = "[java,python,nodejs,ruby]"; @@ -33,7 +33,7 @@ public class JoinerSplitterTest { } @Test - public void provided_string_convert_to_stream_and_convert_to_listOfString() { + public void givenString_transformedToStream_convertToList() { String programming_languages = "java,python,nodejs,ruby"; List expectation = new ArrayList(); @@ -48,7 +48,7 @@ public class JoinerSplitterTest { } @Test - public void provided_string_convert_to_stream_and_convert_to_listOfChar() { + public void givenString_transformedToStream_convertToListOfChar() { String programming_languages = "java,python,nodejs,ruby"; List expectation = new ArrayList(); 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 new file mode 100644 index 0000000000..3ef4949067 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/test/comparison/DependentTests.java @@ -0,0 +1,46 @@ +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/DivisibilityTest.java b/core-java/src/test/java/com/baeldung/test/comparison/DivisibilityTest.java new file mode 100644 index 0000000000..9ae13f5934 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/test/comparison/DivisibilityTest.java @@ -0,0 +1,21 @@ +package com.baeldung.test.comparison; + +import static org.junit.Assert.assertEquals; + +import org.junit.BeforeClass; +import org.junit.Test; + +public class DivisibilityTest { + + private static int number; + + @BeforeClass + public static void setup() { + number = 40; + } + + @Test + public void givenNumber_whenDivisiblebyTwo_thenCorrect() { + assertEquals(number % 2, 0); + } +} 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 new file mode 100644 index 0000000000..3372bbb577 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTest.java @@ -0,0 +1,49 @@ +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 new file mode 100644 index 0000000000..4096c3fb6f --- /dev/null +++ b/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTestNg.java @@ -0,0 +1,81 @@ +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 new file mode 100644 index 0000000000..86836425a9 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/test/comparison/RegistrationTest.java @@ -0,0 +1,11 @@ +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 new file mode 100644 index 0000000000..9669f60b6b --- /dev/null +++ b/core-java/src/test/java/com/baeldung/test/comparison/SignInTest.java @@ -0,0 +1,12 @@ +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/java/com/baeldung/test/comparison/StringCaseTest.java b/core-java/src/test/java/com/baeldung/test/comparison/StringCaseTest.java new file mode 100644 index 0000000000..b4226b82e7 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/test/comparison/StringCaseTest.java @@ -0,0 +1,22 @@ +package com.baeldung.test.comparison; + +import static org.junit.Assert.assertEquals; + +import org.junit.BeforeClass; +import org.junit.Test; + +public class StringCaseTest { + + private static String data; + + @BeforeClass + public static void setup() { + data = "HELLO BAELDUNG"; + } + + @Test + public void givenString_whenAllCaps_thenCorrect() { + assertEquals(data.toUpperCase(), data); + } + +} diff --git a/core-java/src/test/java/com/baeldung/test/comparison/SuiteTest.java b/core-java/src/test/java/com/baeldung/test/comparison/SuiteTest.java new file mode 100644 index 0000000000..a30e5d312a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/test/comparison/SuiteTest.java @@ -0,0 +1,10 @@ +package com.baeldung.test.comparison; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +@RunWith(Suite.class) +@Suite.SuiteClasses({ StringCaseTest.class, DivisibilityTest.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/test/comparison/SummationServiceTest.java new file mode 100644 index 0000000000..b76a87c0fe --- /dev/null +++ b/core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTest.java @@ -0,0 +1,59 @@ +package com.baeldung.test.comparison; + +import java.security.Security; +import java.util.ArrayList; +import java.util.List; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +public class SummationServiceTest { + private static List numbers; + + @BeforeClass + public static void initialize() { + numbers = new ArrayList<>(); + } + + @AfterClass + public static void tearDown() { + numbers = null; + } + + @Before + public void runBeforeEachTest() { + numbers.add(1); + numbers.add(2); + numbers.add(3); + } + + @After + public void runAfterEachTest() { + numbers.clear(); + } + + @Test + public void givenNumbers_sumEquals_thenCorrect() { + int sum = numbers.stream() + .reduce(0, Integer::sum); + Assert.assertEquals(6, sum); + } + + @Ignore + @Test + public void givenEmptyList_sumEqualsZero_thenCorrect() { + int sum = numbers.stream() + .reduce(0, Integer::sum); + Assert.assertEquals(6, sum); + } + + @Test(expected = ArithmeticException.class) + public void givenNumber_whenThrowsException_thenCorrect() { + int i = 1 / 0; + } +} diff --git a/core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTestTestNg.java b/core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTestTestNg.java new file mode 100644 index 0000000000..fb02f28d06 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTestTestNg.java @@ -0,0 +1,94 @@ +package com.baeldung.test.comparison; + +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 { + + private List numbers; + + private int testCount = 0; + + @BeforeClass + public void initialize() { + numbers = new ArrayList<>(); + } + + @AfterClass + public void tearDown() { + numbers = null; + } + + @BeforeMethod + public void runBeforeEachTest() { + testCount++; + } + + @AfterMethod + public void runAfterEachTest() { + + } + + @BeforeGroups("negative_tests") + public void runBeforeEachNegativeGroup() { + numbers.clear(); + } + + @BeforeGroups("regression") + public void runBeforeEachRegressionGroup() { + numbers.add(-11); + numbers.add(2); + } + + @BeforeGroups("positive_tests") + public void runBeforeEachPositiveGroup() { + numbers.add(1); + numbers.add(2); + numbers.add(3); + } + + @AfterGroups("positive_tests,regression,negative_tests") + public void runAfterEachGroup() { + numbers.clear(); + } + + @Test(groups = "positive_tests", enabled = false) + public void givenNumbers_sumEquals_thenCorrect() { + int sum = numbers.stream().reduce(0, Integer::sum); + Assert.assertEquals(sum, 6); + } + + @Test(groups = "negative_tests") + public void givenEmptyList_sumEqualsZero_thenCorrect() { + int sum = numbers.stream().reduce(0, Integer::sum); + Assert.assertEquals(0, sum); + } + + @Test(groups = "regression") + 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) + public void givenNumber_whenThrowsException_thenCorrect() { + int i = 1 / 0; + } + +} diff --git a/core-java/src/test/java/com/baeldung/test/comparison/TimeOutTest.java b/core-java/src/test/java/com/baeldung/test/comparison/TimeOutTest.java new file mode 100644 index 0000000000..6e06132009 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/test/comparison/TimeOutTest.java @@ -0,0 +1,11 @@ +package com.baeldung.test.comparison; + +import org.testng.annotations.Test; + +public class TimeOutTest { + @Test(timeOut = 1000, enabled = false) + public void givenExecution_takeMoreTime_thenFail() { + while (true) + ; + } +} diff --git a/core-java/src/test/resources/parameterised_test.xml b/core-java/src/test/resources/parameterised_test.xml new file mode 100644 index 0000000000..69a2c60460 --- /dev/null +++ b/core-java/src/test/resources/parameterised_test.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ 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 new file mode 100644 index 0000000000..0c9a6c73df --- /dev/null +++ b/core-java/src/test/resources/test_group.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ 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 new file mode 100644 index 0000000000..36305aa5fc --- /dev/null +++ b/core-java/src/test/resources/test_suite.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/guava/src/main/java/org/baeldung/guava/EventBusWrapper.java b/guava/src/main/java/org/baeldung/guava/EventBusWrapper.java deleted file mode 100644 index 243bc9e6ea..0000000000 --- a/guava/src/main/java/org/baeldung/guava/EventBusWrapper.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.guava; - -import com.google.common.eventbus.EventBus; - -class EventBusWrapper { - - private static EventBus eventBus = new EventBus(); - - static void register(Object object) { - eventBus.register(object); - } - - static void unregister(Object object) { - eventBus.unregister(object); - } - - static void post(Object object) { - eventBus.post(object); - } - -} diff --git a/guava/src/main/java/org/baeldung/guava/EventListener.java b/guava/src/main/java/org/baeldung/guava/EventListener.java index 02f22ce6b9..438fcade63 100644 --- a/guava/src/main/java/org/baeldung/guava/EventListener.java +++ b/guava/src/main/java/org/baeldung/guava/EventListener.java @@ -1,5 +1,6 @@ package org.baeldung.guava; +import com.google.common.eventbus.DeadEvent; import com.google.common.eventbus.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -21,6 +22,12 @@ public class EventListener { eventsHandled++; } + @Subscribe + public void handleDeadEvent(DeadEvent deadEvent) { + LOG.info("unhandled event [" + deadEvent.getEvent() + "]"); + eventsHandled++; + } + public int getEventsHandled() { return eventsHandled; } diff --git a/guava/src/test/java/org/baeldung/guava/GuavaCacheLoaderTest.java b/guava/src/test/java/org/baeldung/guava/GuavaCacheLoaderTest.java new file mode 100644 index 0000000000..2aa2e6140b --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaCacheLoaderTest.java @@ -0,0 +1,71 @@ +package org.baeldung.guava; + +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import org.assertj.core.api.Assertions; +import org.junit.Test; + +import java.util.Map; +import java.util.concurrent.ExecutionException; + +import static com.google.common.collect.Iterables.cycle; +import static com.google.common.collect.Maps.newHashMap; +import static org.assertj.core.api.Assertions.assertThat; + +public class GuavaCacheLoaderTest { + int callCount = 0; + + @Test + public void givenAMap_whenAddingValues_thenCanTreatThemAsCache() { + Map cache = newHashMap(); + cache.put("foo", "cachedValueForFoo"); + cache.put("bar", "cachedValueForBar"); + + assertThat(cache.get("foo")).isEqualTo("cachedValueForFoo"); + assertThat(cache.get("bar")).isEqualTo("cachedValueForBar"); + } + + @Test + public void givenCacheLoader_whenGettingItemTwice_shouldOnlyCallOnce() throws ExecutionException { + + final LoadingCache loadingCache = CacheBuilder.newBuilder() + .build(new CacheLoader() { + @Override + public String load(final String s) throws Exception { + return slowMethod(s); + } + }); + + String value = loadingCache.get("key"); + value = loadingCache.get("key"); + + assertThat(callCount).isEqualTo(1); + assertThat(value).isEqualTo("key"); + } + + @Test + public void givenCacheLoader_whenRefreshingItem_shouldCallAgain() throws ExecutionException { + + final LoadingCache loadingCache = CacheBuilder.newBuilder() + .build(new CacheLoader() { + @Override + public String load(final String s) throws Exception { + return slowMethod(s); + } + }); + + String value = loadingCache.get("key"); + loadingCache.refresh("key"); + + assertThat(callCount).isEqualTo(2); + assertThat(value).isEqualTo("key"); + } + + private String slowMethod(final String s) { + callCount++; + return s; + } +} diff --git a/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java b/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java index 1db361d22c..1390eb05aa 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java @@ -1,5 +1,6 @@ package org.baeldung.guava; +import com.google.common.eventbus.EventBus; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -9,25 +10,27 @@ import static org.junit.Assert.*; public class GuavaEventBusTest { private EventListener listener; + private EventBus eventBus; @Before public void setUp() { + eventBus = new EventBus(); listener = new EventListener(); - EventBusWrapper.register(listener); + + eventBus.register(listener); } @After public void tearDown() { - EventBusWrapper.unregister(listener); + eventBus.unregister(listener); } @Test public void givenStringEvent_whenEventHandled_thenSuccess() { listener.resetEventsHandled(); - EventBusWrapper.post("String Event"); + eventBus.post("String Event"); assertEquals(1, listener.getEventsHandled()); - } @Test @@ -35,8 +38,18 @@ public class GuavaEventBusTest { listener.resetEventsHandled(); CustomEvent customEvent = new CustomEvent("Custom Event"); - EventBusWrapper.post(customEvent); + eventBus.post(customEvent); assertEquals(1, listener.getEventsHandled()); } + + @Test + public void givenUnSubscribedEvent_whenEventHandledByDeadEvent_thenSuccess() throws InterruptedException { + listener.resetEventsHandled(); + + eventBus.post(12345); + + assertEquals(1, listener.getEventsHandled()); + } + } diff --git a/httpclient/pom.xml b/httpclient/pom.xml index be0daae995..eec705b224 100644 --- a/httpclient/pom.xml +++ b/httpclient/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 com.baeldung httpclient @@ -113,6 +114,13 @@ ${mockito.version} test + + com.github.tomakehurst + wiremock + ${wiremock.version} + test + + @@ -145,7 +153,7 @@ **/*LiveTest.java - + @@ -202,6 +210,7 @@ 1.3 4.12 1.10.19 + 2.5.1 4.4.5 4.5.2 diff --git a/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java b/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java new file mode 100644 index 0000000000..9b5cb3f293 --- /dev/null +++ b/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java @@ -0,0 +1,154 @@ +package org.baeldung.httpclient.advancedconfig; + + +import com.github.tomakehurst.wiremock.junit.WireMockRule; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpHost; +import org.apache.http.HttpResponse; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.AuthCache; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.auth.BasicScheme; +import org.apache.http.impl.client.BasicAuthCache; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.DefaultProxyRoutePlanner; +import org.junit.Rule; +import org.junit.Test; + +import java.io.IOException; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static org.junit.Assert.assertEquals; + +public class HttpClientAdvancedConfiguration { + + @Rule + public WireMockRule serviceMock = new WireMockRule(8089); + + @Rule + public WireMockRule proxyMock = new WireMockRule(8090); + + @Test + public void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn200() throws IOException { + //given + String userAgent = "BaeldungAgent/1.0"; + serviceMock.stubFor(get(urlEqualTo("/detail")) + .withHeader("User-Agent", equalTo(userAgent)) + .willReturn(aResponse() + .withStatus(200))); + + HttpClient httpClient = HttpClients.createDefault(); + HttpGet httpGet = new HttpGet("http://localhost:8089/detail"); + httpGet.setHeader(HttpHeaders.USER_AGENT, userAgent); + + //when + HttpResponse response = httpClient.execute(httpGet); + + //then + assertEquals(response.getStatusLine().getStatusCode(), 200); + } + + @Test + public void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException { + //given + String xmlBody = "1"; + serviceMock.stubFor(post(urlEqualTo("/person")) + .withHeader("Content-Type", equalTo("application/xml")) + .withRequestBody(equalTo(xmlBody)) + .willReturn(aResponse() + .withStatus(200))); + + HttpClient httpClient = HttpClients.createDefault(); + HttpPost httpPost = new HttpPost("http://localhost:8089/person"); + httpPost.setHeader("Content-Type", "application/xml"); + StringEntity xmlEntity = new StringEntity(xmlBody); + httpPost.setEntity(xmlEntity); + + //when + HttpResponse response = httpClient.execute(httpPost); + + //then + assertEquals(response.getStatusLine().getStatusCode(), 200); + + } + + @Test + public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException { + //given + proxyMock.stubFor(get(urlMatching(".*")) + .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); + + serviceMock.stubFor(get(urlEqualTo("/private")) + .willReturn(aResponse().withStatus(200))); + + + HttpHost proxy = new HttpHost("localhost", 8090); + DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); + HttpClient httpclient = HttpClients.custom() + .setRoutePlanner(routePlanner) + .build(); + + //when + final HttpGet httpGet = new HttpGet("http://localhost:8089/private"); + HttpResponse response = httpclient.execute(httpGet); + + //then + assertEquals(response.getStatusLine().getStatusCode(), 200); + proxyMock.verify(getRequestedFor(urlEqualTo("/private"))); + serviceMock.verify(getRequestedFor(urlEqualTo("/private"))); + } + + @Test + public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException { + //given + proxyMock.stubFor(get(urlMatching("/private")) + .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); + serviceMock.stubFor(get(urlEqualTo("/private")) + .willReturn(aResponse().withStatus(200))); + + + HttpHost proxy = new HttpHost("localhost", 8090); + DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); + + // Client credentials + CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials(new AuthScope(proxy), + new UsernamePasswordCredentials("username_admin", "secret_password")); + + + // Create AuthCache instance + AuthCache authCache = new BasicAuthCache(); + + // Generate BASIC scheme object and add it to the local auth cache + BasicScheme basicAuth = new BasicScheme(); + authCache.put(proxy, basicAuth); + HttpClientContext context = HttpClientContext.create(); + context.setCredentialsProvider(credentialsProvider); + context.setAuthCache(authCache); + + + HttpClient httpclient = HttpClients.custom() + .setRoutePlanner(routePlanner) + .setDefaultCredentialsProvider(credentialsProvider) + .build(); + + + //when + final HttpGet httpGet = new HttpGet("http://localhost:8089/private"); + HttpResponse response = httpclient.execute(httpGet, context); + + //then + assertEquals(response.getStatusLine().getStatusCode(), 200); + proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic"))); + serviceMock.verify(getRequestedFor(urlEqualTo("/private"))); + } + + +} diff --git a/mesos-marathon/Dockerfile b/mesos-marathon/Dockerfile new file mode 100644 index 0000000000..ca79f2dc82 --- /dev/null +++ b/mesos-marathon/Dockerfile @@ -0,0 +1,4 @@ +FROM openjdk:8-jre-alpine +ADD target/mesos-marathon-0.0.1-SNAPSHOT.jar app.jar +EXPOSE 8082 +ENTRYPOINT ["java","-jar","/app.jar"] \ No newline at end of file diff --git a/mesos-marathon/dockerise.sh b/mesos-marathon/dockerise.sh new file mode 100755 index 0000000000..50f5d38306 --- /dev/null +++ b/mesos-marathon/dockerise.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -e +docker login -u mogronalol -p $DOCKER_PASSWORD +docker build -t baeldung/mesos-marathon-demo:$BUILD_NUMBER . +docker push baeldung/mesos-marathon-demo:$BUILD_NUMBER diff --git a/mesos-marathon/marathon.json b/mesos-marathon/marathon.json new file mode 100644 index 0000000000..6471259e92 --- /dev/null +++ b/mesos-marathon/marathon.json @@ -0,0 +1,14 @@ +{ + "id": "mesos-marathon-demo", + "container": { + "type": "DOCKER", + "docker": { + "image": "", + "network": "BRIDGE", + "portMappings": [ + { "containerPort": 8082, "hostPort": 0 } + ] + }, + "volumes": [] + } +} \ No newline at end of file diff --git a/mesos-marathon/pom.xml b/mesos-marathon/pom.xml new file mode 100644 index 0000000000..ca17a5c4c4 --- /dev/null +++ b/mesos-marathon/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + + com.baeldung + mesos-marathon + 0.0.1-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.5.1.RELEASE + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + 1.5.1.RELEASE + + + + repackage + + + + + + + + \ No newline at end of file diff --git a/mesos-marathon/src/main/java/com/mogronalol/DemoApplication.java b/mesos-marathon/src/main/java/com/mogronalol/DemoApplication.java new file mode 100644 index 0000000000..f757178026 --- /dev/null +++ b/mesos-marathon/src/main/java/com/mogronalol/DemoApplication.java @@ -0,0 +1,14 @@ +package com.mogronalol; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import javax.annotation.PostConstruct; + +@SpringBootApplication +public class DemoApplication { + + public static void main(String[] args) { + SpringApplication.run(DemoApplication.class, args); + } +} diff --git a/mesos-marathon/src/main/java/com/mogronalol/HelloController.java b/mesos-marathon/src/main/java/com/mogronalol/HelloController.java new file mode 100644 index 0000000000..2059280ba0 --- /dev/null +++ b/mesos-marathon/src/main/java/com/mogronalol/HelloController.java @@ -0,0 +1,17 @@ +package com.mogronalol; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController(value = "/") +public class HelloController { + + @GetMapping + @ResponseBody + public String getMapping() { + return "Hello world"; + } + +} diff --git a/mesos-marathon/src/main/resources/application.properties b/mesos-marathon/src/main/resources/application.properties new file mode 100644 index 0000000000..8d51d0c619 --- /dev/null +++ b/mesos-marathon/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=8082 \ No newline at end of file diff --git a/mesos-marathon/src/test/java/com/mogronalol/DemoApplicationTests.java b/mesos-marathon/src/test/java/com/mogronalol/DemoApplicationTests.java new file mode 100644 index 0000000000..5e88f9a70f --- /dev/null +++ b/mesos-marathon/src/test/java/com/mogronalol/DemoApplicationTests.java @@ -0,0 +1,34 @@ +package com.mogronalol; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.client.RestTemplate; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = {DemoApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class DemoApplicationTests { + + private RestTemplate restTemplate; + + @LocalServerPort + private int port; + + @Before + public void setUp() { + restTemplate = new RestTemplate(); + } + + @Test + public void contextLoads() { + final String result = restTemplate.getForObject("http://localhost:" + port + "/", String.class); + assertThat(result).isEqualTo("Hello world"); + } + +} diff --git a/pom.xml b/pom.xml index 2392e2c594..ecb07e987b 100644 --- a/pom.xml +++ b/pom.xml @@ -81,6 +81,7 @@ mapstruct metrics + mesos-marathon mockito mocks @@ -191,6 +192,8 @@ xstream struts2 + apache-velocity + diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index b6a24b6cb7..e77ab10aff 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -24,26 +24,6 @@ org.springframework.boot spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - - org.apache.geronimo.specs - geronimo-osgi-locator - 1.1 - test - - - - org.apache.geronimo.components - geronimo-jaspi - 2.0.0 - test @@ -109,18 +89,12 @@ - org.apache.tomee - arquillian-tomee-embedded - ${arquillian-tomee-embedded.version} - test - - - - org.apache.tomee - javaee-api - ${tomee-javaee-api.version} + org.apache.tomcat + tomcat-servlet-api + ${tomee-servlet-api.version} provided + @@ -220,8 +194,7 @@ 3.1.1 3.3.7-1 3.1.7 - 7.0.2 - 7.0-1 + 8.5.11 diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/JavaEEApp.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/JavaEEApp.java deleted file mode 100644 index 773503c5af..0000000000 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/JavaEEApp.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.annotation.servletcomponentscan; - -import javax.enterprise.context.ApplicationScoped; -import javax.enterprise.context.Initialized; -import javax.enterprise.event.Observes; -import javax.servlet.ServletContext; - -@ApplicationScoped -public class JavaEEApp { - - private ServletContext context; - - /** - * act as a servletContext provider - */ - private void setContext(@Observes @Initialized(ApplicationScoped.class) final ServletContext context) { - if (this.context != null) { - throw new IllegalStateException("app context started twice"); - } - - this.context = context; - } - - public ServletContext getContext() { - return context; - } - -} diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java index 9fd66ee12a..b4d416dd96 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java @@ -9,13 +9,13 @@ import org.springframework.boot.web.servlet.ServletComponentScan; *
  • * @ServletComponentScan *
  • - * @ServletComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.javaee") + * @ServletComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.components") *
  • * @ServletComponentScan(basePackageClasses = {AttrListener.class, HelloFilter.class, HelloServlet.class, EchoServlet.class}) *
*/ @SpringBootApplication -@ServletComponentScan("com.baeldung.annotation.servletcomponentscan.javaee") +@ServletComponentScan("com.baeldung.annotation.servletcomponentscan.components") public class SpringBootAnnotatedApp { public static void main(String[] args) { diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java index 9ce1c296e6..8a39078aac 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java @@ -4,7 +4,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication -@ComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.javaee") +@ComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.components") public class SpringBootPlainApp { public static void main(String[] args) { diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/AttrListener.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java similarity index 90% rename from spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/AttrListener.java rename to spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java index 321ddd59d1..bad39c52c4 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/AttrListener.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java @@ -1,4 +1,4 @@ -package com.baeldung.annotation.servletcomponentscan.javaee; +package com.baeldung.annotation.servletcomponentscan.components; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/EchoServlet.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java similarity index 90% rename from spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/EchoServlet.java rename to spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java index b9fed314c7..3419cd0eaf 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/EchoServlet.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java @@ -1,4 +1,4 @@ -package com.baeldung.annotation.servletcomponentscan.javaee; +package com.baeldung.annotation.servletcomponentscan.components; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; @@ -6,7 +6,6 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; -import java.nio.file.CopyOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloFilter.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java similarity index 94% rename from spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloFilter.java rename to spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java index 81e90d69ad..dc2368c5b2 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloFilter.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java @@ -1,4 +1,4 @@ -package com.baeldung.annotation.servletcomponentscan.javaee; +package com.baeldung.annotation.servletcomponentscan.components; import javax.servlet.*; import javax.servlet.annotation.WebFilter; diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloServlet.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java similarity index 90% rename from spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloServlet.java rename to spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java index 4a46a56107..aeae7aecc9 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloServlet.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java @@ -1,7 +1,6 @@ -package com.baeldung.annotation.servletcomponentscan.javaee; +package com.baeldung.annotation.servletcomponentscan.components; import javax.servlet.ServletConfig; -import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/JavaEEAppIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/JavaEEAppIntegrationTest.java deleted file mode 100644 index 95106d2dc8..0000000000 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/JavaEEAppIntegrationTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.annotation.servletcomponentscan; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URL; - -import javax.inject.Inject; -import javax.servlet.FilterRegistration; -import javax.servlet.ServletContext; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.container.test.api.RunAsClient; -import org.jboss.arquillian.junit.Arquillian; -import org.jboss.arquillian.test.api.ArquillianResource; -import org.jboss.shrinkwrap.api.ShrinkWrap; -import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.junit.Test; -import org.junit.runner.RunWith; - -import com.baeldung.annotation.servletcomponentscan.javaee.AttrListener; -import com.baeldung.annotation.servletcomponentscan.javaee.EchoServlet; -import com.baeldung.annotation.servletcomponentscan.javaee.HelloFilter; -import com.baeldung.annotation.servletcomponentscan.javaee.HelloServlet; - -@RunWith(Arquillian.class) -public class JavaEEAppIntegrationTest { - - @Deployment - public static WebArchive createDeployment() { - return ShrinkWrap.create(WebArchive.class).addClass(JavaEEApp.class).addClasses(AttrListener.class, HelloFilter.class, HelloServlet.class, EchoServlet.class); - } - - @Inject - private ServletContext servletContext; - - @Test - public void givenServletContextListener_whenAccessSpecialAttrs_thenFound() throws MalformedURLException { - assertNotNull(servletContext); - assertNotNull(servletContext.getAttribute("servlet-context-attr")); - assertEquals("test", servletContext.getAttribute("servlet-context-attr")); - } - - @Test - public void givenServletContext_whenCheckHelloFilterMappings_thenCorrect() throws MalformedURLException { - assertNotNull(servletContext); - FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter"); - - assertNotNull(filterRegistration); - assertTrue(filterRegistration.getServletNameMappings().contains("echo servlet")); - } - - @ArquillianResource - private URL base; - - @Test - @RunAsClient - public void givenFilterAndServlet_whenGetHello_thenRespondFilteringHello() throws MalformedURLException { - Client client = ClientBuilder.newClient(); - WebTarget target = client.target(URI.create(new URL(base, "hello").toExternalForm())); - Response response = target.request().get(); - - assertEquals("filtering hello", response.readEntity(String.class)); - } - - @Test - @RunAsClient - public void givenFilterAndServlet_whenPostEcho_thenEchoFiltered() throws MalformedURLException { - Client client = ClientBuilder.newClient(); - WebTarget target = client.target(URI.create(new URL(base, "echo").toExternalForm())); - Response response = target.request().post(Entity.entity("echo", MediaType.TEXT_PLAIN_TYPE)); - - assertEquals("filtering echo", response.readEntity(String.class)); - } - -} diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java index 81ac3c9841..8d5eb56bf4 100644 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java @@ -19,7 +19,7 @@ import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class) @AutoConfigureMockMvc -@TestPropertySource(properties = { "security.basic.enabled=false", "server.tomcat.additional-tld-skip-patterns=tomee-*.jar,tomcat-*.jar,openejb-*.jar,cxf-*.jar,activemq-*.jar" }) +@TestPropertySource(properties = { "security.basic.enabled=false" }) public class SpringBootWithServletComponentIntegrationTest { @Autowired private ServletContext servletContext; diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java index b2dea25864..64507ad02c 100644 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java @@ -19,7 +19,7 @@ import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class) @AutoConfigureMockMvc -@TestPropertySource(properties = { "security.basic.enabled=false", "server.tomcat.additional-tld-skip-patterns=tomee-*.jar,tomcat-*.jar,openejb-*.jar,cxf-*.jar,activemq-*.jar" }) +@TestPropertySource(properties = { "security.basic.enabled=false" }) public class SpringBootWithoutServletComponentIntegrationTest { @Autowired private ServletContext servletContext; diff --git a/spring-data-neo4j/pom.xml b/spring-data-neo4j/pom.xml index ce10313b2e..96606d597b 100644 --- a/spring-data-neo4j/pom.xml +++ b/spring-data-neo4j/pom.xml @@ -7,10 +7,41 @@ 1.0 + + org.neo4j + neo4j + 3.1.0 + + + + org.neo4j + neo4j-ogm-core + 2.1.1 + + + + org.neo4j + neo4j-ogm-embedded-driver + 2.1.1 + + + + org.neo4j.driver + neo4j-java-driver + 1.1.1 + + + + org.springframework.data + spring-data-neo4j + 4.2.0.RELEASE + + org.springframework.data spring-data-neo4j ${spring-data-neo4j.version} + test-jar @@ -27,13 +58,6 @@ test - - org.springframework.data - spring-data-neo4j - ${spring-data-neo4j.version} - test-jar - - org.neo4j neo4j-kernel @@ -72,9 +96,9 @@ spring-test ${spring-test.version} - + @@ -130,16 +154,18 @@ + 1.8 + 1.8 1.8 UTF-8 UTF-8 - 3.0.7 + 3.1.0 4.1.6.RELEASE 1.1 1.4.3.RELEASE 4.3.5.RELEASE - 2.0.6 + 2.1.1 4.12 diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java index fb4fda1497..344282d665 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java @@ -4,15 +4,12 @@ import org.neo4j.ogm.session.SessionFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.data.neo4j.config.Neo4jConfiguration; import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; -import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.transaction.annotation.EnableTransactionManagement; @ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" }) @Configuration @EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory") -public class MovieDatabaseNeo4jConfiguration extends Neo4jConfiguration { +public class MovieDatabaseNeo4jConfiguration { public static final String URL = System.getenv("NEO4J_URL") != null ? System.getenv("NEO4J_URL") : "http://neo4j:movies@localhost:7474"; @@ -23,7 +20,7 @@ public class MovieDatabaseNeo4jConfiguration extends Neo4jConfiguration { return config; } - @Override + @Bean public SessionFactory getSessionFactory() { return new SessionFactory(getConfiguration(), "com.baeldung.spring.data.neo4j.domain"); } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java index 81935b2293..7bb1b78a09 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java @@ -5,9 +5,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; -import org.springframework.data.neo4j.config.Neo4jConfiguration; import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; -import org.springframework.data.neo4j.server.Neo4jServer; import org.springframework.transaction.annotation.EnableTransactionManagement; @EnableTransactionManagement @@ -15,7 +13,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory") @Profile({ "embedded", "test" }) -public class MovieDatabaseNeo4jTestConfiguration extends Neo4jConfiguration { +public class MovieDatabaseNeo4jTestConfiguration { @Bean public org.neo4j.ogm.config.Configuration getConfiguration() { @@ -24,7 +22,7 @@ public class MovieDatabaseNeo4jTestConfiguration extends Neo4jConfiguration { return config; } - @Override + @Bean public SessionFactory getSessionFactory() { return new SessionFactory(getConfiguration(), "com.baeldung.spring.data.neo4j.domain"); } diff --git a/core-java/src/main/java/com/baeldung/graph/Car.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java similarity index 89% rename from core-java/src/main/java/com/baeldung/graph/Car.java rename to spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java index 1dc65a0d4b..f2325a334f 100644 --- a/core-java/src/main/java/com/baeldung/graph/Car.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java @@ -1,12 +1,9 @@ -package com.baeldung.graph; +package com.baeldung.spring.data.neo4j.domain; import org.neo4j.ogm.annotation.GraphId; import org.neo4j.ogm.annotation.NodeEntity; import org.neo4j.ogm.annotation.Relationship; -/** - * @author Danil Kornishev (danil.kornishev@mastercard.com) - */ @NodeEntity public class Car { @GraphId diff --git a/core-java/src/main/java/com/baeldung/graph/Company.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Company.java similarity index 87% rename from core-java/src/main/java/com/baeldung/graph/Company.java rename to spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Company.java index 1fe892b331..4422ade44f 100644 --- a/core-java/src/main/java/com/baeldung/graph/Company.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Company.java @@ -1,11 +1,8 @@ -package com.baeldung.graph; +package com.baeldung.spring.data.neo4j.domain; import org.neo4j.ogm.annotation.NodeEntity; import org.neo4j.ogm.annotation.Relationship; -/** - * @author Danil Kornishev (danil.kornishev@mastercard.com) - */ @NodeEntity public class Company { private Long id; diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java index 1bd605a7bc..afb82551e7 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java @@ -12,6 +12,7 @@ import java.util.Map; @Repository public interface MovieRepository extends GraphRepository { + Movie findByTitle(@Param("title") String title); @Query("MATCH (m:Movie) WHERE m.title =~ ('(?i).*'+{title}+'.*') RETURN m") diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java index f7f694c07f..4ac40ef75b 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java @@ -6,5 +6,4 @@ import org.springframework.stereotype.Repository; @Repository public interface PersonRepository extends GraphRepository { - } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java index d760d19066..ae1f6eb8e5 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java @@ -12,11 +12,11 @@ import java.util.*; public class MovieService { @Autowired - MovieRepository movieRepository; + private MovieRepository movieRepository; private Map toD3Format(Iterator> result) { - List> nodes = new ArrayList>(); - List> rels = new ArrayList>(); + List> nodes = new ArrayList<>(); + List> rels = new ArrayList<>(); int i = 0; while (result.hasNext()) { Map row = result.next(); @@ -37,7 +37,7 @@ public class MovieService { } private Map map(String key1, Object value1, String key2, Object value2) { - Map result = new HashMap(2); + Map result = new HashMap<>(2); result.put(key1, value1); result.put(key2, value2); return result; diff --git a/core-java/src/test/java/com/baeldung/graph/Neo4JServerTest.java b/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4JServerTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/graph/Neo4JServerTest.java rename to spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4JServerTest.java index b41588b71e..e959e0237d 100644 --- a/core-java/src/test/java/com/baeldung/graph/Neo4JServerTest.java +++ b/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4JServerTest.java @@ -1,10 +1,11 @@ -package com.baeldung.graph; +package com.baeldung.neo4j; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; +import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.neo4j.driver.v1.AuthTokens; @@ -12,7 +13,6 @@ import org.neo4j.driver.v1.Driver; import org.neo4j.driver.v1.GraphDatabase; import org.neo4j.driver.v1.Session; import org.neo4j.driver.v1.StatementResult; -import org.testng.Assert; @Ignore public class Neo4JServerTest { diff --git a/core-java/src/test/java/com/baeldung/graph/Neo4jTest.java b/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jLiveTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/graph/Neo4jTest.java rename to spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jLiveTest.java index 6956c2c39f..1ff01b93a1 100644 --- a/core-java/src/test/java/com/baeldung/graph/Neo4jTest.java +++ b/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.graph; +package com.baeldung.neo4j; import java.io.File; @@ -7,6 +7,7 @@ import java.util.HashMap; import java.util.Map; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; @@ -16,9 +17,8 @@ import org.neo4j.graphdb.NotFoundException; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.Result; import org.neo4j.graphdb.factory.GraphDatabaseFactory; -import org.testng.Assert; -public class Neo4jTest { +public class Neo4jLiveTest { private static GraphDatabaseService graphDb; diff --git a/core-java/src/test/java/com/baeldung/graph/Neo4jOgmTest.java b/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java similarity index 78% rename from core-java/src/test/java/com/baeldung/graph/Neo4jOgmTest.java rename to spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java index 00bd47d029..06b31667dd 100644 --- a/core-java/src/test/java/com/baeldung/graph/Neo4jOgmTest.java +++ b/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java @@ -1,26 +1,27 @@ -package com.baeldung.graph; +package com.baeldung.neo4j; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; import org.junit.Test; import org.neo4j.ogm.config.Configuration; import org.neo4j.ogm.model.Result; import org.neo4j.ogm.session.Session; import org.neo4j.ogm.session.SessionFactory; -import org.testng.Assert; -import java.util.HashMap; -import java.util.Map; +import com.baeldung.spring.data.neo4j.domain.Car; +import com.baeldung.spring.data.neo4j.domain.Company; +import org.neo4j.ogm.transaction.Transaction; -/** - * @author Danil Kornishev (danil.kornishev@mastercard.com) - */ -public class Neo4jOgmTest { +public class Neo4jOgmLiveTest { @Test public void testOgm() { Configuration conf = new Configuration(); conf.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver"); - SessionFactory factory = new SessionFactory(conf, "com.baeldung.graph"); + SessionFactory factory = new SessionFactory(conf, "com.baeldung.spring.data.neo4j.domain"); Session session = factory.openSession(); Car tesla = new Car("tesla", "modelS"); @@ -30,6 +31,8 @@ public class Neo4jOgmTest { session.save(baeldung); + Assert.assertEquals(1, session.countEntitiesOfType(Company.class)); + Map params = new HashMap<>(); params.put("make", "tesla"); Result result = session.query("MATCH (car:Car) <-[:owns]- (company:Company)" + diff --git a/spring-data-neo4j/src/test/resources/logback.xml b/spring-data-neo4j/src/test/resources/logback.xml new file mode 100644 index 0000000000..39a6538324 --- /dev/null +++ b/spring-data-neo4j/src/test/resources/logback.xml @@ -0,0 +1,16 @@ + + + + + + %d %5p %40.40c:%4L - %m%n + + + + + + + + + + diff --git a/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java b/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java index 89ab848e81..8f14d6c1c6 100644 --- a/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java +++ b/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java @@ -22,9 +22,15 @@ public class ValidatorEventRegister implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { List events = Arrays.asList("beforeCreate", "afterCreate", "beforeSave", "afterSave", "beforeLinkSave", "afterLinkSave", "beforeDelete", "afterDelete"); - + for (Map.Entry entry : validators.entrySet()) { - events.stream().filter(p -> entry.getKey().startsWith(p)).findFirst().ifPresent(p -> validatingRepositoryEventListener.addValidator(p, entry.getValue())); + events + .stream() + .filter(p -> entry + .getKey() + .startsWith(p)) + .findFirst() + .ifPresent(p -> validatingRepositoryEventListener.addValidator(p, entry.getValue())); } } } diff --git a/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java b/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java index ee84738e7a..aa24fccac7 100644 --- a/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java +++ b/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java @@ -1,16 +1,17 @@ package com.baeldung.exception.handlers; -import java.util.stream.Collectors; - import org.springframework.data.rest.core.RepositoryConstraintViolationException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; +import java.util.stream.Collectors; + @ControllerAdvice public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { @@ -18,8 +19,13 @@ public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionH public ResponseEntity handleAccessDeniedException(Exception ex, WebRequest request) { RepositoryConstraintViolationException nevEx = (RepositoryConstraintViolationException) ex; - String errors = nevEx.getErrors().getAllErrors().stream().map(p -> p.toString()).collect(Collectors.joining("\n")); - return new ResponseEntity(errors, new HttpHeaders(), HttpStatus.NOT_ACCEPTABLE); + String errors = nevEx + .getErrors() + .getAllErrors() + .stream() + .map(ObjectError::toString) + .collect(Collectors.joining("\n")); + return new ResponseEntity<>(errors, new HttpHeaders(), HttpStatus.NOT_ACCEPTABLE); } } \ No newline at end of file diff --git a/spring-data-solr/pom.xml b/spring-data-solr/pom.xml index e43b3ff774..2aa9f86a96 100644 --- a/spring-data-solr/pom.xml +++ b/spring-data-solr/pom.xml @@ -51,6 +51,12 @@ ${spring.version} test + diff --git a/spring-data-solr/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java b/spring-data-solr/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java new file mode 100644 index 0000000000..1613ba5480 --- /dev/null +++ b/spring-data-solr/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java @@ -0,0 +1,70 @@ +package com.baeldung.solrjava; + +import static org.junit.Assert.assertEquals; + +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; + + @Before + public void setUp() throws Exception { + + solr = new HttpSolrClient("http://localhost:8983/solr/bigboxstore"); + solr.setParser(new XMLResponseParser()); + } + + @Test + public void givenAdd_thenVerifyAdded() throws SolrServerException, IOException { + + SolrInputDocument document = new SolrInputDocument(); + document.addField("id", "123456"); + document.addField("name", "Kenmore Dishwasher"); + document.addField("price", "599.99"); + + solr.add(document); + solr.commit(); + + SolrQuery query = new SolrQuery(); + query.set("q", "id:123456"); + QueryResponse response = null; + + response = solr.query(query); + + SolrDocumentList docList = response.getResults(); + assertEquals(docList.getNumFound(), 1); + + for (SolrDocument doc : docList) { + assertEquals((String) doc.getFieldValue("id"), "123456"); + assertEquals((Double) doc.getFieldValue("price"), (Double) 599.99); + } + } + + @Test + public void givenDelete_thenVerifyDeleted() throws SolrServerException, IOException { + + solr.deleteById("123456"); + solr.commit(); + + SolrQuery query = new SolrQuery(); + query.set("q", "id:123456"); + QueryResponse response = null; + + response = solr.query(query); + + SolrDocumentList docList = response.getResults(); + assertEquals(docList.getNumFound(), 0); + } +} diff --git a/spring-security-mvc-boot/README.MD b/spring-security-mvc-boot/README.MD index d59aea97b4..3e789dedad 100644 --- a/spring-security-mvc-boot/README.MD +++ b/spring-security-mvc-boot/README.MD @@ -5,3 +5,4 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com - [A Custom Security Expression with Spring Security](http://www.baeldung.com/spring-security-create-new-custom-security-expression) - [Custom AccessDecisionVoters in Spring Security](http://www.baeldung.com/spring-security-custom-voter) - [Spring Security: Authentication with a Database-backed UserDetailsService](http://www.baeldung.com/spring-security-authentication-with-a-database) +- [Two Login Pages with Spring Security](http://www.baeldung.com/spring-security-two-login-pages) diff --git a/spring-security-mvc-login/README.md b/spring-security-mvc-login/README.md index d1f6b884b1..35305112b4 100644 --- a/spring-security-mvc-login/README.md +++ b/spring-security-mvc-login/README.md @@ -10,6 +10,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Spring Security Logout](http://www.baeldung.com/spring-security-logout) - [Spring Security Expressions – hasRole Example](http://www.baeldung.com/spring-security-expressions-basic) - [Spring HTTP/HTTPS Channel Security](http://www.baeldung.com/spring-channel-security-https) +- [Spring Security - Customize the 403 Forbidden/Access Denied Page](http://www.baeldung.com/spring-security-custom-access-denied-page) ### Build the Project ``` diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAccessDeniedHandler.java b/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAccessDeniedHandler.java new file mode 100644 index 0000000000..ea4407c5c4 --- /dev/null +++ b/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAccessDeniedHandler.java @@ -0,0 +1,30 @@ +package org.baeldung.security; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.log4j.Logger; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.access.AccessDeniedHandler; + +public class CustomAccessDeniedHandler implements AccessDeniedHandler { + + public static final Logger LOG = Logger.getLogger(CustomAccessDeniedHandler.class); + + @Override + public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exc) throws IOException, ServletException { + Authentication auth = SecurityContextHolder.getContext() + .getAuthentication(); + if (auth != null) { + LOG.warn("User: " + auth.getName() + " attempted to access the protected URL: " + request.getRequestURI()); + } + + response.sendRedirect(request.getContextPath() + "/accessDenied"); + } + +} diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-mvc-login/src/main/java/org/baeldung/spring/MvcConfig.java index 02392df736..b59dbee0cf 100644 --- a/spring-security-mvc-login/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-security-mvc-login/src/main/java/org/baeldung/spring/MvcConfig.java @@ -28,6 +28,7 @@ public class MvcConfig extends WebMvcConfigurerAdapter { registry.addViewController("/login.html"); registry.addViewController("/homepage.html"); registry.addViewController("/admin/adminpage.html"); + registry.addViewController("/accessDenied"); } @Bean diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java index ae41a037cd..7331d7bb18 100644 --- a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -1,5 +1,6 @@ package org.baeldung.spring; +import org.baeldung.security.CustomAccessDeniedHandler; import org.baeldung.security.CustomLogoutSuccessHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -8,6 +9,7 @@ import org.springframework.security.config.annotation.authentication.builders.Au import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; @Configuration @@ -53,6 +55,9 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { .logoutUrl("/perform_logout") .deleteCookies("JSESSIONID") .logoutSuccessHandler(logoutSuccessHandler()); + //.and() + //.exceptionHandling().accessDeniedPage("/accessDenied"); + //.exceptionHandling().accessDeniedHandler(accessDeniedHandler()); // @formatter:on } @@ -60,5 +65,10 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { public LogoutSuccessHandler logoutSuccessHandler() { return new CustomLogoutSuccessHandler(); } + + @Bean + public AccessDeniedHandler accessDeniedHandler(){ + return new CustomAccessDeniedHandler(); + } } diff --git a/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml index 9c8fdea9ee..f0fa956934 100644 --- a/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml @@ -19,10 +19,16 @@ always-use-default-target="true"/> + + + + + + diff --git a/spring-security-mvc-login/src/main/webapp/WEB-INF/view/accessDenied.jsp b/spring-security-mvc-login/src/main/webapp/WEB-INF/view/accessDenied.jsp new file mode 100644 index 0000000000..45820cf43d --- /dev/null +++ b/spring-security-mvc-login/src/main/webapp/WEB-INF/view/accessDenied.jsp @@ -0,0 +1,15 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> + + + + +Access Denied + + +

Sorry, you do not have permission to view this page.

+ +Click ">here to go back to the Homepage. + + \ No newline at end of file diff --git a/spring-security-mvc-login/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-security-mvc-login/src/main/webapp/WEB-INF/view/homepage.jsp index 80f27f5466..c9d88cbc9b 100644 --- a/spring-security-mvc-login/src/main/webapp/WEB-INF/view/homepage.jsp +++ b/spring-security-mvc-login/src/main/webapp/WEB-INF/view/homepage.jsp @@ -4,21 +4,23 @@ -

This is the body of the sample view

+

This is the body of the sample view

- - This text is only visible to a user -
-
+ + This text is only visible to a user +

+ ">Restricted Admin Page +

+
- - This text is only visible to an admin -
+ + This text is only visible to an admin +
">Admin Page
-
+
+ + ">Logout - ">Logout - \ No newline at end of file diff --git a/spring-security-mvc-login/src/main/webapp/WEB-INF/web.xml b/spring-security-mvc-login/src/main/webapp/WEB-INF/web.xml index 0a0a340995..eef48ec9b3 100644 --- a/spring-security-mvc-login/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-mvc-login/src/main/webapp/WEB-INF/web.xml @@ -43,8 +43,15 @@ /* + + 403 + /accessDenied + + + + \ No newline at end of file diff --git a/struts2/WebContent/WEB-INF/web.xml b/struts2/WebContent/WEB-INF/web.xml index 3aa1d1d173..8f1b55943c 100644 --- a/struts2/WebContent/WEB-INF/web.xml +++ b/struts2/WebContent/WEB-INF/web.xml @@ -1,16 +1,12 @@ - - - MyStrutsApp - - struts2 - org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter - - - - struts2 - /* - + + + struts + + struts2 + org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter + + + struts2 + /* + \ No newline at end of file diff --git a/struts2/pom.xml b/struts2/pom.xml index 9b9adeaf46..983f18903b 100644 --- a/struts2/pom.xml +++ b/struts2/pom.xml @@ -1,48 +1,66 @@ - 4.0.0 - com.baeldung - struts2 - 0.0.1-SNAPSHOT - war - struts2 - - - src - - - src - - **/*.java - - - - - - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - maven-war-plugin - 3.0.0 - - WebContent - - - - - - - - - org.apache.struts - struts2-core - 2.5.5 - - - + 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 + MyStrutsApp + 0.0.1-SNAPSHOT + war + struts + + src/main/java + + + src/main/resources + + + + + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + maven-war-plugin + 3.0.0 + + WebContent + + + + + + + junit + junit + 4.12 + + + org.apache.struts + struts2-core + 2.5.5 + + + org.apache.struts + struts2-junit-plugin + 2.5.5 + + + org.apache.struts + struts2-convention-plugin + 2.5.8 + + + javax.servlet + javax.servlet-api + 3.0.1 + + + org.springframework + spring-core + 4.3.6.RELEASE + + \ No newline at end of file diff --git a/struts2/src/com/baeldung/struts/CarAction.java b/struts2/src/main/java/com/baeldung/struts/CarAction.java similarity index 67% rename from struts2/src/com/baeldung/struts/CarAction.java rename to struts2/src/main/java/com/baeldung/struts/CarAction.java index a96aa440b6..478f3b4cc2 100644 --- a/struts2/src/com/baeldung/struts/CarAction.java +++ b/struts2/src/main/java/com/baeldung/struts/CarAction.java @@ -1,7 +1,13 @@ package com.baeldung.struts; -public class CarAction { +import org.apache.struts2.convention.annotation.Action; +import org.apache.struts2.convention.annotation.Namespace; +import org.apache.struts2.convention.annotation.Result; +@Namespace("/tutorial") +@Action("/car") +@Result(name = "success", location = "/result.jsp") +public class CarAction { private String carName; private String carMessage; private CarMessageService carMessageService = new CarMessageService(); diff --git a/struts2/src/com/baeldung/struts/CarMessageService.java b/struts2/src/main/java/com/baeldung/struts/CarMessageService.java similarity index 64% rename from struts2/src/com/baeldung/struts/CarMessageService.java rename to struts2/src/main/java/com/baeldung/struts/CarMessageService.java index fef9c1719d..34d3ca3d76 100644 --- a/struts2/src/com/baeldung/struts/CarMessageService.java +++ b/struts2/src/main/java/com/baeldung/struts/CarMessageService.java @@ -4,12 +4,15 @@ public class CarMessageService { public String getMessage(String carName) { System.out.println("inside getMessage()" + carName); - if (carName.equalsIgnoreCase("ferrari")) + if (carName.equalsIgnoreCase("ferrari")){ return "Ferrari Fan!"; - else if (carName.equalsIgnoreCase("bmw")) + } + else if (carName.equalsIgnoreCase("bmw")){ return "BMW Fan!"; - else + } + else{ return "please choose ferrari Or bmw"; + } } } diff --git a/struts2/src/struts.xml b/struts2/src/struts.xml deleted file mode 100644 index 1c117ac900..0000000000 --- a/struts2/src/struts.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - /result.jsp - - - \ No newline at end of file diff --git a/struts2/src/test/java/com/baeldung/struts/test/CarActionTest.java b/struts2/src/test/java/com/baeldung/struts/test/CarActionTest.java new file mode 100644 index 0000000000..64b640edfb --- /dev/null +++ b/struts2/src/test/java/com/baeldung/struts/test/CarActionTest.java @@ -0,0 +1,29 @@ +//package com.baeldung.struts.test; +// +//import org.apache.struts2.StrutsTestCase; +//import org.junit.Test; +// +//import com.baeldung.struts.CarAction; +//import com.opensymphony.xwork2.ActionProxy; +// +//public class CarActionTest extends StrutsTestCase { +// +// public void testgivenCarOptions_WhenferrariSelected_ThenShowMessage() throws Exception { +// request.setParameter("carName", "ferrari"); +// ActionProxy proxy = getActionProxy("/tutorial/car.action"); +// CarAction carAction = (CarAction) proxy.getAction(); +// String result = proxy.execute(); +// assertEquals(result, "success"); +// assertEquals(carAction.getCarMessage(), "Ferrari Fan!"); +// } +// +// public void testgivenCarOptions_WhenbmwSelected_ThenShowMessage() throws Exception { +// request.setParameter("carName", "bmw"); +// ActionProxy proxy = getActionProxy("/tutorial/car.action"); +// CarAction carAction = (CarAction) proxy.getAction(); +// String result = proxy.execute(); +// assertEquals(result, "success"); +// assertEquals(carAction.getCarMessage(), "BMW Fan!"); +// } +// +//}