Merge branch 'master' of https://github.com/sbmaggarwal/tutorials
This commit is contained in:
commit
bb56f50bc2
|
@ -1,11 +1,12 @@
|
|||
package com.baeldung.file;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
@ -14,12 +15,6 @@ import java.nio.file.Path;
|
|||
import java.nio.file.Paths;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileOperationsUnitTest {
|
||||
|
||||
@Test
|
||||
|
@ -58,9 +53,9 @@ public class FileOperationsUnitTest {
|
|||
|
||||
@Test
|
||||
public void givenURLName_whenUsingURL_thenFileData() throws IOException {
|
||||
String expectedData = "Baeldung";
|
||||
String expectedData = "Example Domain";
|
||||
|
||||
URL urlObject = new URL("http://www.baeldung.com/");
|
||||
URL urlObject = new URL("http://www.example.com/");
|
||||
|
||||
URLConnection urlConnection = urlObject.openConnection();
|
||||
|
||||
|
|
|
@ -58,19 +58,18 @@ public class AsyncEchoServer2 {
|
|||
|
||||
@Override
|
||||
public void completed(Integer result, Map<String, Object> attachment) {
|
||||
Map<String, Object> actionInfo = attachment;
|
||||
String action = (String) actionInfo.get("action");
|
||||
String action = (String) attachment.get("action");
|
||||
if ("read".equals(action)) {
|
||||
ByteBuffer buffer = (ByteBuffer) actionInfo.get("buffer");
|
||||
ByteBuffer buffer = (ByteBuffer) attachment.get("buffer");
|
||||
buffer.flip();
|
||||
actionInfo.put("action", "write");
|
||||
clientChannel.write(buffer, actionInfo, this);
|
||||
attachment.put("action", "write");
|
||||
clientChannel.write(buffer, attachment, this);
|
||||
buffer.clear();
|
||||
} else if ("write".equals(action)) {
|
||||
ByteBuffer buffer = ByteBuffer.allocate(32);
|
||||
actionInfo.put("action", "read");
|
||||
actionInfo.put("buffer", buffer);
|
||||
clientChannel.read(buffer, actionInfo, this);
|
||||
attachment.put("action", "read");
|
||||
attachment.put("buffer", buffer);
|
||||
clientChannel.read(buffer, attachment, this);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package com.baeldung.java.nio2.async;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
|
@ -11,22 +11,22 @@ import java.nio.file.Path;
|
|||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class AsyncFileTest {
|
||||
@Test
|
||||
public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException {
|
||||
Path path = Paths.get(URI.create(new AsyncFileTest().getClass().getResource("/file.txt").toString()));
|
||||
public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
|
||||
Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
|
||||
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
|
||||
Future<Integer> operation = fileChannel.read(buffer, 0);
|
||||
|
||||
while (!operation.isDone())
|
||||
;
|
||||
operation.get();
|
||||
|
||||
String fileContent = new String(buffer.array()).trim();
|
||||
buffer.clear();
|
||||
|
@ -36,7 +36,7 @@ public class AsyncFileTest {
|
|||
|
||||
@Test
|
||||
public void givenPath_whenReadsContentWithCompletionHandler_thenCorrect() throws IOException {
|
||||
Path path = Paths.get(URI.create(new AsyncFileTest().getClass().getResource("/file.txt").toString()));
|
||||
Path path = Paths.get(URI.create(AsyncFileTest.class.getResource("/file.txt").toString()));
|
||||
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
|
@ -58,10 +58,10 @@ public class AsyncFileTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException {
|
||||
String fileName = UUID.randomUUID().toString();
|
||||
public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
|
||||
String fileName = "temp";
|
||||
Path path = Paths.get(fileName);
|
||||
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE,StandardOpenOption.DELETE_ON_CLOSE);
|
||||
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
long position = 0;
|
||||
|
@ -72,9 +72,7 @@ public class AsyncFileTest {
|
|||
Future<Integer> operation = fileChannel.write(buffer, position);
|
||||
buffer.clear();
|
||||
|
||||
while (!operation.isDone()) {
|
||||
|
||||
}
|
||||
operation.get();
|
||||
|
||||
String content = readContent(path);
|
||||
assertEquals("hello world", content);
|
||||
|
@ -107,7 +105,7 @@ public class AsyncFileTest {
|
|||
});
|
||||
}
|
||||
|
||||
public static String readContent(Path file) {
|
||||
public static String readContent(Path file) throws ExecutionException, InterruptedException {
|
||||
AsynchronousFileChannel fileChannel = null;
|
||||
try {
|
||||
fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
|
||||
|
@ -120,8 +118,7 @@ public class AsyncFileTest {
|
|||
|
||||
Future<Integer> operation = fileChannel.read(buffer, 0);
|
||||
|
||||
while (!operation.isDone())
|
||||
;
|
||||
operation.get();
|
||||
|
||||
String fileContent = new String(buffer.array()).trim();
|
||||
buffer.clear();
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
package com.baeldung.java.nio2.attributes;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
|
@ -11,15 +11,15 @@ import java.nio.file.attribute.BasicFileAttributeView;
|
|||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.nio.file.attribute.FileTime;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class BasicAttribsTest {
|
||||
private static final String HOME = System.getProperty("user.home");
|
||||
BasicFileAttributes basicAttribs;
|
||||
private static BasicFileAttributes basicAttribs;
|
||||
|
||||
@Before
|
||||
public void setup() throws IOException {
|
||||
@BeforeClass
|
||||
public static void setup() throws IOException {
|
||||
Path home = Paths.get(HOME);
|
||||
BasicFileAttributeView basicView = Files.getFileAttributeView(home, BasicFileAttributeView.class);
|
||||
basicAttribs = basicView.readAttributes();
|
||||
|
@ -31,9 +31,10 @@ public class BasicAttribsTest {
|
|||
FileTime modified = basicAttribs.lastModifiedTime();
|
||||
FileTime accessed = basicAttribs.lastAccessTime();
|
||||
|
||||
assertTrue(0 > created.compareTo(accessed));
|
||||
assertTrue(0 < modified.compareTo(created));
|
||||
assertTrue(0 == created.compareTo(created));
|
||||
System.out.println("Created: " + created);
|
||||
System.out.println("Modified: " + modified);
|
||||
System.out.println("Accessed: " + accessed);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
baeldung.com
|
|
@ -0,0 +1,15 @@
|
|||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
||||
xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
</head>
|
||||
<body>
|
||||
<form action="#" th:action="@{/message/processForm}" method="post">
|
||||
Message: <input type="text" value="message" id="message" name="message"/>
|
||||
<input type="submit" />
|
||||
</form>
|
||||
|
||||
<span th:text="${message}" id="received"></span>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.htmlunit;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.gargoylesoftware.htmlunit.WebClient;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlPage;
|
||||
|
||||
public class HtmlUnitAndJUnitTest {
|
||||
|
||||
@Before
|
||||
public void init() throws Exception {
|
||||
webClient = new WebClient();
|
||||
}
|
||||
|
||||
@After
|
||||
public void close() throws Exception {
|
||||
webClient.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAClient_whenEnteringBaeldung_thenPageTitleIsOk()
|
||||
throws Exception {
|
||||
webClient.getOptions().setThrowExceptionOnScriptError(false);
|
||||
HtmlPage page = webClient.getPage("http://www.baeldung.com/");
|
||||
Assert.assertEquals(
|
||||
"Baeldung | Java, Spring and Web Development tutorials",
|
||||
page.getTitleText());
|
||||
}
|
||||
|
||||
}
|
|
@ -1,72 +0,0 @@
|
|||
package com.baeldung.htmlunit;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.MalformedURLException;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
|
||||
import com.gargoylesoftware.htmlunit.WebClient;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlForm;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlPage;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = { TestConfig.class })
|
||||
public class HtmlUnitAndSpringIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext wac;
|
||||
|
||||
private WebClient webClient;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
webClient = MockMvcWebClientBuilder.webAppContextSetup(wac).build();
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
@Ignore("Related view message.html does not exist check MessageController")
|
||||
public void givenAMessage_whenSent_thenItShows() throws FailingHttpStatusCodeException, MalformedURLException, IOException {
|
||||
final String text = "Hello world!";
|
||||
final HtmlPage page = webClient.getPage("http://localhost/message/showForm");
|
||||
System.out.println(page.asXml());
|
||||
|
||||
final HtmlTextInput messageText = page.getHtmlElementById("message");
|
||||
messageText.setValueAttribute(text);
|
||||
|
||||
final HtmlForm form = page.getForms().get(0);
|
||||
final HtmlSubmitInput submit = form.getOneHtmlElementByAttribute("input", "type", "submit");
|
||||
final HtmlPage newPage = submit.click();
|
||||
|
||||
final String receivedText = newPage.getHtmlElementById("received").getTextContent();
|
||||
|
||||
Assert.assertEquals(receivedText, text);
|
||||
System.out.println(newPage.asXml());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception {
|
||||
try (final WebClient client = new WebClient()) {
|
||||
webClient.getOptions().setThrowExceptionOnScriptError(false);
|
||||
|
||||
final HtmlPage page = webClient.getPage("http://www.baeldung.com/");
|
||||
Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
package com.baeldung.htmlunit;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
|
||||
import com.gargoylesoftware.htmlunit.WebClient;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlForm;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlPage;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = { TestConfig.class })
|
||||
public class HtmlUnitAndSpringTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext wac;
|
||||
|
||||
private WebClient webClient;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
webClient = MockMvcWebClientBuilder
|
||||
.webAppContextSetup(wac).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAMessage_whenSent_thenItShows() throws Exception {
|
||||
String text = "Hello world!";
|
||||
HtmlPage page;
|
||||
|
||||
String url = "http://localhost/message/showForm";
|
||||
page = webClient.getPage(url);
|
||||
|
||||
HtmlTextInput messageText = page.getHtmlElementById("message");
|
||||
messageText.setValueAttribute(text);
|
||||
|
||||
HtmlForm form = page.getForms().get(0);
|
||||
HtmlSubmitInput submit = form.getOneHtmlElementByAttribute(
|
||||
"input", "type", "submit");
|
||||
HtmlPage newPage = submit.click();
|
||||
|
||||
String receivedText = newPage.getHtmlElementById("received")
|
||||
.getTextContent();
|
||||
|
||||
Assert.assertEquals(receivedText, text);
|
||||
}
|
||||
}
|
|
@ -1,21 +0,0 @@
|
|||
package com.baeldung.htmlunit;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.gargoylesoftware.htmlunit.WebClient;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlPage;
|
||||
|
||||
public class HtmlUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception {
|
||||
try (final WebClient webClient = new WebClient()) {
|
||||
webClient.getOptions().setThrowExceptionOnScriptError(false);
|
||||
|
||||
final HtmlPage page = webClient.getPage("http://www.baeldung.com/");
|
||||
Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -5,36 +5,38 @@ import java.util.List;
|
|||
import com.gargoylesoftware.htmlunit.WebClient;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlHeading1;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlHeading2;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlPage;
|
||||
|
||||
public class HtmlUnitWebScraping {
|
||||
|
||||
public static void main(final String[] args) throws Exception {
|
||||
try (final WebClient webClient = new WebClient()) {
|
||||
private WebClient webClient;
|
||||
|
||||
webClient.getOptions().setCssEnabled(false);
|
||||
webClient.getOptions().setJavaScriptEnabled(false);
|
||||
@Before
|
||||
public void init() throws Exception {
|
||||
webClient = new WebClient();
|
||||
}
|
||||
|
||||
final HtmlPage page = webClient.getPage("http://www.baeldung.com/full_archive");
|
||||
final HtmlAnchor latestPostLink = (HtmlAnchor) page.getByXPath("(//ul[@class='car-monthlisting']/li)[1]/a").get(0);
|
||||
@After
|
||||
public void close() throws Exception {
|
||||
webClient.close();
|
||||
}
|
||||
|
||||
System.out.println("Entering: " + latestPostLink.getHrefAttribute());
|
||||
@Test
|
||||
public void givenBaeldungArchive_whenRetrievingArticle_thenHasH1()
|
||||
throws Exception {
|
||||
webClient.getOptions().setCssEnabled(false);
|
||||
webClient.getOptions().setJavaScriptEnabled(false);
|
||||
|
||||
final HtmlPage postPage = latestPostLink.click();
|
||||
String url = "http://www.baeldung.com/full_archive";
|
||||
HtmlPage page = webClient.getPage(url);
|
||||
String xpath = "(//ul[@class='car-monthlisting']/li)[1]/a";
|
||||
HtmlAnchor latestPostLink
|
||||
= (HtmlAnchor) page.getByXPath(xpath).get(0);
|
||||
HtmlPage postPage = latestPostLink.click();
|
||||
|
||||
final HtmlHeading1 heading1 = (HtmlHeading1) postPage.getByXPath("//h1").get(0);
|
||||
System.out.println("Title: " + heading1.getTextContent());
|
||||
|
||||
final List<HtmlHeading2> headings2 = (List<HtmlHeading2>) postPage.getByXPath("//h2");
|
||||
|
||||
final StringBuilder sb = new StringBuilder(heading1.getTextContent());
|
||||
for (final HtmlHeading2 h2 : headings2) {
|
||||
sb.append("\n").append(h2.getTextContent());
|
||||
}
|
||||
|
||||
System.out.println(sb.toString());
|
||||
}
|
||||
}
|
||||
List<HtmlHeading1> h1
|
||||
= (List<HtmlHeading1>) postPage.getByXPath("//h1");
|
||||
|
||||
Assert.assertTrue(h1.size() > 0);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,76 @@
|
|||
package org.baeldung.web.controller;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.baeldung.web.dto.Foo;
|
||||
import org.baeldung.web.exception.ResourceNotFoundException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = "/myfoos")
|
||||
public class MyFooController {
|
||||
|
||||
private final Map<Long, Foo> myfoos;
|
||||
|
||||
public MyFooController() {
|
||||
super();
|
||||
myfoos = new HashMap<Long, Foo>();
|
||||
myfoos.put(1L, new Foo(1L, "sample foo"));
|
||||
}
|
||||
|
||||
// API - read
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public Collection<Foo> findAll() {
|
||||
return myfoos.values();
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/{id}", produces = { "application/json" })
|
||||
@ResponseBody
|
||||
public Foo findById(@PathVariable final long id) {
|
||||
final Foo foo = myfoos.get(id);
|
||||
if (foo == null) {
|
||||
throw new ResourceNotFoundException();
|
||||
}
|
||||
return foo;
|
||||
}
|
||||
|
||||
// API - write
|
||||
|
||||
@RequestMapping(method = RequestMethod.PUT, value = "/{id}")
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ResponseBody
|
||||
public Foo updateFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) {
|
||||
myfoos.put(id, foo);
|
||||
return foo;
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST)
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
@ResponseBody
|
||||
public Foo createFoo(@RequestBody final Foo foo, HttpServletResponse response) {
|
||||
myfoos.put(foo.getId(), foo);
|
||||
response.setHeader("Location", ServletUriComponentsBuilder.fromCurrentRequest().path("/" + foo.getId()).toUriString());
|
||||
return foo;
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
public void deleteById(@PathVariable final long id) {
|
||||
myfoos.remove(id);
|
||||
}
|
||||
|
||||
}
|
|
@ -11,6 +11,12 @@ public class Foo {
|
|||
super();
|
||||
}
|
||||
|
||||
public Foo(final String name) {
|
||||
super();
|
||||
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Foo(final long id, final String name) {
|
||||
super();
|
||||
|
||||
|
|
|
@ -0,0 +1,8 @@
|
|||
package org.baeldung.web.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
@ResponseStatus(value = HttpStatus.NOT_FOUND)
|
||||
public class ResourceNotFoundException extends RuntimeException {
|
||||
}
|
|
@ -8,7 +8,7 @@
|
|||
|
||||
<context:component-scan base-package="org.baeldung.web" />
|
||||
|
||||
<mvc:annotation-driven>
|
||||
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" >
|
||||
<mvc:message-converters register-defaults="true">
|
||||
<!--
|
||||
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
|
||||
|
@ -18,6 +18,7 @@
|
|||
<property name="unmarshaller" ref="xstreamMarshaller" />
|
||||
</bean>
|
||||
-->
|
||||
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
|
||||
<bean class="org.baeldung.config.converter.KryoHttpMessageConverter"/>
|
||||
<bean class="org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter"/>
|
||||
</mvc:message-converters>
|
||||
|
@ -43,6 +44,11 @@
|
|||
<property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
|
||||
|
||||
</bean>
|
||||
|
||||
<bean id="contentNegotiationManager"
|
||||
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
|
||||
<property name="defaultContentType" value="application/json" />
|
||||
</bean>
|
||||
|
||||
|
||||
</beans>
|
||||
|
|
|
@ -1,28 +1,42 @@
|
|||
package org.baeldung.client;
|
||||
|
||||
import static org.apache.commons.codec.binary.Base64.encodeBase64;
|
||||
import static org.baeldung.client.Consts.APPLICATION_PORT;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.hamcrest.CoreMatchers.notNullValue;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.mockito.Matchers.notNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.util.Arrays;
|
||||
import java.util.Set;
|
||||
|
||||
import org.baeldung.web.dto.Foo;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.client.ClientHttpRequestFactory;
|
||||
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
import org.springframework.web.client.RequestCallback;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.common.base.Charsets;
|
||||
|
||||
public class RestTemplateBasicLiveTest {
|
||||
|
||||
private RestTemplate restTemplate;
|
||||
private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-rest/foos";
|
||||
private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-rest/myfoos";
|
||||
|
||||
@Before
|
||||
public void beforeTest() {
|
||||
|
@ -33,19 +47,19 @@ public class RestTemplateBasicLiveTest {
|
|||
|
||||
@Test
|
||||
public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException {
|
||||
ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
|
||||
final ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
|
||||
|
||||
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResourceUrl_whenSendGetForRequestEntity_thenBodyCorrect() throws IOException {
|
||||
ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
|
||||
final ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
|
||||
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
JsonNode root = mapper.readTree(response.getBody());
|
||||
JsonNode name = root.path("name");
|
||||
assertThat(name.asText(), is(notNull()));
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final JsonNode root = mapper.readTree(response.getBody());
|
||||
final JsonNode name = root.path("name");
|
||||
assertThat(name.asText(), notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -56,4 +70,147 @@ public class RestTemplateBasicLiveTest {
|
|||
assertThat(foo.getId(), is(1L));
|
||||
}
|
||||
|
||||
// HEAD, OPTIONS
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() {
|
||||
final HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl);
|
||||
|
||||
assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON));
|
||||
}
|
||||
|
||||
// POST
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenPostForObject_thenCreatedObjectIsReturned() {
|
||||
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
|
||||
final Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class);
|
||||
assertThat(foo, notNullValue());
|
||||
assertThat(foo.getName(), is("bar"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenPostForLocation_thenCreatedLocationIsReturned() {
|
||||
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
|
||||
final URI location = restTemplate.postForLocation(fooResourceUrl, request);
|
||||
assertThat(location, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenPostResource_thenResourceIsCreated() {
|
||||
final RestTemplate template = new RestTemplate();
|
||||
|
||||
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
|
||||
|
||||
final ResponseEntity<Foo> response = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
|
||||
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
|
||||
final Foo foo = response.getBody();
|
||||
assertThat(foo, notNullValue());
|
||||
assertThat(foo.getName(), is("bar"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() {
|
||||
final Set<HttpMethod> optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl);
|
||||
final HttpMethod[] supportedMethods = { HttpMethod.GET, HttpMethod.POST, HttpMethod.HEAD };
|
||||
|
||||
assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods)));
|
||||
}
|
||||
|
||||
// PUT
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenPutExistingEntity_thenItIsUpdated() {
|
||||
final RestTemplate template = new RestTemplate();
|
||||
final HttpHeaders headers = prepareBasicAuthHeaders();
|
||||
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
|
||||
|
||||
// Create Resource
|
||||
final ResponseEntity<Foo> createResponse = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
|
||||
|
||||
// Update Resource
|
||||
final Foo updatedInstance = new Foo("newName");
|
||||
updatedInstance.setId(createResponse.getBody().getId());
|
||||
final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody().getId();
|
||||
final HttpEntity<Foo> requestUpdate = new HttpEntity<>(updatedInstance, headers);
|
||||
template.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class);
|
||||
|
||||
// Check that Resource was updated
|
||||
final ResponseEntity<Foo> updateResponse = template.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class);
|
||||
final Foo foo = updateResponse.getBody();
|
||||
assertThat(foo.getName(), is(updatedInstance.getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenPutExistingEntityWithCallback_thenItIsUpdated() {
|
||||
final RestTemplate template = new RestTemplate();
|
||||
final HttpHeaders headers = prepareBasicAuthHeaders();
|
||||
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
|
||||
|
||||
// Create entity
|
||||
ResponseEntity<Foo> response = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
|
||||
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
|
||||
|
||||
// Update entity
|
||||
final Foo updatedInstance = new Foo("newName");
|
||||
updatedInstance.setId(response.getBody().getId());
|
||||
final String resourceUrl = fooResourceUrl + '/' + response.getBody().getId();
|
||||
template.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null);
|
||||
|
||||
// Check that entity was updated
|
||||
response = template.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class);
|
||||
final Foo foo = response.getBody();
|
||||
assertThat(foo.getName(), is(updatedInstance.getName()));
|
||||
}
|
||||
|
||||
// DELETE
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenCallDelete_thenEntityIsRemoved() {
|
||||
final Foo foo = new Foo("remove me");
|
||||
final ResponseEntity<Foo> response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class);
|
||||
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
|
||||
|
||||
final String entityUrl = fooResourceUrl + "/" + response.getBody().getId();
|
||||
restTemplate.delete(entityUrl);
|
||||
try {
|
||||
restTemplate.getForEntity(entityUrl, Foo.class);
|
||||
fail();
|
||||
} catch (final HttpClientErrorException ex) {
|
||||
assertThat(ex.getStatusCode(), is(HttpStatus.NOT_FOUND));
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
private HttpHeaders prepareBasicAuthHeaders() {
|
||||
final HttpHeaders headers = new HttpHeaders();
|
||||
final String encodedLogPass = getBase64EncodedLogPass();
|
||||
headers.add(HttpHeaders.AUTHORIZATION, "Basic " + encodedLogPass);
|
||||
return headers;
|
||||
}
|
||||
|
||||
private String getBase64EncodedLogPass() {
|
||||
final String logPass = "user1:user1Pass";
|
||||
final byte[] authHeaderBytes = encodeBase64(logPass.getBytes(Charsets.US_ASCII));
|
||||
return new String(authHeaderBytes, Charsets.US_ASCII);
|
||||
}
|
||||
|
||||
private RequestCallback requestCallback(final Foo updatedInstance) {
|
||||
return clientHttpRequest -> {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.writeValue(clientHttpRequest.getBody(), updatedInstance);
|
||||
clientHttpRequest.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
|
||||
clientHttpRequest.getHeaders().add(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass());
|
||||
};
|
||||
}
|
||||
|
||||
// Simply setting restTemplate timeout using ClientHttpRequestFactory
|
||||
|
||||
ClientHttpRequestFactory getSimpleClientHttpRequestFactory() {
|
||||
final int timeout = 5;
|
||||
final HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
|
||||
clientHttpRequestFactory.setConnectTimeout(timeout * 1000);
|
||||
return clientHttpRequestFactory;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
package org.baeldung.okhttp;
|
||||
|
||||
import static org.baeldung.client.Consts.APPLICATION_PORT;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
@ -7,10 +8,6 @@ import static org.junit.Assert.assertThat;
|
|||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.baeldung.okhttp.ProgressRequestWrapper;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import okhttp3.Call;
|
||||
import okhttp3.MediaType;
|
||||
import okhttp3.MultipartBody;
|
||||
|
@ -19,33 +16,29 @@ import okhttp3.Request;
|
|||
import okhttp3.RequestBody;
|
||||
import okhttp3.Response;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class OkHttpFileUploadingLiveTest {
|
||||
|
||||
private static final String BASE_URL = "http://localhost:8080/spring-rest";
|
||||
private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest";
|
||||
|
||||
OkHttpClient client;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
client = new OkHttpClient();
|
||||
client = new OkHttpClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUploadFile_thenCorrect() throws IOException {
|
||||
|
||||
RequestBody requestBody = new MultipartBody.Builder()
|
||||
.setType(MultipartBody.FORM)
|
||||
.addFormDataPart("file", "file.txt",
|
||||
RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt")))
|
||||
.build();
|
||||
final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build();
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(BASE_URL + "/users/upload")
|
||||
.post(requestBody)
|
||||
.build();
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/users/upload").post(requestBody).build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
Response response = call.execute();
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
@ -53,25 +46,18 @@ public class OkHttpFileUploadingLiveTest {
|
|||
@Test
|
||||
public void whenGetUploadFileProgress_thenCorrect() throws IOException {
|
||||
|
||||
RequestBody requestBody = new MultipartBody.Builder()
|
||||
.setType(MultipartBody.FORM)
|
||||
.addFormDataPart("file", "file.txt",
|
||||
RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt")))
|
||||
.build();
|
||||
final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build();
|
||||
|
||||
ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, (long bytesWritten, long contentLength) -> {
|
||||
final ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, (long bytesWritten, long contentLength) -> {
|
||||
|
||||
float percentage = 100f * bytesWritten / contentLength;
|
||||
final float percentage = (100f * bytesWritten) / contentLength;
|
||||
assertFalse(Float.compare(percentage, 100) > 0);
|
||||
});
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(BASE_URL + "/users/upload")
|
||||
.post(countingBody)
|
||||
.build();
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/users/upload").post(countingBody).build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
Response response = call.execute();
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
|
||||
|
|
|
@ -1,14 +1,12 @@
|
|||
package org.baeldung.okhttp;
|
||||
|
||||
import static org.baeldung.client.Consts.APPLICATION_PORT;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import okhttp3.Call;
|
||||
import okhttp3.Callback;
|
||||
import okhttp3.HttpUrl;
|
||||
|
@ -16,9 +14,12 @@ import okhttp3.OkHttpClient;
|
|||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class OkHttpGetLiveTest {
|
||||
|
||||
private static final String BASE_URL = "http://localhost:8080/spring-rest";
|
||||
private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest";
|
||||
|
||||
OkHttpClient client;
|
||||
|
||||
|
@ -30,40 +31,42 @@ public class OkHttpGetLiveTest {
|
|||
|
||||
@Test
|
||||
public void whenGetRequest_thenCorrect() throws IOException {
|
||||
Request request = new Request.Builder().url(BASE_URL + "/date").build();
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/date").build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
Response response = call.execute();
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException {
|
||||
HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder();
|
||||
final HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder();
|
||||
urlBuilder.addQueryParameter("id", "1");
|
||||
|
||||
String url = urlBuilder.build().toString();
|
||||
final String url = urlBuilder.build().toString();
|
||||
|
||||
Request request = new Request.Builder().url(url).build();
|
||||
final Request request = new Request.Builder().url(url).build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
Response response = call.execute();
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException {
|
||||
Request request = new Request.Builder().url(BASE_URL + "/date").build();
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/date").build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
final Call call = client.newCall(request);
|
||||
|
||||
call.enqueue(new Callback() {
|
||||
@Override
|
||||
public void onResponse(Call call, Response response) throws IOException {
|
||||
System.out.println("OK");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Call call, IOException e) {
|
||||
fail();
|
||||
}
|
||||
|
|
|
@ -1,27 +1,27 @@
|
|||
package org.baeldung.okhttp;
|
||||
|
||||
import okhttp3.*;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import static org.baeldung.client.Consts.APPLICATION_PORT;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import okhttp3.Cache;
|
||||
import okhttp3.Call;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class OkHttpMiscLiveTest {
|
||||
|
||||
private static final String BASE_URL = "http://localhost:8080/spring-rest";
|
||||
private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest";
|
||||
private static Logger logger = LoggerFactory.getLogger(OkHttpMiscLiveTest.class);
|
||||
|
||||
OkHttpClient client;
|
||||
|
@ -29,31 +29,27 @@ public class OkHttpMiscLiveTest {
|
|||
@Before
|
||||
public void init() {
|
||||
|
||||
client = new OkHttpClient();
|
||||
client = new OkHttpClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSetRequestTimeout_thenFail() throws IOException {
|
||||
OkHttpClient clientWithTimeout = new OkHttpClient.Builder()
|
||||
.readTimeout(1, TimeUnit.SECONDS)
|
||||
.build();
|
||||
final OkHttpClient clientWithTimeout = new OkHttpClient.Builder().readTimeout(1, TimeUnit.SECONDS).build();
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
|
||||
.build();
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
|
||||
.build();
|
||||
|
||||
Call call = clientWithTimeout.newCall(request);
|
||||
Response response = call.execute();
|
||||
final Call call = clientWithTimeout.newCall(request);
|
||||
final Response response = call.execute();
|
||||
response.close();
|
||||
}
|
||||
|
||||
@Test(expected = IOException.class)
|
||||
public void whenCancelRequest_thenCorrect() throws IOException {
|
||||
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
|
||||
final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
|
||||
.build();
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
|
||||
.build();
|
||||
|
||||
final int seconds = 1;
|
||||
final long startNanos = System.nanoTime();
|
||||
|
@ -63,42 +59,38 @@ public class OkHttpMiscLiveTest {
|
|||
// Schedule a job to cancel the call in 1 second.
|
||||
executor.schedule(() -> {
|
||||
|
||||
logger.debug("Canceling call: " + (System.nanoTime() - startNanos) / 1e9f);
|
||||
logger.debug("Canceling call: " + ((System.nanoTime() - startNanos) / 1e9f));
|
||||
call.cancel();
|
||||
logger.debug("Canceled call: " + (System.nanoTime() - startNanos) / 1e9f);
|
||||
logger.debug("Canceled call: " + ((System.nanoTime() - startNanos) / 1e9f));
|
||||
|
||||
}, seconds, TimeUnit.SECONDS);
|
||||
|
||||
logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f);
|
||||
Response response = call.execute();
|
||||
logger.debug("Call completed: " + (System.nanoTime() - startNanos) / 1e9f, response);
|
||||
logger.debug("Executing call: " + ((System.nanoTime() - startNanos) / 1e9f));
|
||||
final Response response = call.execute();
|
||||
logger.debug("Call completed: " + ((System.nanoTime() - startNanos) / 1e9f), response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSetResponseCache_thenCorrect() throws IOException {
|
||||
public void whenSetResponseCache_thenCorrect() throws IOException {
|
||||
|
||||
int cacheSize = 10 * 1024 * 1024; // 10 MiB
|
||||
File cacheDirectory = new File("src/test/resources/cache");
|
||||
Cache cache = new Cache(cacheDirectory, cacheSize);
|
||||
final int cacheSize = 10 * 1024 * 1024; // 10 MiB
|
||||
final File cacheDirectory = new File("src/test/resources/cache");
|
||||
final Cache cache = new Cache(cacheDirectory, cacheSize);
|
||||
|
||||
OkHttpClient clientCached = new OkHttpClient.Builder()
|
||||
.cache(cache)
|
||||
.build();
|
||||
final OkHttpClient clientCached = new OkHttpClient.Builder().cache(cache).build();
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url("http://publicobject.com/helloworld.txt")
|
||||
.build();
|
||||
final Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build();
|
||||
|
||||
Response response1 = clientCached.newCall(request).execute();
|
||||
final Response response1 = clientCached.newCall(request).execute();
|
||||
logResponse(response1);
|
||||
|
||||
Response response2 = clientCached.newCall(request).execute();
|
||||
final Response response2 = clientCached.newCall(request).execute();
|
||||
logResponse(response2);
|
||||
}
|
||||
|
||||
private void logResponse(Response response) throws IOException {
|
||||
|
||||
logger.debug("Response response: " + response);
|
||||
logger.debug("Response response: " + response);
|
||||
logger.debug("Response cache response: " + response.cacheResponse());
|
||||
logger.debug("Response network response: " + response.networkResponse());
|
||||
logger.debug("Response responseBody: " + response.body().string());
|
||||
|
|
|
@ -1,14 +1,12 @@
|
|||
package org.baeldung.okhttp;
|
||||
|
||||
import static org.baeldung.client.Consts.APPLICATION_PORT;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import okhttp3.Call;
|
||||
import okhttp3.Credentials;
|
||||
import okhttp3.FormBody;
|
||||
|
@ -19,9 +17,12 @@ import okhttp3.Request;
|
|||
import okhttp3.RequestBody;
|
||||
import okhttp3.Response;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class OkHttpPostingLiveTest {
|
||||
|
||||
private static final String BASE_URL = "http://localhost:8080/spring-rest";
|
||||
private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest";
|
||||
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";
|
||||
|
||||
OkHttpClient client;
|
||||
|
@ -29,77 +30,56 @@ public class OkHttpPostingLiveTest {
|
|||
@Before
|
||||
public void init() {
|
||||
|
||||
client = new OkHttpClient();
|
||||
client = new OkHttpClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendPostRequest_thenCorrect() throws IOException {
|
||||
RequestBody formBody = new FormBody.Builder()
|
||||
.add("username", "test")
|
||||
.add("password", "test")
|
||||
.build();
|
||||
final RequestBody formBody = new FormBody.Builder().add("username", "test").add("password", "test").build();
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(BASE_URL + "/users")
|
||||
.post(formBody)
|
||||
.build();
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/users").post(formBody).build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
Response response = call.execute();
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException {
|
||||
String postBody = "test post";
|
||||
final String postBody = "test post";
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(URL_SECURED_BY_BASIC_AUTHENTICATION)
|
||||
.addHeader("Authorization", Credentials.basic("test", "test"))
|
||||
.post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), postBody))
|
||||
.build();
|
||||
final Request request = new Request.Builder().url(URL_SECURED_BY_BASIC_AUTHENTICATION).addHeader("Authorization", Credentials.basic("test", "test")).post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), postBody)).build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
Response response = call.execute();
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPostJson_thenCorrect() throws IOException {
|
||||
String json = "{\"id\":1,\"name\":\"John\"}";
|
||||
final String json = "{\"id\":1,\"name\":\"John\"}";
|
||||
|
||||
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
|
||||
final RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(BASE_URL + "/users/detail")
|
||||
.post(body)
|
||||
.build();
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
Response response = call.execute();
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendMultipartRequest_thenCorrect() throws IOException {
|
||||
RequestBody requestBody = new MultipartBody.Builder()
|
||||
.setType(MultipartBody.FORM)
|
||||
.addFormDataPart("username", "test")
|
||||
.addFormDataPart("password", "test")
|
||||
.addFormDataPart("file", "file.txt",
|
||||
RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt")))
|
||||
.build();
|
||||
final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("username", "test").addFormDataPart("password", "test")
|
||||
.addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build();
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(BASE_URL + "/users/multipart")
|
||||
.post(requestBody)
|
||||
.build();
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/users/multipart").post(requestBody).build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
Response response = call.execute();
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
package org.baeldung.web.test;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
import org.junit.Test;
|
||||
|
@ -31,7 +32,7 @@ public class RequestMappingLiveTest {
|
|||
|
||||
@Test
|
||||
public void givenAcceptHeader_whenGetFoos_thenOk() {
|
||||
RestAssured.given().accept("application/json").get(BASE_URI + "foos").then().assertThat().body(equalTo("Get some Foos with Header New"));
|
||||
RestAssured.given().accept("application/json").get(BASE_URI + "foos").then().assertThat().body(containsString("Get some Foos with Header New"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -1,393 +1,400 @@
|
|||
<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>spring-security-rest</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
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>spring-security-rest</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
|
||||
<name>spring-security-rest</name>
|
||||
<packaging>war</packaging>
|
||||
<name>spring-security-rest</name>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<dependencies>
|
||||
<dependencies>
|
||||
|
||||
<!-- Spring Security -->
|
||||
<!-- Spring Security -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-web</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-config</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-web</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-config</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring -->
|
||||
<!-- Spring -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-jdbc</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-beans</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-aop</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-tx</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-expression</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-jdbc</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-beans</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-aop</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-tx</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-expression</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring HATEOAS -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.hateoas</groupId>
|
||||
<artifactId>spring-hateoas</artifactId>
|
||||
<version>${org.springframework.hateoas.version}</version>
|
||||
</dependency>
|
||||
<!-- Spring HATEOAS -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.hateoas</groupId>
|
||||
<artifactId>spring-hateoas</artifactId>
|
||||
<version>${org.springframework.hateoas.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- web -->
|
||||
<!-- web -->
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>${javax.servlet-api.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>${javax.servlet-api.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jstl</artifactId>
|
||||
<version>${jstl.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jstl</artifactId>
|
||||
<version>${jstl.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
<version>${javax.validation.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
<version>${javax.validation.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- marshalling -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<!-- marshalling -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- util -->
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- logging -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
<!-- <scope>runtime</scope> -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<!-- util -->
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- logging -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
<!-- <scope>runtime</scope> -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-test</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-test</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>com.jayway.restassured</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
<version>${rest-assured.version}</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.restassured</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
<version>${rest-assured.version}</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- swagger -->
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger2</artifactId>
|
||||
<version>${springfox-swagger.version}</version>
|
||||
</dependency>
|
||||
<!-- swagger -->
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger2</artifactId>
|
||||
<version>${springfox-swagger.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger-ui</artifactId>
|
||||
<version>${springfox-swagger.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger-ui</artifactId>
|
||||
<version>${springfox-swagger.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
|
||||
<dependency>
|
||||
<groupId>commons-fileupload</groupId>
|
||||
<artifactId>commons-fileupload</artifactId>
|
||||
<version>1.3.2</version>
|
||||
</dependency>
|
||||
|
||||
<build>
|
||||
<finalName>spring-security-rest</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</dependencies>
|
||||
|
||||
<plugins>
|
||||
<build>
|
||||
<finalName>spring-security-rest</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>${maven-war-plugin.version}</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</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>
|
||||
<!-- <provPersistenceTarget>h2</provPersistenceTarget> -->
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>${maven-war-plugin.version}</version>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.cargo</groupId>
|
||||
<artifactId>cargo-maven2-plugin</artifactId>
|
||||
<version>${cargo-maven2-plugin.version}</version>
|
||||
<configuration>
|
||||
<container>
|
||||
<containerId>jetty8x</containerId>
|
||||
<type>embedded</type>
|
||||
<systemProperties>
|
||||
<!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
|
||||
</systemProperties>
|
||||
</container>
|
||||
<configuration>
|
||||
<properties>
|
||||
<cargo.servlet.port>8082</cargo.servlet.port>
|
||||
</properties>
|
||||
</configuration>
|
||||
</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>
|
||||
<!-- <provPersistenceTarget>h2</provPersistenceTarget> -->
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.cargo</groupId>
|
||||
<artifactId>cargo-maven2-plugin</artifactId>
|
||||
<version>${cargo-maven2-plugin.version}</version>
|
||||
<configuration>
|
||||
<container>
|
||||
<containerId>jetty8x</containerId>
|
||||
<type>embedded</type>
|
||||
<systemProperties>
|
||||
<!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
|
||||
</systemProperties>
|
||||
</container>
|
||||
<configuration>
|
||||
<properties>
|
||||
<cargo.servlet.port>8082</cargo.servlet.port>
|
||||
</properties>
|
||||
</configuration>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</build>
|
||||
</plugins>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>live</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.cargo</groupId>
|
||||
<artifactId>cargo-maven2-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>start-server</id>
|
||||
<phase>pre-integration-test</phase>
|
||||
<goals>
|
||||
<goal>start</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>stop-server</id>
|
||||
<phase>post-integration-test</phase>
|
||||
<goals>
|
||||
<goal>stop</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</build>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>none</exclude>
|
||||
</excludes>
|
||||
<includes>
|
||||
<include>**/*LiveTest.java</include>
|
||||
</includes>
|
||||
<systemPropertyVariables>
|
||||
<webTarget>cargo</webTarget>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>live</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.cargo</groupId>
|
||||
<artifactId>cargo-maven2-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>start-server</id>
|
||||
<phase>pre-integration-test</phase>
|
||||
<goals>
|
||||
<goal>start</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>stop-server</id>
|
||||
<phase>post-integration-test</phase>
|
||||
<goals>
|
||||
<goal>stop</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
|
||||
<properties>
|
||||
<!-- Spring -->
|
||||
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
|
||||
<org.springframework.security.version>4.0.4.RELEASE</org.springframework.security.version>
|
||||
<org.springframework.hateoas.version>0.19.0.RELEASE</org.springframework.hateoas.version>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>none</exclude>
|
||||
</excludes>
|
||||
<includes>
|
||||
<include>**/*LiveTest.java</include>
|
||||
</includes>
|
||||
<systemPropertyVariables>
|
||||
<webTarget>cargo</webTarget>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<!-- persistence -->
|
||||
<hibernate.version>4.3.11.Final</hibernate.version>
|
||||
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
|
||||
<!-- various -->
|
||||
<hibernate-validator.version>5.2.2.Final</hibernate-validator.version>
|
||||
<javax.servlet-api.version>3.0.1</javax.servlet-api.version>
|
||||
<javax.validation.version>1.1.0.Final</javax.validation.version>
|
||||
<jstl.version>1.2</jstl.version>
|
||||
<jackson.version>2.7.8</jackson.version>
|
||||
<properties>
|
||||
<!-- Spring -->
|
||||
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
|
||||
<org.springframework.security.version>4.0.4.RELEASE</org.springframework.security.version>
|
||||
<org.springframework.hateoas.version>0.19.0.RELEASE</org.springframework.hateoas.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.4</commons-lang3.version>
|
||||
<!-- persistence -->
|
||||
<hibernate.version>4.3.11.Final</hibernate.version>
|
||||
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
<rest-assured.version>2.9.0</rest-assured.version>
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
|
||||
<!-- swagger -->
|
||||
<springfox-swagger.version>2.4.0</springfox-swagger.version>
|
||||
<!-- various -->
|
||||
<hibernate-validator.version>5.2.2.Final</hibernate-validator.version>
|
||||
<javax.servlet-api.version>3.0.1</javax.servlet-api.version>
|
||||
<javax.validation.version>1.1.0.Final</javax.validation.version>
|
||||
<jstl.version>1.2</jstl.version>
|
||||
<jackson.version>2.7.8</jackson.version>
|
||||
|
||||
<httpcore.version>4.4.1</httpcore.version>
|
||||
<httpclient.version>4.5</httpclient.version>
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.4</commons-lang3.version>
|
||||
|
||||
<rest-assured.version>2.9.0</rest-assured.version>
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
<rest-assured.version>2.9.0</rest-assured.version>
|
||||
|
||||
<!-- Maven plugins -->
|
||||
<maven-compiler-plugin.version>3.5.1</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>
|
||||
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
|
||||
<!-- swagger -->
|
||||
<springfox-swagger.version>2.4.0</springfox-swagger.version>
|
||||
|
||||
</properties>
|
||||
<httpcore.version>4.4.1</httpcore.version>
|
||||
<httpclient.version>4.5</httpclient.version>
|
||||
|
||||
<rest-assured.version>2.9.0</rest-assured.version>
|
||||
|
||||
<!-- Maven plugins -->
|
||||
<maven-compiler-plugin.version>3.5.1</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>
|
||||
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
|
||||
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,24 @@
|
|||
package org.baeldung.web.controller;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Controller
|
||||
public class AsyncController {
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, value = "/upload")
|
||||
public Callable<Boolean> processUpload(final MultipartFile file) {
|
||||
|
||||
return new Callable<Boolean>() {
|
||||
public Boolean call() throws Exception {
|
||||
// ...
|
||||
return true;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
|
@ -1,6 +1,10 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd" >
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
|
||||
|
||||
<bean id="multipartResolver"
|
||||
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
|
||||
<property name="maxUploadSize" value="1000000" />
|
||||
</bean>
|
||||
</beans>
|
|
@ -1,54 +1,57 @@
|
|||
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
|
||||
xsi:schemaLocation="
|
||||
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
|
||||
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"
|
||||
>
|
||||
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
|
||||
id="WebApp_ID" version="3.0">
|
||||
|
||||
<display-name>Spring MVC Application</display-name>
|
||||
<display-name>Spring MVC Application</display-name>
|
||||
|
||||
<!-- Spring root -->
|
||||
<context-param>
|
||||
<param-name>contextClass</param-name>
|
||||
<param-value>
|
||||
<!-- Spring root -->
|
||||
<context-param>
|
||||
<param-name>contextClass</param-name>
|
||||
<param-value>
|
||||
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
|
||||
</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>contextConfigLocation</param-name>
|
||||
<param-value>org.baeldung.spring</param-value>
|
||||
</context-param>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>contextConfigLocation</param-name>
|
||||
<param-value>org.baeldung.spring</param-value>
|
||||
</context-param>
|
||||
|
||||
<listener>
|
||||
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
|
||||
</listener>
|
||||
<listener>
|
||||
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
|
||||
</listener>
|
||||
|
||||
<!-- Spring child -->
|
||||
<servlet>
|
||||
<servlet-name>api</servlet-name>
|
||||
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
|
||||
<init-param>
|
||||
<param-name>throwExceptionIfNoHandlerFound</param-name>
|
||||
<param-value>true</param-value>
|
||||
</init-param>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>api</servlet-name>
|
||||
<url-pattern>/api/*</url-pattern>
|
||||
</servlet-mapping>
|
||||
<!-- Spring child -->
|
||||
<servlet>
|
||||
<servlet-name>api</servlet-name>
|
||||
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
|
||||
<init-param>
|
||||
<param-name>throwExceptionIfNoHandlerFound</param-name>
|
||||
<param-value>true</param-value>
|
||||
</init-param>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>api</servlet-name>
|
||||
<url-pattern>/api/*</url-pattern>
|
||||
</servlet-mapping>
|
||||
|
||||
<!-- Spring Security -->
|
||||
<filter>
|
||||
<filter-name>springSecurityFilterChain</filter-name>
|
||||
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
|
||||
</filter>
|
||||
<filter-mapping>
|
||||
<filter-name>springSecurityFilterChain</filter-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
</filter-mapping>
|
||||
<!-- Spring Security -->
|
||||
<filter>
|
||||
<filter-name>springSecurityFilterChain</filter-name>
|
||||
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
|
||||
</filter>
|
||||
<filter-mapping>
|
||||
<filter-name>springSecurityFilterChain</filter-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
<dispatcher>REQUEST</dispatcher>
|
||||
<dispatcher>ASYNC</dispatcher>
|
||||
</filter-mapping>
|
||||
|
||||
<!-- <welcome-file-list> -->
|
||||
<!-- <welcome-file>index.html</welcome-file> -->
|
||||
<!-- </welcome-file-list> -->
|
||||
<!-- <welcome-file-list> -->
|
||||
<!-- <welcome-file>index.html</welcome-file> -->
|
||||
<!-- </welcome-file-list> -->
|
||||
|
||||
</web-app>
|
|
@ -0,0 +1,51 @@
|
|||
package org.baeldung.web;
|
||||
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import org.baeldung.spring.ClientWebConfig;
|
||||
import org.baeldung.spring.SecurityJavaConfig;
|
||||
import org.baeldung.spring.WebConfig;
|
||||
import org.baeldung.web.controller.AsyncController;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.mock.web.MockHttpSession;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = { ClientWebConfig.class, SecurityJavaConfig.class, WebConfig.class})
|
||||
public class AsyncControllerTest {
|
||||
|
||||
@Autowired
|
||||
WebApplicationContext wac;
|
||||
@Autowired
|
||||
MockHttpSession session;
|
||||
|
||||
@Mock
|
||||
AsyncController controller;
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessUpload() throws Exception {
|
||||
MockMultipartFile jsonFile = new MockMultipartFile("json", "", "application/json",
|
||||
"{\"json\": \"someValue\"}".getBytes());
|
||||
mockMvc.perform(MockMvcRequestBuilders.fileUpload("/upload").file(jsonFile)).andExpect(status().isOk());
|
||||
}
|
||||
|
||||
}
|
|
@ -1,10 +1,19 @@
|
|||
package org.baeldung.web;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.multipart.MultipartResolver;
|
||||
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan({ "org.baeldung.web" })
|
||||
public class TestConfig {
|
||||
|
||||
@Bean
|
||||
public MultipartResolver multipartResolver() {
|
||||
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
|
||||
return multipartResolver;
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue