* BAEL-2294

* BAEL-2294

* live tests...

* formatting

* Live Tests! But not parent pom. Yet.
This commit is contained in:
Andrea Ligios 2019-01-23 18:12:06 +01:00 committed by maibin
parent effde80333
commit 4c7ef02bf3
35 changed files with 1004 additions and 0 deletions

5
blade/README.md Normal file
View File

@ -0,0 +1,5 @@
### Relevant Articles:
- [Blade - A Complete GuideBook](http://www.baeldung.com/blade)
Run Integration Tests with `mvn integration-test`

189
blade/pom.xml Normal file
View File

@ -0,0 +1,189 @@
<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>
<artifactId>blade</artifactId>
<name>blade</name>
<!-- WITH THIS mvn integration-test DOES WORK -->
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
<!-- WITH THIS mvn integration-test DOESN'T WORK -->
<!-- <parent> -->
<!-- <groupId>com.baeldung</groupId> -->
<!-- <artifactId>parent-modules</artifactId> -->
<!-- <version>1.0.0-SNAPSHOT</version> -->
<!-- </parent> -->
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.bladejava</groupId>
<artifactId>blade-mvc</artifactId>
<version>2.0.14.RELEASE</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
<!-- PROVIDED -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
<scope>provided</scope>
</dependency>
<!-- TEST -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.11.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>sample-blade-app</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<forkCount>3</forkCount>
<reuseForks>true</reuseForks>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>3.0.0-M3</version>
<configuration>
<includes>
<include>**/*LiveTest.java</include>
</includes>
</configuration>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.bazaarvoice.maven.plugins</groupId>
<artifactId>process-exec-maven-plugin</artifactId>
<version>0.7</version>
<executions>
<!--Start Blade -->
<execution>
<id>blade-process</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
<configuration>
<name>Blade</name>
<waitForInterrupt>false</waitForInterrupt>
<arguments>
<argument>java</argument>
<argument>-jar</argument>
<argument>sample-blade-app.jar</argument>
</arguments>
</configuration>
</execution>
<!--Stop all processes in reverse order -->
<execution>
<id>stop-all</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop-all</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<finalName>${project.build.finalName}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<archive>
<manifest>
<mainClass>com.baeldung.blade.sample.App</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,38 @@
package com.baeldung.blade.sample;
import com.baeldung.blade.sample.interceptors.BaeldungMiddleware;
import com.blade.Blade;
import com.blade.event.EventType;
import com.blade.mvc.WebContext;
import com.blade.mvc.http.Session;
public class App {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(App.class);
public static void main(String[] args) {
Blade.of()
.get("/", ctx -> ctx.render("index.html"))
.get("/basic-route-example", ctx -> ctx.text("GET called"))
.post("/basic-route-example", ctx -> ctx.text("POST called"))
.put("/basic-route-example", ctx -> ctx.text("PUT called"))
.delete("/basic-route-example", ctx -> ctx.text("DELETE called"))
.addStatics("/custom-static")
// .showFileList(true)
.enableCors(true)
.before("/user/*", ctx -> log.info("[NarrowedHook] Before '/user/*', URL called: " + ctx.uri()))
.on(EventType.SERVER_STARTED, e -> {
String version = WebContext.blade()
.env("app.version")
.orElse("N/D");
log.info("[Event::serverStarted] Loading 'app.version' from configuration, value: " + version);
})
.on(EventType.SESSION_CREATED, e -> {
Session session = (Session) e.attribute("session");
session.attribute("mySessionValue", "Baeldung");
})
.use(new BaeldungMiddleware())
.start(App.class, args);
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.blade.sample;
import com.blade.mvc.annotation.GetRoute;
import com.blade.mvc.annotation.Path;
import com.blade.mvc.http.Request;
import com.blade.mvc.http.Response;
import com.blade.mvc.http.Session;
@Path
public class AttributesExampleController {
public final static String REQUEST_VALUE = "Some Request value";
public final static String SESSION_VALUE = "1337";
public final static String HEADER = "Some Header";
@GetRoute("/request-attribute-example")
public void getRequestAttribute(Request request, Response response) {
request.attribute("request-val", REQUEST_VALUE);
String requestVal = request.attribute("request-val");
response.text(requestVal);
}
@GetRoute("/session-attribute-example")
public void getSessionAttribute(Request request, Response response) {
Session session = request.session();
session.attribute("session-val", SESSION_VALUE);
String sessionVal = session.attribute("session-val");
response.text(sessionVal);
}
@GetRoute("/header-example")
public void getHeader(Request request, Response response) {
String headerVal = request.header("a-header", HEADER);
response.header("a-header", headerVal);
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.blade.sample;
import com.blade.mvc.annotation.Path;
import com.blade.mvc.annotation.Route;
import com.blade.mvc.http.Response;
@Path
public class LogExampleController {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExampleController.class);
@Route(value = "/test-logs")
public void testLogs(Response response) {
log.trace("This is a TRACE Message");
log.debug("This is a DEBUG Message");
log.info("This is an INFO Message");
log.warn("This is a WARN Message");
log.error("This is an ERROR Message");
response.text("Check in ./logs");
}
}

View File

@ -0,0 +1,71 @@
package com.baeldung.blade.sample;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import com.baeldung.blade.sample.vo.User;
import com.blade.mvc.annotation.CookieParam;
import com.blade.mvc.annotation.GetRoute;
import com.blade.mvc.annotation.HeaderParam;
import com.blade.mvc.annotation.JSON;
import com.blade.mvc.annotation.MultipartParam;
import com.blade.mvc.annotation.Param;
import com.blade.mvc.annotation.Path;
import com.blade.mvc.annotation.PathParam;
import com.blade.mvc.annotation.PostRoute;
import com.blade.mvc.http.Response;
import com.blade.mvc.multipart.FileItem;
import com.blade.mvc.ui.RestResponse;
@Path
public class ParameterInjectionExampleController {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ParameterInjectionExampleController.class);
@GetRoute("/params/form")
public void formParam(@Param String name, Response response) {
log.info("name: " + name);
response.text(name);
}
@GetRoute("/params/path/:uid")
public void restfulParam(@PathParam Integer uid, Response response) {
log.info("uid: " + uid);
response.text(String.valueOf(uid));
}
@PostRoute("/params-file") // DO NOT USE A SLASH WITHIN THE ROUTE OR IT WILL BREAK (?)
@JSON
public RestResponse<?> fileParam(@MultipartParam FileItem fileItem) throws Exception {
try {
byte[] fileContent = fileItem.getData();
log.debug("Saving the uploaded file");
java.nio.file.Path tempFile = Files.createTempFile("baeldung_tempfiles", ".tmp");
Files.write(tempFile, fileContent, StandardOpenOption.WRITE);
return RestResponse.ok();
} catch (Exception e) {
log.error(e.getMessage(), e);
return RestResponse.fail(e.getMessage());
}
}
@GetRoute("/params/header")
public void headerParam(@HeaderParam String customheader, Response response) {
log.info("Custom header: " + customheader);
response.text(customheader);
}
@GetRoute("/params/cookie")
public void cookieParam(@CookieParam(defaultValue = "default value") String myCookie, Response response) {
log.info("myCookie: " + myCookie);
response.text(myCookie);
}
@PostRoute("/params/vo")
public void voParam(@Param User user, Response response) {
log.info("user as voParam: " + user.toString());
response.html(user.toString() + "<br/><br/><a href='/'>Back</a>");
}
}

View File

@ -0,0 +1,78 @@
package com.baeldung.blade.sample;
import com.baeldung.blade.sample.configuration.BaeldungException;
import com.blade.mvc.WebContext;
import com.blade.mvc.annotation.DeleteRoute;
import com.blade.mvc.annotation.GetRoute;
import com.blade.mvc.annotation.Path;
import com.blade.mvc.annotation.PostRoute;
import com.blade.mvc.annotation.PutRoute;
import com.blade.mvc.annotation.Route;
import com.blade.mvc.http.HttpMethod;
import com.blade.mvc.http.Request;
import com.blade.mvc.http.Response;
@Path
public class RouteExampleController {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(RouteExampleController.class);
@GetRoute("/route-example")
public String get() {
return "get.html";
}
@PostRoute("/route-example")
public String post() {
return "post.html";
}
@PutRoute("/route-example")
public String put() {
return "put.html";
}
@DeleteRoute("/route-example")
public String delete() {
return "delete.html";
}
@Route(value = "/another-route-example", method = HttpMethod.GET)
public String anotherGet() {
return "get.html";
}
@Route(value = "/allmatch-route-example")
public String allmatch() {
return "allmatch.html";
}
@Route(value = "/triggerInternalServerError")
public void triggerInternalServerError() {
int x = 1 / 0;
}
@Route(value = "/triggerBaeldungException")
public void triggerBaeldungException() throws BaeldungException {
throw new BaeldungException("Foobar Exception to threat differently");
}
@Route(value = "/user/foo")
public void urlCoveredByNarrowedWebhook(Response response) {
response.text("Check out for the WebHook covering '/user/*' in the logs");
}
@GetRoute("/load-configuration-in-a-route")
public void loadConfigurationInARoute(Response response) {
String authors = WebContext.blade()
.env("app.authors", "Unknown authors");
log.info("[/load-configuration-in-a-route] Loading 'app.authors' from configuration, value: " + authors);
response.render("index.html");
}
@GetRoute("/template-output-test")
public void templateOutputTest(Request request, Response response) {
request.attribute("name", "Blade");
response.render("template-output-test.html");
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.blade.sample.configuration;
public class BaeldungException extends RuntimeException {
public BaeldungException(String message) {
super(message);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.blade.sample.configuration;
import com.blade.ioc.annotation.Bean;
import com.blade.mvc.WebContext;
import com.blade.mvc.handler.DefaultExceptionHandler;
@Bean
public class GlobalExceptionHandler extends DefaultExceptionHandler {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(GlobalExceptionHandler.class);
@Override
public void handle(Exception e) {
if (e instanceof BaeldungException) {
Exception baeldungException = (BaeldungException) e;
String msg = baeldungException.getMessage();
log.error("[GlobalExceptionHandler] Intercepted an exception to threat with additional logic. Error message: " + msg);
WebContext.response()
.render("index.html");
} else {
super.handle(e);
}
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.blade.sample.configuration;
import com.blade.Blade;
import com.blade.ioc.annotation.Bean;
import com.blade.loader.BladeLoader;
import com.blade.mvc.WebContext;
@Bean
public class LoadConfig implements BladeLoader {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LoadConfig.class);
@Override
public void load(Blade blade) {
String version = WebContext.blade()
.env("app.version")
.orElse("N/D");
String authors = WebContext.blade()
.env("app.authors", "Unknown authors");
log.info("[LoadConfig] loaded 'app.version' (" + version + ") and 'app.authors' (" + authors + ") in a configuration bean");
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.blade.sample.configuration;
import com.blade.ioc.annotation.Bean;
import com.blade.task.annotation.Schedule;
@Bean
public class ScheduleExample {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ScheduleExample.class);
@Schedule(name = "baeldungTask", cron = "0 */1 * * * ?")
public void runScheduledTask() {
log.info("[ScheduleExample] This is a scheduled Task running once per minute.");
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.blade.sample.interceptors;
import com.blade.ioc.annotation.Bean;
import com.blade.mvc.RouteContext;
import com.blade.mvc.hook.WebHook;
@Bean
public class BaeldungHook implements WebHook {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(BaeldungHook.class);
@Override
public boolean before(RouteContext ctx) {
log.info("[BaeldungHook] called before Route method");
return true;
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.blade.sample.interceptors;
import com.blade.mvc.RouteContext;
import com.blade.mvc.hook.WebHook;
public class BaeldungMiddleware implements WebHook {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(BaeldungMiddleware.class);
@Override
public boolean before(RouteContext context) {
log.info("[BaeldungMiddleware] called before Route method and other WebHooks");
return true;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.blade.sample.vo;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import lombok.Getter;
import lombok.Setter;
public class User {
@Getter @Setter private String name;
@Getter @Setter private String site;
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}

View File

@ -0,0 +1,5 @@
mvc.statics.show-list=true
mvc.view.404=my-404.html
mvc.view.500=my-500.html
app.version=0.0.1
app.authors=Andrea Ligios

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 650 B

View File

@ -0,0 +1 @@
/* App CSS */

View File

View File

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h1>File Upload and download test</h1>
<form id="uploadForm" enctype="multipart/form-data">
<input id="file" type="file" name="file" />
<button id="upload" type="button">Upload</button>
</form>
<br />
<a href="/">Back</a>
<script>
var data = new FormData();
$('#upload').click(function() {
$.ajax({
url : '/params-file',
type : 'POST',
cache : false,
data : new FormData($('#uploadForm')[0]),
processData : false,
contentType : false
}).done(function(res) {
console.log(res);
if (res.success) {
alert('Ok');
} else {
alert(res.msg || 'Error');
}
}).fail(function(res) {
});
});
</script>
</body>
</html>

View File

@ -0,0 +1,25 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h1>User POJO post test</h1>
<form id="uploadForm" action="/params/vo" method="post">
<span>Person POJO:</span>
<input type="text" name="name" placeholder="name"/>
<input type="text" name="site" placeholder="site"/>
<button id="upload" type="submit">Send user object</button>
</form>
<br />
<a href="/">Back</a>
</body>
</html>

View File

@ -0,0 +1 @@
ALLMATCH called

View File

@ -0,0 +1 @@
DELETE called

View File

@ -0,0 +1 @@
GET called

View File

@ -0,0 +1,30 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Baeldung Blade App • Written by Andrea Ligios</title>
<link href="/static/app.css" rel="stylesheet" />
</head>
<body>
<h1>Baeldung Blade App - Showcase</h1>
<h3>Manual tests</h3>
<p>The following are tests which are not covered by integration tests, but that can be run manually in order to check the functionality, either in the browser or in the logs, depending on the case.</p>
<ul>
<li><a href="/static/file-upload.html">File Upload</a></li>
<li><a href="/static/user-post.html">User POJO Post</a></li>
<li><a href="/user/foo">Webhook narrowed to the '/user/*' URL</a></li>
<li><a href="/load-configuration-in-a-route">Load Configuration in a Route</a></li>
<li><a href="/triggerInternalServerError">Trigger internal server error (and test the custom error 500 page)</a></li>
<li><a href="/triggerBaeldungException">Trigger BaeldungException (and test the Global Exception Handler)</a></li>
</ul>
<h3>Session value created in App.java</h3>
<p>mySessionValue = ${mySessionValue}</p>
<script src="/static/app.js"></script>
</body>
</html>

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>404 Not found</title>
</head>
<body>
Custom Error 404 Page
</body>
</html>

View File

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>500 Internal Server Error</title>
</head>
<body>
<h1> Custom Error 500 Page </h1>
<p> The following error occurred "<strong>${message}</strong>"</p>
<pre> ${stackTrace} </pre>
</body>
</html>

View File

@ -0,0 +1 @@
POST called

View File

@ -0,0 +1 @@
PUT called

View File

@ -0,0 +1 @@
<h1>Hello, ${name}!</h1>

View File

@ -0,0 +1,56 @@
package com.baeldung.blade.sample;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
public class AppLiveTest {
@Test
public void givenBasicRoute_whenGet_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/basic-route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("GET called");
}
}
@Test
public void givenBasicRoute_whenPost_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpPost("http://localhost:9000/basic-route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("POST called");
}
}
@Test
public void givenBasicRoute_whenPut_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpPut("http://localhost:9000/basic-route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("PUT called");
}
}
@Test
public void givenBasicRoute_whenDelete_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpDelete("http://localhost:9000/basic-route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("DELETE called");
}
}
}

View File

@ -0,0 +1,55 @@
package com.baeldung.blade.sample;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
public class AttributesExampleControllerLiveTest {
@Test
public void givenRequestAttribute_whenSet_thenRetrieveWithGet() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/request-attribute-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo(AttributesExampleController.REQUEST_VALUE);
}
}
@Test
public void givenSessionAttribute_whenSet_thenRetrieveWithGet() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/session-attribute-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo(AttributesExampleController.SESSION_VALUE);
}
}
@Test
public void givenHeader_whenSet_thenRetrieveWithGet() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/header-example");
request.addHeader("a-header","foobar");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(httpResponse.getHeaders("a-header")[0].getValue()).isEqualTo("foobar");
}
}
@Test
public void givenNoHeader_whenSet_thenRetrieveDefaultValueWithGet() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/header-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(httpResponse.getHeaders("a-header")[0].getValue()).isEqualTo(AttributesExampleController.HEADER);
}
}
}

