Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-633

Conflicts:
	pom.xml
This commit is contained in:
Tomasz Lelek 2017-02-17 16:02:23 +01:00
commit 5b1135cae6
69 changed files with 1223 additions and 328 deletions

101
apache-velocity/pom.xml Normal file
View File

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

View File

@ -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 + '}';
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,4 @@
<div
style="background: #63B175; text-align: center; padding: 5px; margin-top: 10px;">
@Copyright baeldung.com
</div>

View File

@ -0,0 +1,5 @@
<div style="background: #63B175; height: 80px; padding: 5px;">
<div style="float: left">
<h1> Layout Demo Page</h1>
</div>
</div>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -12,7 +12,7 @@ import com.baeldung.string.JoinerSplitter;
public class JoinerSplitterTest {
@Test
public void givenArray_transformedToStream_convertToString() {
public void provided_array_convert_to_stream_and_convert_to_string() {
String[] programming_languages = {"java", "python", "nodejs", "ruby"};
@ -24,6 +24,7 @@ public class JoinerSplitterTest {
@Test
public void givenArray_transformedToStream_convertToPrefixPostfixString() {
String[] programming_languages = {"java", "python",
"nodejs", "ruby"};
String expectation = "[java,python,nodejs,ruby]";
@ -34,6 +35,7 @@ public class JoinerSplitterTest {
@Test
public void givenString_transformedToStream_convertToList() {
String programming_languages = "java,python,nodejs,ruby";
List<String> expectation = new ArrayList<String>();
@ -49,6 +51,7 @@ public class JoinerSplitterTest {
@Test
public void givenString_transformedToStream_convertToListOfChar() {
String programming_languages = "java,python,nodejs,ruby";
List<Character> expectation = new ArrayList<Character>();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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"]

5
mesos-marathon/dockerise.sh Executable file
View File

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

View File

@ -0,0 +1,14 @@
{
"id": "mesos-marathon-demo",
"container": {
"type": "DOCKER",
"docker": {
"image": "",
"network": "BRIDGE",
"portMappings": [
{ "containerPort": 8082, "hostPort": 0 }
]
},
"volumes": []
}
}

46
mesos-marathon/pom.xml Normal file
View File

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

View File

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

View File

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

View File

@ -0,0 +1 @@
server.port=8082

View File

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

View File

@ -81,6 +81,7 @@
<module>mapstruct</module>
<module>metrics</module>
<module>mesos-marathon</module>
<module>mockito</module>
<module>mocks</module>
@ -192,6 +193,8 @@
<module>struts2</module>
<module>cglib</module>
<module>apache-velocity</module>
</modules>

View File

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

View File

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

View File

@ -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) {

View File

@ -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) {

View File

@ -1,4 +1,4 @@
package com.baeldung.annotation.servletcomponentscan.javaee;
package com.baeldung.annotation.servletcomponentscan.components;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

View File

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

View File

@ -1,4 +1,4 @@
package com.baeldung.annotation.servletcomponentscan.javaee;
package com.baeldung.annotation.servletcomponentscan.components;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;

View File

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

View File

@ -0,0 +1,18 @@
package com.baeldung.utils;
import javax.annotation.security.RolesAllowed;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages="com.baeldung.utils")
public class Application {
@RolesAllowed("*")
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.utils.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.util.WebUtils;
@Controller
public class UtilsController {
@GetMapping("/utils")
public String webUtils(Model model) {
return "utils";
}
@PostMapping("/setParam")
public String post(HttpServletRequest request, Model model) {
String param = ServletRequestUtils.getStringParameter(request, "param", "DEFAULT");
// Long param = ServletRequestUtils.getLongParameter(request, "param",1L);
// boolean param = ServletRequestUtils.getBooleanParameter(request, "param", true);
// double param = ServletRequestUtils.getDoubleParameter(request, "param", 1000);
// float param = ServletRequestUtils.getFloatParameter(request, "param", (float) 1.00);
// int param = ServletRequestUtils.getIntParameter(request, "param", 100);
// try {
// ServletRequestUtils.getRequiredStringParameter(request, "param");
// } catch (ServletRequestBindingException e) {
// e.printStackTrace();
// }
WebUtils.setSessionAttribute(request, "parameter", param);
model.addAttribute("parameter", "You set: "+(String) WebUtils.getSessionAttribute(request, "parameter"));
return "utils";
}
@GetMapping("/other")
public String other(HttpServletRequest request, Model model) {
String param = (String) WebUtils.getSessionAttribute(request, "parameter");
model.addAttribute("parameter", param);
return "other";
}
}

View File

@ -0,0 +1,16 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Spring Utils Demo</title>
<style type="text/css">
.param{
color:green;
font-style: italic;
}
</style>
</head>
<body>
Parameter set by you: <p th:text="${parameter}" class="param"/>
</body>
</html>

View File

@ -0,0 +1,23 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Spring Utils Demo</title>
<style type="text/css">
.param{
color:green;
font-style: italic;
}
</style>
</head>
<body>
<form action="setParam" method="POST">
<h3>Set Parameter: </h3>
<p th:text="${parameter}" class="param"/>
<input type="text" name="param" id="param"/>
<input type="submit" value="SET"/>
</form>
<br/>
<a href="other">Another Page</a>
</body>
</html>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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")

View File

@ -6,5 +6,4 @@ import org.springframework.stereotype.Repository;
@Repository
public interface PersonRepository extends GraphRepository<Person> {
}

View File

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

View File

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

View File

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

View File

@ -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)" +

View File

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

View File

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

View File

@ -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;
private SolrInputDocument document;
@Before
public void setUp() throws Exception {
solr = new HttpSolrClient("http://localhost:8983/solr/bigboxstore");
solr.setParser(new XMLResponseParser());
document = new SolrInputDocument();
document.addField("id", "123456");
document.addField("name", "Kenmore Dishwasher");
document.addField("price", "599.99");
solr.add(document);
solr.commit();
}
@Test
public void whenAdd_thenVerifyAdded() throws SolrServerException, IOException {
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 whenDelete_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);
}
}

View File

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

View File

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

View File

@ -5,12 +5,12 @@
<artifactId>MyStrutsApp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>MyStrutsApp</name>
<name>struts</name>
<build>
<sourceDirectory>src</sourceDirectory>
<sourceDirectory>src/main/java</sourceDirectory>
<resources>
<resource>
<directory>src</directory>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
@ -32,28 +32,35 @@
</plugins>
</build>
<dependencies>
<!-- http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22struts2-core%22 -->
<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>
<!-- http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22struts2-core%22 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-junit-plugin</artifactId>
<version>2.5.5</version>
</dependency>
<!-- http://search.maven.org/#search%7Cga%7C1%7Cstruts2-convention-plugin -->
<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>
<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>

View File

@ -1,32 +0,0 @@
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 TestCarAction extends StrutsTestCase {
@Test
public void test_givenCarOptions_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 test_givenCarOptions_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!");
}
}

View File

@ -3,7 +3,6 @@ package com.baeldung.struts;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
@Namespace("/tutorial")
@Action("/car")

View File

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