Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
2fabf7c26f
|
@ -0,0 +1,101 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<artifactId>apache-velocity</artifactId>
|
||||
|
||||
<packaging>war</packaging>
|
||||
<name>apache-velocity</name>
|
||||
|
||||
<properties>
|
||||
<jdk.version>1.8</jdk.version>
|
||||
<jstl.version>1.2</jstl.version>
|
||||
<junit.version>4.11</junit.version>
|
||||
<logback.version>1.0.13</logback.version>
|
||||
<jcl-over-slf4j.version>1.7.5</jcl-over-slf4j.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<org.apache.httpcomponents.version>4.5.2</org.apache.httpcomponents.version>
|
||||
<velocity-version>1.7</velocity-version>
|
||||
<velocity-tools-version>2.0</velocity-tools-version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.velocity</groupId>
|
||||
<artifactId>velocity</artifactId>
|
||||
<version>${velocity-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.velocity</groupId>
|
||||
<artifactId>velocity-tools</artifactId>
|
||||
<version>${velocity-tools-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${jcl-over-slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>${org.apache.httpcomponents.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<finalName>apache-velocity</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${jdk.version}</source>
|
||||
<target>${jdk.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>${maven-war-plugin.version}</version>
|
||||
<configuration>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
<systemPropertyVariables>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -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 + '}';
|
||||
}
|
||||
}
|
|
@ -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<Product> 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));
|
||||
}
|
||||
}
|
|
@ -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<Product> 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;
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -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<Product> 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;
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<layout class="ch.qos.logback.classic.PatternLayout">
|
||||
|
||||
<Pattern>
|
||||
%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
|
||||
</Pattern>
|
||||
|
||||
</layout>
|
||||
</appender>
|
||||
|
||||
<logger name="com.baeldung.apache.velocity.service" level="debug"
|
||||
additivity="false">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</logger>
|
||||
|
||||
<root level="error">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
</configuration>
|
|
@ -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
|
|
@ -0,0 +1,49 @@
|
|||
<!DOCTYPE web-app PUBLIC
|
||||
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
|
||||
"http://java.sun.com/dtd/web-app_2_3.dtd" >
|
||||
|
||||
<web-app>
|
||||
<display-name>apache-velocity</display-name>
|
||||
<servlet>
|
||||
<servlet-name>ProductServlet</servlet-name>
|
||||
<servlet-class>com.baeldung.apache.velocity.servlet.ProductServlet</servlet-class>
|
||||
</servlet>
|
||||
|
||||
<servlet>
|
||||
<servlet-name>LayoutServlet</servlet-name>
|
||||
<servlet-class>com.baeldung.apache.velocity.servlet.LayoutServlet</servlet-class>
|
||||
</servlet>
|
||||
<servlet>
|
||||
<servlet-name>velocityLayout</servlet-name>
|
||||
<servlet-class>org.apache.velocity.tools.view.VelocityLayoutServlet</servlet-class>
|
||||
|
||||
<init-param>
|
||||
<param-name>org.apache.velocity.properties</param-name>
|
||||
<param-value>/WEB-INF/velocity.properties</param-value>
|
||||
</init-param>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>ProductServlet</servlet-name>
|
||||
<url-pattern>/</url-pattern>
|
||||
</servlet-mapping>
|
||||
|
||||
<servlet-mapping>
|
||||
<servlet-name>LayoutServlet</servlet-name>
|
||||
<url-pattern>/layout</url-pattern>
|
||||
</servlet-mapping>
|
||||
<servlet-mapping>
|
||||
<servlet-name>velocityLayout</servlet-name>
|
||||
<url-pattern>*.vm</url-pattern>
|
||||
</servlet-mapping>
|
||||
<!-- session timeout -->
|
||||
<session-config>
|
||||
<session-timeout>
|
||||
30
|
||||
</session-timeout>
|
||||
</session-config>
|
||||
|
||||
<!-- welcome file -->
|
||||
<welcome-file-list>
|
||||
<welcome-file>index.html</welcome-file>
|
||||
</welcome-file-list>
|
||||
</web-app>
|
|
@ -0,0 +1,4 @@
|
|||
<div
|
||||
style="background: #63B175; text-align: center; padding: 5px; margin-top: 10px;">
|
||||
@Copyright baeldung.com
|
||||
</div>
|
|
@ -0,0 +1,5 @@
|
|||
<div style="background: #63B175; height: 80px; padding: 5px;">
|
||||
<div style="float: left">
|
||||
<h1> Layout Demo Page</h1>
|
||||
</div>
|
||||
</div>
|
|
@ -0,0 +1,22 @@
|
|||
<html>
|
||||
<head>
|
||||
<title>Velocity</title>
|
||||
</head>
|
||||
<body>
|
||||
<div>
|
||||
#parse("/fragments/header.vm")
|
||||
</div>
|
||||
|
||||
|
||||
<div>
|
||||
|
||||
<!-- View index.vm is inserted here -->
|
||||
$screen_content
|
||||
|
||||
</div>
|
||||
|
||||
<div>
|
||||
#parse("/fragments/footer.vm")
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,63 @@
|
|||
<HTML>
|
||||
<HEAD>
|
||||
<TITLE>Online Electronic Store</TITLE>
|
||||
<style>
|
||||
body {background-color: powderblue;}
|
||||
h1 {color: blue;}
|
||||
p {color: red;}
|
||||
table.gridtable {
|
||||
font-family: verdana,arial,sans-serif;
|
||||
font-size:11px;
|
||||
color:#333333;
|
||||
border-width: 1px;
|
||||
border-color: #666666;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
table.gridtable th {
|
||||
border-width: 1px;
|
||||
padding: 8px;
|
||||
border-style: solid;
|
||||
border-color: #666666;
|
||||
background-color: #dedede;
|
||||
}
|
||||
table.gridtable td {
|
||||
border-width: 1px;
|
||||
padding: 8px;
|
||||
border-style: solid;
|
||||
border-color: #666666;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
|
||||
</style>
|
||||
|
||||
</HEAD>
|
||||
<BODY>
|
||||
<CENTER>
|
||||
<h1>Today's Offers</h1>
|
||||
<BR/>
|
||||
<BR/>
|
||||
<h2>$products.size() Products on Sale!</h2>
|
||||
<BR/>
|
||||
We are proud to offer these fine products
|
||||
at these amazing prices.
|
||||
<BR/>
|
||||
<BR/>
|
||||
#set( $count = 1 )
|
||||
<TABLE class="gridtable">
|
||||
<TR>
|
||||
<TH>Serial #</TH><TH>Product Name</TH><TH>Price</TH>
|
||||
</TR>
|
||||
#foreach( $product in $products )
|
||||
<TR>
|
||||
<TD>$count)</TD>
|
||||
<TD>$product.getName()</TD>
|
||||
<TD>$product.getPrice()</TD>
|
||||
</TR>
|
||||
#set( $count = $count + 1 )
|
||||
#end
|
||||
</TABLE>
|
||||
<BR/>
|
||||
</CENTER>
|
||||
|
||||
</BODY>
|
||||
</HTML>
|
|
@ -0,0 +1,27 @@
|
|||
#set( $layout = "layout.vm" )
|
||||
<CENTER>
|
||||
<h1>Today's Offers</h1>
|
||||
<BR/>
|
||||
<BR/>
|
||||
<h2>$products.size() Products on Sale!</h2>
|
||||
<BR/>
|
||||
We are proud to offer these fine products
|
||||
at these amazing prices.
|
||||
<BR/>
|
||||
<BR/>
|
||||
#set( $count = 1 )
|
||||
<TABLE class="gridtable">
|
||||
<TR>
|
||||
<TH>Serial #</TH><TH>Product Name</TH><TH>Price</TH>
|
||||
</TR>
|
||||
#foreach( $product in $products )
|
||||
<TR>
|
||||
<TD>$count)</TD>
|
||||
<TD>$product.getName()</TD>
|
||||
<TD>$product.getPrice()</TD>
|
||||
</TR>
|
||||
#set( $count = $count + 1 )
|
||||
#end
|
||||
</TABLE>
|
||||
<BR/>
|
||||
</CENTER>
|
|
@ -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());
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -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());
|
||||
|
||||
}
|
||||
}
|
|
@ -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)
|
||||
|
|
|
@ -9,45 +9,7 @@
|
|||
<name>core-java</name>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.neo4j</groupId>
|
||||
<artifactId>neo4j</artifactId>
|
||||
<version>3.1.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.neo4j.driver</groupId>
|
||||
<artifactId>neo4j-java-driver</artifactId>
|
||||
<version>1.1.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.neo4j</groupId>
|
||||
<artifactId>neo4j-jdbc-driver</artifactId>
|
||||
<version>3.0.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.neo4j</groupId>
|
||||
<artifactId>neo4j-ogm-core</artifactId>
|
||||
<version>2.1.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.neo4j</groupId>
|
||||
<artifactId>neo4j-ogm-embedded-driver</artifactId>
|
||||
<version>2.1.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.inject</groupId>
|
||||
<artifactId>guice</artifactId>
|
||||
<version>4.1.0</version>
|
||||
<classifier>no_aop</classifier>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.collections</groupId>
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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<Integer> integers = Stream.iterate(0, i -> i + 1);
|
||||
integers.limit(10).forEach(System.out::println);
|
||||
}
|
||||
}
|
|
@ -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<String> split(String str) {
|
||||
return Stream
|
||||
.of(str.split(","))
|
||||
.map(elem -> new String(elem))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static List<Character> splitToListOfChar(String str) {
|
||||
return str
|
||||
.chars()
|
||||
.mapToObj(item -> (char) item)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
|
@ -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<String> split ( String str ) {
|
||||
return Stream.of(str.split(","))
|
||||
.map (elem -> new String(elem))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static List<Character> splitToListOfChar ( String str ) {
|
||||
return str.chars()
|
||||
.mapToObj(item -> (char) item)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
|
@ -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<Integer> 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<Person> 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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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<Integer> infiniteStream = Stream.iterate(0, i -> i + 2);
|
||||
|
||||
//when
|
||||
List<Integer> 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<UUID> randomUUIDSupplier = UUID::randomUUID;
|
||||
Stream<UUID> infiniteStreamOfRandomUUID = Stream.generate(randomUUIDSupplier);
|
||||
|
||||
//when
|
||||
List<UUID> randomInts = infiniteStreamOfRandomUUID
|
||||
.skip(10)
|
||||
.limit(10)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
//then
|
||||
assertEquals(randomInts.size(), 10);
|
||||
}
|
||||
|
||||
}
|
|
@ -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<String> expectation = new ArrayList<String>();
|
||||
|
@ -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<Character> expectation = new ArrayList<Character>();
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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<Object[]> 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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.test.comparison;
|
||||
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
public class RegistrationTest {
|
||||
|
||||
@Test
|
||||
public void givenEmail_ifValid_thenCorrect() {
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.test.comparison;
|
||||
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
public class SignInTest {
|
||||
|
||||
@Test
|
||||
public void givenUsername_ifValid_thenCorrect() {
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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 {
|
||||
|
||||
}
|
|
@ -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<Integer> 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;
|
||||
}
|
||||
}
|
|
@ -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<Integer> 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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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)
|
||||
;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
|
||||
<suite name="My test suite">
|
||||
<test name="testing">
|
||||
<parameter name="num" value="2"/>
|
||||
<parameter name="expectedResult" value="true"/>
|
||||
<classes>
|
||||
<class name="com.baeldung.test.comparison.MyParameterisedUnitTestNg"/>
|
||||
</classes>
|
||||
</test>
|
||||
</suite>
|
|
@ -0,0 +1,13 @@
|
|||
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
|
||||
<suite name="regression_test">
|
||||
<test name="testing">
|
||||
<groups>
|
||||
<run>
|
||||
<include name="sanity" />
|
||||
</run>
|
||||
</groups>
|
||||
<classes>
|
||||
<class name="com.baeldung.test.comparison.SummationServiceTestTestNg" />
|
||||
</classes>
|
||||
</test>
|
||||
</suite>
|
|
@ -0,0 +1,9 @@
|
|||
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
|
||||
<suite name="Evaluation_Suite">
|
||||
<test name="Sanity">
|
||||
<classes>
|
||||
<class name="com.baeldung.test.comparison.RegistrationTest" />
|
||||
<class name="com.baeldung.test.comparison.SignInTest" />
|
||||
</classes>
|
||||
</test>
|
||||
</suite>
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -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<String, String> 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<String, String> loadingCache = CacheBuilder.newBuilder()
|
||||
.build(new CacheLoader<String, String>() {
|
||||
@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<String, String> loadingCache = CacheBuilder.newBuilder()
|
||||
.build(new CacheLoader<String, String>() {
|
||||
@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;
|
||||
}
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
|
@ -113,6 +114,13 @@
|
|||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.tomakehurst</groupId>
|
||||
<artifactId>wiremock</artifactId>
|
||||
<version>${wiremock.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
@ -145,7 +153,7 @@
|
|||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
|
@ -202,6 +210,7 @@
|
|||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
<wiremock.version>2.5.1</wiremock.version>
|
||||
|
||||
<httpcore.version>4.4.5</httpcore.version>
|
||||
<httpclient.version>4.5.2</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 -->
|
||||
|
|
|
@ -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 = "<xml><id>1</id></xml>";
|
||||
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")));
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -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"]
|
|
@ -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
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"id": "mesos-marathon-demo",
|
||||
"container": {
|
||||
"type": "DOCKER",
|
||||
"docker": {
|
||||
"image": "",
|
||||
"network": "BRIDGE",
|
||||
"portMappings": [
|
||||
{ "containerPort": 8082, "hostPort": 0 }
|
||||
]
|
||||
},
|
||||
"volumes": []
|
||||
}
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>mesos-marathon</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.5.1.RELEASE</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>1.5.1.RELEASE</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
server.port=8082
|
|
@ -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");
|
||||
}
|
||||
|
||||
}
|
3
pom.xml
3
pom.xml
|
@ -81,6 +81,7 @@
|
|||
|
||||
<module>mapstruct</module>
|
||||
<module>metrics</module>
|
||||
<module>mesos-marathon</module>
|
||||
<module>mockito</module>
|
||||
<module>mocks</module>
|
||||
|
||||
|
@ -191,6 +192,8 @@
|
|||
<module>xstream</module>
|
||||
|
||||
<module>struts2</module>
|
||||
<module>apache-velocity</module>
|
||||
|
||||
|
||||
</modules>
|
||||
|
||||
|
|
|
@ -24,26 +24,6 @@
|
|||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-tomcat</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.geronimo.specs</groupId>
|
||||
<artifactId>geronimo-osgi-locator</artifactId>
|
||||
<version>1.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.geronimo.components</groupId>
|
||||
<artifactId>geronimo-jaspi</artifactId>
|
||||
<version>2.0.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
|
@ -109,18 +89,12 @@
|
|||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.tomee</groupId>
|
||||
<artifactId>arquillian-tomee-embedded</artifactId>
|
||||
<version>${arquillian-tomee-embedded.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.tomee</groupId>
|
||||
<artifactId>javaee-api</artifactId>
|
||||
<version>${tomee-javaee-api.version}</version>
|
||||
<groupId>org.apache.tomcat</groupId>
|
||||
<artifactId>tomcat-servlet-api</artifactId>
|
||||
<version>${tomee-servlet-api.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -220,8 +194,7 @@
|
|||
<jquery.version>3.1.1</jquery.version>
|
||||
<bootstrap.version>3.3.7-1</bootstrap.version>
|
||||
<subethasmtp.version>3.1.7</subethasmtp.version>
|
||||
<arquillian-tomee-embedded.version>7.0.2</arquillian-tomee-embedded.version>
|
||||
<tomee-javaee-api.version>7.0-1</tomee-javaee-api.version>
|
||||
<tomee-servlet-api.version>8.5.11</tomee-servlet-api.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -9,13 +9,13 @@ import org.springframework.boot.web.servlet.ServletComponentScan;
|
|||
* <ul><li>
|
||||
* <code>@ServletComponentScan</code>
|
||||
* </li><li>
|
||||
* <code>@ServletComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.javaee")</code>
|
||||
* <code>@ServletComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.components")</code>
|
||||
* </li><li>
|
||||
* <code>@ServletComponentScan(basePackageClasses = {AttrListener.class, HelloFilter.class, HelloServlet.class, EchoServlet.class})</code>
|
||||
* </li></ul>
|
||||
*/
|
||||
@SpringBootApplication
|
||||
@ServletComponentScan("com.baeldung.annotation.servletcomponentscan.javaee")
|
||||
@ServletComponentScan("com.baeldung.annotation.servletcomponentscan.components")
|
||||
public class SpringBootAnnotatedApp {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.annotation.servletcomponentscan.javaee;
|
||||
package com.baeldung.annotation.servletcomponentscan.components;
|
||||
|
||||
import javax.servlet.ServletContextEvent;
|
||||
import javax.servlet.ServletContextListener;
|
|
@ -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;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.annotation.servletcomponentscan.javaee;
|
||||
package com.baeldung.annotation.servletcomponentscan.components;
|
||||
|
||||
import javax.servlet.*;
|
||||
import javax.servlet.annotation.WebFilter;
|
|
@ -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;
|
|
@ -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));
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -7,10 +7,41 @@
|
|||
<version>1.0</version>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.neo4j</groupId>
|
||||
<artifactId>neo4j</artifactId>
|
||||
<version>3.1.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.neo4j</groupId>
|
||||
<artifactId>neo4j-ogm-core</artifactId>
|
||||
<version>2.1.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.neo4j</groupId>
|
||||
<artifactId>neo4j-ogm-embedded-driver</artifactId>
|
||||
<version>2.1.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.neo4j.driver</groupId>
|
||||
<artifactId>neo4j-java-driver</artifactId>
|
||||
<version>1.1.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-neo4j</artifactId>
|
||||
<version>4.2.0.RELEASE</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-neo4j</artifactId>
|
||||
<version>${spring-data-neo4j.version}</version>
|
||||
<type>test-jar</type>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
|
@ -27,13 +58,6 @@
|
|||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-neo4j</artifactId>
|
||||
<version>${spring-data-neo4j.version}</version>
|
||||
<type>test-jar</type>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.neo4j</groupId>
|
||||
<artifactId>neo4j-kernel</artifactId>
|
||||
|
@ -72,9 +96,9 @@
|
|||
<artifactId>spring-test</artifactId>
|
||||
<version>${spring-test.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -130,16 +154,18 @@
|
|||
</profiles>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<java.version>1.8</java.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
|
||||
<neo4j.version>3.0.7</neo4j.version>
|
||||
<neo4j.version>3.1.0</neo4j.version>
|
||||
<spring-data-neo4j.version>4.1.6.RELEASE</spring-data-neo4j.version>
|
||||
<jackson-jsog.version>1.1</jackson-jsog.version>
|
||||
<spring-boot.version>1.4.3.RELEASE</spring-boot.version>
|
||||
<spring-test.version>4.3.5.RELEASE</spring-test.version>
|
||||
<neo4j-ogm-test.version>2.0.6</neo4j-ogm-test.version>
|
||||
<neo4j-ogm-test.version>2.1.1</neo4j-ogm-test.version>
|
||||
|
||||
<junit.version>4.12</junit.version>
|
||||
|
||||
|
|
|
@ -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");
|
||||
}
|
||||
|
|
|
@ -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");
|
||||
}
|
||||
|
|
|
@ -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
|
|
@ -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;
|
|
@ -12,6 +12,7 @@ import java.util.Map;
|
|||
|
||||
@Repository
|
||||
public interface MovieRepository extends GraphRepository<Movie> {
|
||||
|
||||
Movie findByTitle(@Param("title") String title);
|
||||
|
||||
@Query("MATCH (m:Movie) WHERE m.title =~ ('(?i).*'+{title}+'.*') RETURN m")
|
||||
|
|
|
@ -6,5 +6,4 @@ import org.springframework.stereotype.Repository;
|
|||
|
||||
@Repository
|
||||
public interface PersonRepository extends GraphRepository<Person> {
|
||||
|
||||
}
|
||||
|
|
|
@ -12,11 +12,11 @@ import java.util.*;
|
|||
public class MovieService {
|
||||
|
||||
@Autowired
|
||||
MovieRepository movieRepository;
|
||||
private MovieRepository movieRepository;
|
||||
|
||||
private Map<String, Object> toD3Format(Iterator<Map<String, Object>> result) {
|
||||
List<Map<String, Object>> nodes = new ArrayList<Map<String, Object>>();
|
||||
List<Map<String, Object>> rels = new ArrayList<Map<String, Object>>();
|
||||
List<Map<String, Object>> nodes = new ArrayList<>();
|
||||
List<Map<String, Object>> rels = new ArrayList<>();
|
||||
int i = 0;
|
||||
while (result.hasNext()) {
|
||||
Map<String, Object> row = result.next();
|
||||
|
@ -37,7 +37,7 @@ public class MovieService {
|
|||
}
|
||||
|
||||
private Map<String, Object> map(String key1, Object value1, String key2, Object value2) {
|
||||
Map<String, Object> result = new HashMap<String, Object>(2);
|
||||
Map<String, Object> result = new HashMap<>(2);
|
||||
result.put(key1, value1);
|
||||
result.put(key2, value2);
|
||||
return result;
|
||||
|
|
|
@ -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 {
|
|
@ -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;
|
||||
|
|
@ -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<String, String> params = new HashMap<>();
|
||||
params.put("make", "tesla");
|
||||
Result result = session.query("MATCH (car:Car) <-[:owns]- (company:Company)" +
|
|
@ -0,0 +1,16 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
|
||||
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d %5p %40.40c:%4L - %m%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="org.neo4j.ogm" level="info"/>
|
||||
|
||||
<root level="warn">
|
||||
<appender-ref ref="console"/>
|
||||
</root>
|
||||
|
||||
</configuration>
|
|
@ -22,9 +22,15 @@ public class ValidatorEventRegister implements InitializingBean {
|
|||
@Override
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
List<String> events = Arrays.asList("beforeCreate", "afterCreate", "beforeSave", "afterSave", "beforeLinkSave", "afterLinkSave", "beforeDelete", "afterDelete");
|
||||
|
||||
|
||||
for (Map.Entry<String, Validator> 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()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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<Object> 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<Object>(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);
|
||||
}
|
||||
|
||||
}
|
|
@ -51,6 +51,12 @@
|
|||
<version>${spring.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- This is included in spring-data-solr above, no need to include twice
|
||||
<dependency>
|
||||
<groupId>org.apache.solr</groupId>
|
||||
<artifactId>solr-solrj</artifactId>
|
||||
<version>5.5.0</version>
|
||||
</dependency-->
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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)
|
||||
|
|
|
@ -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
|
||||
```
|
||||
|
|
|
@ -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");
|
||||
}
|
||||
|
||||
}
|
|
@ -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
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -19,10 +19,16 @@
|
|||
always-use-default-target="true"/>
|
||||
|
||||
<logout logout-url="/perform_logout" delete-cookies="JSESSIONID" success-handler-ref="customLogoutSuccessHandler"/>
|
||||
|
||||
<!-- <access-denied-handler error-page="/accessDenied"/> -->
|
||||
<access-denied-handler ref="customAccessDeniedHandler"/>
|
||||
|
||||
</http>
|
||||
|
||||
<beans:bean name="customLogoutSuccessHandler" class="org.baeldung.security.CustomLogoutSuccessHandler"/>
|
||||
|
||||
<beans:bean name="customAccessDeniedHandler" class="org.baeldung.security.CustomAccessDeniedHandler" />
|
||||
|
||||
<authentication-manager>
|
||||
<authentication-provider>
|
||||
<user-service>
|
||||
|
|
|
@ -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"%>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>Access Denied</title>
|
||||
</head>
|
||||
<body>
|
||||
<h2>Sorry, you do not have permission to view this page.</h2>
|
||||
|
||||
Click <a href="<c:url value="/homepage.html" /> ">here</a> to go back to the Homepage.
|
||||
</body>
|
||||
</html>
|
|
@ -4,21 +4,23 @@
|
|||
<head></head>
|
||||
|
||||
<body>
|
||||
<h1>This is the body of the sample view</h1>
|
||||
<h1>This is the body of the sample view</h1>
|
||||
|
||||
<security:authorize access="hasRole('ROLE_USER')">
|
||||
This text is only visible to a user
|
||||
<br/>
|
||||
</security:authorize>
|
||||
<security:authorize access="hasRole('ROLE_USER')">
|
||||
This text is only visible to a user
|
||||
<br/> <br/>
|
||||
<a href="<c:url value="/admin/adminpage.html" />">Restricted Admin Page</a>
|
||||
<br/> <br/>
|
||||
</security:authorize>
|
||||
|
||||
<security:authorize access="hasRole('ROLE_ADMIN')">
|
||||
This text is only visible to an admin
|
||||
<br/>
|
||||
<security:authorize access="hasRole('ROLE_ADMIN')">
|
||||
This text is only visible to an admin
|
||||
<br/>
|
||||
<a href="<c:url value="/admin/adminpage.html" />">Admin Page</a>
|
||||
<br/>
|
||||
</security:authorize>
|
||||
</security:authorize>
|
||||
|
||||
<a href="<c:url value="/perform_logout" />">Logout</a>
|
||||
|
||||
<a href="<c:url value="/perform_logout" />">Logout</a>
|
||||
|
||||
</body>
|
||||
</html>
|
|
@ -43,8 +43,15 @@
|
|||
<url-pattern>/*</url-pattern>
|
||||
</filter-mapping>
|
||||
|
||||
<error-page>
|
||||
<error-code>403</error-code>
|
||||
<location>/accessDenied</location>
|
||||
</error-page>
|
||||
|
||||
<!-- <welcome-file-list> -->
|
||||
<!-- <welcome-file>index.html</welcome-file> -->
|
||||
<!-- </welcome-file-list> -->
|
||||
|
||||
|
||||
|
||||
</web-app>
|
|
@ -1,16 +1,12 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://java.sun.com/xml/ns/javaee"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
|
||||
id="WebApp_ID" version="3.0">
|
||||
<display-name>MyStrutsApp</display-name>
|
||||
<filter>
|
||||
<filter-name>struts2</filter-name>
|
||||
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
|
||||
</filter>
|
||||
|
||||
<filter-mapping>
|
||||
<filter-name>struts2</filter-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
</filter-mapping>
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
|
||||
<display-name>struts</display-name>
|
||||
<filter>
|
||||
<filter-name>struts2</filter-name>
|
||||
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
|
||||
</filter>
|
||||
<filter-mapping>
|
||||
<filter-name>struts2</filter-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
</filter-mapping>
|
||||
</web-app>
|
110
struts2/pom.xml
110
struts2/pom.xml
|
@ -1,48 +1,66 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>struts2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>war</packaging>
|
||||
<name>struts2</name>
|
||||
|
||||
<build>
|
||||
<sourceDirectory>src</sourceDirectory>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src</directory>
|
||||
<excludes>
|
||||
<exclude>**/*.java</exclude>
|
||||
</excludes>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>3.0.0</version>
|
||||
<configuration>
|
||||
<warSourceDirectory>WebContent</warSourceDirectory>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-core -->
|
||||
<dependency>
|
||||
<groupId>org.apache.struts</groupId>
|
||||
<artifactId>struts2-core</artifactId>
|
||||
<version>2.5.5</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>MyStrutsApp</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>war</packaging>
|
||||
<name>struts</name>
|
||||
<build>
|
||||
<sourceDirectory>src/main/java</sourceDirectory>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>3.0.0</version>
|
||||
<configuration>
|
||||
<warSourceDirectory>WebContent</warSourceDirectory>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.struts</groupId>
|
||||
<artifactId>struts2-core</artifactId>
|
||||
<version>2.5.5</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.struts</groupId>
|
||||
<artifactId>struts2-junit-plugin</artifactId>
|
||||
<version>2.5.5</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.struts</groupId>
|
||||
<artifactId>struts2-convention-plugin</artifactId>
|
||||
<version>2.5.8</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>3.0.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>4.3.6.RELEASE</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
|
@ -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();
|
|
@ -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";
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,12 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE struts PUBLIC
|
||||
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
|
||||
"http://struts.apache.org/dtds/struts-2.0.dtd">
|
||||
<struts>
|
||||
<package name="tutorial" extends="struts-default" namespace="/tutorial">
|
||||
<action name="car" class="com.baeldung.struts.CarAction"
|
||||
method="execute">
|
||||
<result name="success">/result.jsp</result>
|
||||
</action>
|
||||
</package>
|
||||
</struts>
|
|
@ -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!");
|
||||
// }
|
||||
//
|
||||
//}
|
Loading…
Reference in New Issue