View File

@ -0,0 +1,82 @@
package com.baeldung.blade.sample;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
public class ParameterInjectionExampleControllerLiveTest {
@Test
public void givenFormParam_whenSet_thenRetrieveWithGet() throws Exception {
URIBuilder builder = new URIBuilder("http://localhost:9000/params/form");
builder.setParameter("name", "Andrea Ligios");
final HttpUriRequest request = new HttpGet(builder.build());
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("Andrea Ligios");
}
}
@Test
public void givenPathParam_whenSet_thenRetrieveWithGet() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/params/path/1337");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("1337");
}
}
// @Test
// public void givenFileParam_whenSet_thenRetrieveWithGet() throws Exception {
//
// byte[] data = "this is some temp file content".getBytes("UTF-8");
// java.nio.file.Path tempFile = Files.createTempFile("baeldung_test_tempfiles", ".tmp");
// Files.write(tempFile, data, StandardOpenOption.WRITE);
//
// //HttpEntity entity = MultipartEntityBuilder.create().addPart("file", new FileBody(tempFile.toFile())).build();
// HttpEntity entity = MultipartEntityBuilder.create().addTextBody("field1", "value1")
// .addBinaryBody("fileItem", tempFile.toFile(), ContentType.create("application/octet-stream"), "file1.txt").build();
//
// final HttpPost post = new HttpPost("http://localhost:9000/params-file");
// post.setEntity(entity);
//
// try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create().build().execute(post);) {
// assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("file1.txt");
// }
// }
@Test
public void givenHeader_whenSet_thenRetrieveWithGet() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/params/header");
request.addHeader("customheader", "foobar");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("foobar");
}
}
@Test
public void givenNoCookie_whenCalled_thenReadDefaultValue() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/params/cookie");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("default value");
}
}
}

View File

@ -0,0 +1,117 @@
package com.baeldung.blade.sample;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
public class RouteExampleControllerLiveTest {
@Test
public void givenRoute_whenGet_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("GET called");
}
}
@Test
public void givenRoute_whenPost_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpPost("http://localhost:9000/route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("POST called");
}
}
@Test
public void givenRoute_whenPut_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpPut("http://localhost:9000/route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("PUT called");
}
}
@Test
public void givenRoute_whenDelete_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpDelete("http://localhost:9000/route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("DELETE called");
}
}
@Test
public void givenAnotherRoute_whenGet_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/another-route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("GET called");
}
}
@Test
public void givenAllMatchRoute_whenGet_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/allmatch-route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("ALLMATCH called");
}
}
@Test
public void givenAllMatchRoute_whenPost_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpPost("http://localhost:9000/allmatch-route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("ALLMATCH called");
}
}
@Test
public void givenAllMatchRoute_whenPut_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpPut("http://localhost:9000/allmatch-route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("ALLMATCH called");
}
}
@Test
public void givenAllMatchRoute_whenDelete_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpDelete("http://localhost:9000/allmatch-route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("ALLMATCH called");
}
}
@Test
public void givenRequestAttribute_whenRenderedWithTemplate_thenCorrectlyEvaluateIt() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/template-output-test");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("<h1>Hello, Blade!</h1>");
}
}
}

View File

@ -367,6 +367,8 @@
<module>axon</module>
<module>azure</module>
<module>blade</module>
<module>bootique</module>
<module>cas/cas-secured-app</module>