renamed modules org.springframework.integration.* -> spring-integration-*

@Ignore'd SimpleTcpNetOutboundGatewayTests#testOutboundClose() to avoid failure; this failure is correlated to the module name change, but hard to understand how it would be caused by it
This commit is contained in:
Chris Beams
2010-05-25 13:21:25 +00:00
parent b97b2fb090
commit c08a7a657e
1484 changed files with 18 additions and 23 deletions

View File

@@ -0,0 +1,127 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.http;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.springframework.integration.core.Message;
import org.springframework.integration.handler.ExpressionEvaluatingMessageProcessor;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
/**
* @author Iwein Fuld
* @author Mark Fisher
*/
@SuppressWarnings("unchecked")
public class DefaultInboundRequestMapperTests {
private static final String SIMPLE_STRING = "just ascii";
private static final String COMPLEX_STRING = "A\u00ea\u00f1\u00fcC";
private DefaultInboundRequestMapper mapper = new DefaultInboundRequestMapper();
@Test
public void simpleUtf8TextMapping() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContentType("text");
request.setCharacterEncoding("utf-8");
byte[] bytes = SIMPLE_STRING.getBytes("utf-8");
request.setContent(bytes);
Message<String> message = (Message<String>) mapper.toMessage(request);
assertThat(message.getPayload(), is(SIMPLE_STRING));
}
@Test
public void complexUtf8TextMapping() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContentType("text");
// don't forget to specify the character encoding on the request or you
// will end up with unpredictable results!
request.setCharacterEncoding("utf-8");
byte[] bytes = COMPLEX_STRING.getBytes("utf-8");
request.setContent(bytes);
Message<String> message = (Message<String>) mapper.toMessage(request);
assertThat(message.getPayload(), is(COMPLEX_STRING));
}
@Test
public void newlineTest() throws Exception {
String content = "foo\nbar\n";
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContentType("text");
byte[] bytes = content.getBytes();
request.setContent(bytes);
Message<String> message = (Message<String>) mapper.toMessage(request);
assertThat(message.getPayload(), is(content));
}
@Test
public void emptyStringTest() throws Exception {
String content = "";
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContentType("text");
byte[] bytes = content.getBytes();
request.setContent(bytes);
Message<String> message = (Message<String>) mapper.toMessage(request);
assertThat(message.getPayload(), is(content));
}
@Test
public void multipartUpload() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<String, MultipartFile>();
MultipartFile file = new StubMultipartFile("file", "testFile.txt", "foo");
files.add("file", file);
Map<String, String[]> params = new HashMap<String, String[]>();
MultipartHttpServletRequest multipartRequest = new DefaultMultipartHttpServletRequest(request, files, params);
mapper.setCopyUploadedFiles(true);
Message<?> result = mapper.toMessage(multipartRequest);
File tmpFile = (File) ((Map) result.getPayload()).get("file");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileCopyUtils.copy(new FileInputStream(tmpFile), baos);
assertThat(baos.toString(), is("foo"));
tmpFile.deleteOnExit();
}
@Test
public void testProcessMessageWithDollar() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContentType("text");
request.setCharacterEncoding("utf-8");
byte[] bytes = SIMPLE_STRING.getBytes("utf-8");
request.setContent(bytes);
Message<String> message = (Message<String>) mapper.toMessage(request);
ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor("headers['$http_requestUrl']");
assertEquals(message.getHeaders().get(HttpHeaders.REQUEST_URL), processor.processMessage(message));
}
}

View File

@@ -0,0 +1,142 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.http;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.springframework.integration.core.Message;
import org.springframework.integration.message.MessageBuilder;
/**
* @author Mark Fisher
*/
public class DefaultOutboundRequestMapperTests {
@Test
public void simpleStringValueFormData() throws Exception {
DefaultOutboundRequestMapper mapper = new DefaultOutboundRequestMapper(new URL("http://example.org"));
Map<String, String> form = new LinkedHashMap<String, String>();
form.put("a", "1");
form.put("b", "2");
form.put("c", "3");
Message<?> message = MessageBuilder.withPayload(form).build();
HttpRequest request = mapper.fromMessage(message);
String bodyText = request.getBody().toString("UTF-8");
assertEquals("a=1&b=2&c=3", bodyText);
assertEquals("application/x-www-form-urlencoded", request.getContentType());
}
@Test
@SuppressWarnings("unchecked")
public void stringArrayValueFormData() throws Exception {
DefaultOutboundRequestMapper mapper = new DefaultOutboundRequestMapper(new URL("http://example.org"));
Map form = new LinkedHashMap();
form.put("a", new String[] { "1", "2", "3" });
form.put("b", "4");
form.put("c", new String[] { "5" });
form.put("d", "6");
Message<?> message = MessageBuilder.withPayload(form).build();
HttpRequest request = mapper.fromMessage(message);
String bodyText = request.getBody().toString("UTF-8");
assertEquals("a=1&a=2&a=3&b=4&c=5&d=6", bodyText);
assertEquals("application/x-www-form-urlencoded", request.getContentType());
}
@Test
@SuppressWarnings("unchecked")
public void stringListValueFormData() throws Exception {
DefaultOutboundRequestMapper mapper = new DefaultOutboundRequestMapper(new URL("http://example.org"));
Map form = new LinkedHashMap();
List<String> listA = new ArrayList<String>();
listA.add("1");
listA.add("2");
form.put("a", listA);
form.put("b", Collections.EMPTY_LIST);
form.put("c", Collections.singletonList("3"));
Message<?> message = MessageBuilder.withPayload(form).build();
HttpRequest request = mapper.fromMessage(message);
String bodyText = request.getBody().toString("UTF-8");
assertEquals("a=1&a=2&b&c=3", bodyText);
assertEquals("application/x-www-form-urlencoded", request.getContentType());
}
@Test
@SuppressWarnings("unchecked")
public void nameOnlyWithNullValues() throws Exception {
DefaultOutboundRequestMapper mapper = new DefaultOutboundRequestMapper(new URL("http://example.org"));
Map form = new LinkedHashMap();
form.put("a", null);
form.put("b", "foo");
form.put("c", null);
Message<?> message = MessageBuilder.withPayload(form).build();
HttpRequest request = mapper.fromMessage(message);
String bodyText = request.getBody().toString("UTF-8");
assertEquals("a&b=foo&c", bodyText);
assertEquals("application/x-www-form-urlencoded", request.getContentType());
}
@Test
public void encodedFormData() throws Exception {
DefaultOutboundRequestMapper mapper = new DefaultOutboundRequestMapper(new URL("http://example.org"));
Map<String, String> form = new LinkedHashMap<String, String>();
form.put("a", "1 + 2 + 3");
form.put("b", "4+5");
form.put("c", "97%");
Message<?> message = MessageBuilder.withPayload(form).build();
HttpRequest request = mapper.fromMessage(message);
String bodyText = request.getBody().toString("UTF-8");
assertEquals("a=1+%2B+2+%2B+3&b=4%2B5&c=97%25", bodyText);
assertEquals("application/x-www-form-urlencoded", request.getContentType());
}
@Test
@SuppressWarnings("unchecked")
public void nonFormDataInMap() throws Exception {
DefaultOutboundRequestMapper mapper = new DefaultOutboundRequestMapper(new URL("http://example.org"));
Map<String, TestBean> form = new LinkedHashMap<String, TestBean>();
form.put("A", new TestBean());
form.put("B", new TestBean());
Message<?> message = MessageBuilder.withPayload(form).build();
HttpRequest request = mapper.fromMessage(message);
byte[] body = request.getBody().toByteArray();
ByteArrayInputStream byteStream = new ByteArrayInputStream(body);
Object result = new ObjectInputStream(byteStream).readObject();
assertEquals(LinkedHashMap.class, result.getClass());
Map<String, TestBean> resultMap = (Map<String, TestBean>) result;
assertEquals(2, resultMap.size());
assertEquals(TestBean.class, resultMap.get("A").getClass());
assertEquals(TestBean.class, resultMap.get("B").getClass());
}
@SuppressWarnings("serial")
private static class TestBean implements Serializable {
}
}

View File

@@ -0,0 +1,406 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.http;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.getCurrentArguments;
import static org.easymock.EasyMock.isA;
import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.reset;
import static org.easymock.classextension.EasyMock.verify;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.easymock.IAnswer;
import org.easymock.classextension.ConstructorArgs;
import org.junit.Before;
import org.junit.Test;
import org.springframework.integration.core.Message;
import org.springframework.integration.core.MessageChannel;
import org.springframework.integration.core.MessageHeaders;
import org.springframework.integration.message.StringMessage;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.util.MultiValueMap;
import org.springframework.web.servlet.View;
/**
* @author Alex Peters
*/
public class HttpInboundEndpointTests {
private static final String ANY_ENCODING = "UTF-8";
private static final String ANY_STRING_PAYLOAD = "any text content..blabla...bla.äöüßß߀€€€";
private static final byte[] ANY_BINARY_PAYLOAD;
private final MessageChannel requestChannel = createMock(MessageChannel.class);
private final MessageChannel replyChannel = createMock(MessageChannel.class);
private final Object[] allMocks = new Object[] { requestChannel, replyChannel };
private HttpInboundEndpoint endpoint;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
static {
try {
ANY_BINARY_PAYLOAD = "any binary content..blabla...bla.äöüßß߀€€€".getBytes(ANY_ENCODING);
}
catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
}
@Before
public void initializeSample() {
endpoint = new HttpInboundEndpoint();
endpoint.setRequestChannel(requestChannel);
endpoint.setReplyChannel(replyChannel);
endpoint.afterPropertiesSet();
reset(allMocks);
request = new MockHttpServletRequest("GET", "/anyurl");
response = new MockHttpServletResponse();
response.setCharacterEncoding(ANY_ENCODING);
}
@Test
public void handleRequest_withDefaultSettingsAndUnsupportedHTTPMethods_returns405()
throws ServletException, IOException {
String[] httpMethods = { "OPTIONS", "HEAD", "PUT", "DELETE", "TRACE", "CONNECT", "ANY_INVALID" };
for (String deniedHttpMethod : httpMethods) {
request = new MockHttpServletRequest(deniedHttpMethod, "/anyurl");
endpoint.handleRequest(request, response);
assertThat("Unexpected result for http method: " + deniedHttpMethod,
response.getStatus(),
is(HttpServletResponse.SC_METHOD_NOT_ALLOWED));
}
}
@Test
public void handleRequest_withGETRequest_allReqParametersInMessagePayload()
throws ServletException, IOException {
final Map<String, String> sourceParams = addAnyParametersToRequest();
expect(requestChannel.send(isA(Message.class))).andAnswer(
new IAnswer<Boolean>() {
@SuppressWarnings("unchecked")
public Boolean answer() throws Throwable {
final Map<?, ?> msgParams = (Map<?, ?>) ((Message) getCurrentArguments()[0]).getPayload();
assertThat(msgParams.size(), is(sourceParams.size()));
for (String key : sourceParams.keySet()) {
assertThat((List<String>) msgParams.get(key),
is(Collections.singletonList(sourceParams.get(key))));
}
return true;
}
});
replay(allMocks);
endpoint.handleRequest(request, response);
verify(allMocks);
}
@Test
public void handleRequest_withEmptyGETRequest_emptyMapIsInMessagePayload()
throws ServletException, IOException {
expect(requestChannel.send(isA(Message.class))).andAnswer(
new IAnswer<Boolean>() {
@SuppressWarnings("unchecked")
public Boolean answer() throws Throwable {
final Map<?, ?> msgParams = (Map<?, ?>) ((Message) getCurrentArguments()[0]).getPayload();
assertThat(msgParams.size(), is(0));
return true;
}
});
replay(allMocks);
endpoint.handleRequest(request, response);
verify(allMocks);
}
@Test
public void handleRequest_withCustomRequestMapper_requestObjectIsInPayload()
throws ServletException, IOException {
endpoint.setRequestMapper(new InboundRequestMapper() {
public Message<?> toMessage(HttpServletRequest request) throws Exception {
return new StringMessage(request.getRequestURI());
}
});
expect(requestChannel.send(isA(Message.class))).andAnswer(
new IAnswer<Boolean>() {
@SuppressWarnings("unchecked")
public Boolean answer() throws Throwable {
assertThat(((Message) getCurrentArguments()[0]).getPayload(), is((Object) "/anyurl"));
return true;
}
});
replay(allMocks);
endpoint.handleRequest(request, response);
verify(allMocks);
}
@Test
public void handleRequest_RequestHeadersInMsgHeaders()
throws ServletException, IOException {
final Principal anyPrincipal = createMock(Principal.class);
request.setUserPrincipal(anyPrincipal);
expect(requestChannel.send(isA(Message.class))).andAnswer(
new IAnswer<Boolean>() {
@SuppressWarnings("unchecked")
public Boolean answer() throws Throwable {
MessageHeaders headers = ((Message) getCurrentArguments()[0]).getHeaders();
assertThat(headers.get(HttpHeaders.REQUEST_METHOD),
is((Object) "GET"));
assertThat(headers.get(HttpHeaders.REQUEST_URL),
is((Object) "http://localhost:80/anyurl"));
assertThat(headers.get(HttpHeaders.USER_PRINCIPAL),
is((Object) anyPrincipal));
return true;
}
});
replay(allMocks);
endpoint.handleRequest(request, response);
verify(allMocks);
}
@Test
public void handleRequest_withPOSTRequestAndTextContent_sameInMessagePayload()
throws ServletException, IOException {
final String characterEncoding = ANY_ENCODING;
addRequestContent("POST", "text/plain", characterEncoding,
ANY_STRING_PAYLOAD.getBytes(characterEncoding));
expect(requestChannel.send(isA(Message.class))).andAnswer(
new IAnswer<Boolean>() {
@SuppressWarnings("unchecked")
public Boolean answer() throws Throwable {
assertThat((String) ((Message) getCurrentArguments()[0]).getPayload(),
is(ANY_STRING_PAYLOAD));
return true;
}
});
replay(allMocks);
endpoint.handleRequest(request, response);
verify(allMocks);
}
@Test
public void handleRequest_withPOSTRequestAndFormContent_sameInMessagePayload()
throws ServletException, IOException {
addRequestContent("POST", "application/x-www-form-urlencoded", ANY_ENCODING, new byte[0]);
final Map<String, String> sourceParams = addAnyParametersToRequest();
request.setParameters(sourceParams);
expect(requestChannel.send(isA(Message.class))).andAnswer(
new IAnswer<Boolean>() {
@SuppressWarnings("unchecked")
public Boolean answer() throws Throwable {
MultiValueMap<String, String> payloadMap = (MultiValueMap<String, String>)
((Message) getCurrentArguments()[0]).getPayload();
for (String key : sourceParams.keySet()) {
assertThat(payloadMap.get(key),
is(Collections.singletonList(sourceParams.get(key))));
}
return true;
}
});
replay(allMocks);
endpoint.handleRequest(request, response);
verify(allMocks);
}
@Test
public void handleRequest_withEmptyPOSTRequest_emptyStringAsPayload()
throws ServletException, IOException {
addRequestContent("POST", "text/plain", null, new byte[0]);
expect(requestChannel.send(isA(Message.class))).andAnswer(
new IAnswer<Boolean>() {
@SuppressWarnings("unchecked")
public Boolean answer() throws Throwable {
assertThat((String) ((Message) getCurrentArguments()[0]).getPayload(), is(""));
return true;
}
});
replay(allMocks);
endpoint.handleRequest(request, response);
verify(allMocks);
}
@Test
public void handleRequest_withPOSTRequestAndBinaryContent_sameInMessagePayload()
throws ServletException, IOException {
addRequestContent("POST", "", ANY_ENCODING, ANY_BINARY_PAYLOAD);
expect(requestChannel.send(isA(Message.class))).andAnswer(
new IAnswer<Boolean>() {
@SuppressWarnings("unchecked")
public Boolean answer() throws Throwable {
assertThat((byte[]) ((Message) getCurrentArguments()[0]).getPayload(),
is(ANY_BINARY_PAYLOAD));
return true;
}
});
replay(allMocks);
endpoint.handleRequest(request, response);
verify(allMocks);
}
@Test
public void handleRequest_withPOSTRequestEmptyContentLenght_return411()
throws ServletException, IOException {
addRequestContent("POST", "", ANY_ENCODING, null);
endpoint.handleRequest(request, response);
assertThat(response.getStatus(), is(HttpServletResponse.SC_LENGTH_REQUIRED));
}
@Test
public void handleRequest_withoutReplyMessage_return200()
throws ServletException, IOException {
expect(requestChannel.send(isA(Message.class))).andReturn(true);
replay(allMocks);
endpoint.handleRequest(request, response);
assertThat(response.getStatus(), is(HttpServletResponse.SC_OK));
}
@Test
public void handleRequest_replyWithTextPayload_textAsRespContent()
throws ServletException, IOException {
setupEndpointAsMock(ANY_STRING_PAYLOAD);
replay(allMocks);
endpoint.handleRequest(request, response);
assertThat(response.getContentAsString(), is(ANY_STRING_PAYLOAD));
verify(allMocks);
}
@Test
public void handleRequest_replyWithBytePayload_bytesAsRespContent()
throws ServletException, IOException {
setupEndpointAsMock(ANY_BINARY_PAYLOAD);
replay(allMocks);
endpoint.handleRequest(request, response);
assertThat(response.getContentAsByteArray(), is(ANY_BINARY_PAYLOAD));
verify(allMocks);
}
@Test
public void handleRequest_replyWithSerializablePayload_serializableAsRespContent()
throws ServletException, IOException, ClassNotFoundException {
Date obj = new Date();
setupEndpointAsMock(obj);
replay(allMocks);
endpoint.handleRequest(request, response);
byte[] content = response.getContentAsByteArray();
Object deserializedObj = new ObjectInputStream(
new ByteArrayInputStream(content)).readObject();
assertThat(deserializedObj, is(Date.class));
assertThat((Date) deserializedObj, is(obj));
verify(allMocks);
}
@Test(expected = ServletException.class)
public void handleRequest_replyWithNonSerializablePayload_exceptionThrown()
throws ServletException, IOException, ClassNotFoundException {
Object obj = new Object();
setupEndpointAsMock(obj);
replay(allMocks);
endpoint.handleRequest(request, response);
verify(allMocks);
}
@Test
@SuppressWarnings("unchecked")
public void handleRequest_expectReplyWithView_responseDirectedToView() throws Exception {
setupEndpointAsMock(ANY_STRING_PAYLOAD);
View view = createMock(View.class);
view.render(isA(Map.class), eq(request), eq(response));
expectLastCall().andAnswer(new IAnswer<Object>() {
public Object answer() throws Throwable {
Map<?, ?> model = (Map<?, ?>) getCurrentArguments()[0];
assertThat(model.isEmpty(), is(false));
assertThat(model.get("reply"), is((Object) ANY_STRING_PAYLOAD));
assertThat(model.get("requestMessage"), is(notNullValue()));
return null;
}
});
endpoint.setView(view);
replay(view);
replay(allMocks);
endpoint.handleRequest(request, response);
verify(allMocks);
verify(view);
}
/** add some dummy parameters to the request */
private Map<String, String> addAnyParametersToRequest() {
final Map<String, String> sourceParams = new HashMap<String, String>();
for (int i = 0; i < 20; i++) {
sourceParams.put("anyParameter" + i, "anyValue" + i);
}
request.setParameters(sourceParams);
return sourceParams;
}
/** set given params on request instance */
private void addRequestContent(String httpMethod, String contentType, String encoding, byte[] content) {
request.setMethod(httpMethod);
request.setContentType(contentType);
request.setContent(content);
request.setCharacterEncoding(encoding);
}
/** create a new mocked endpoint instance and setup basic data */
private void setupEndpointAsMock(final Object anyPayload) {
try {
endpoint = createMock(HttpInboundEndpoint.class,
new ConstructorArgs(
HttpInboundEndpoint.class.getConstructor(new Class[0]),
new Object[0]),
HttpInboundEndpoint.class.getMethod("sendAndReceive", Object.class));
endpoint.afterPropertiesSet();
}
catch (Exception e) {
throw new IllegalStateException(e);
}
expect(endpoint.sendAndReceive(anyObject())).andReturn(anyPayload);
endpoint.setExpectReply(true);
replay(endpoint);
}
}

View File

@@ -0,0 +1,94 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.http;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.web.multipart.MultipartFile;
/**
* @author Mark Fisher
*/
public class StubMultipartFile implements MultipartFile {
private final String parameterName;
private final String filename;
private final byte[] bytes;
private final String text;
public StubMultipartFile(String parameterName, String filename, String text) {
this.parameterName = parameterName;
this.filename = filename;
if (text != null) {
this.bytes = text.getBytes();
}
else {
this.bytes = null;
}
this.text = text;
}
public StubMultipartFile(String parameterName, String filename, byte[] bytes) {
this.parameterName = parameterName;
this.filename = filename;
this.bytes = bytes;
this.text = null;
}
public byte[] getBytes() throws IOException {
return this.bytes;
}
public String getContentType() {
return (this.text != null) ? "text" : null;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(this.bytes);
}
public String getName() {
return this.parameterName;
}
public String getOriginalFilename() {
return this.filename;
}
public long getSize() {
return this.bytes.length;
}
public boolean isEmpty() {
return this.bytes == null || this.bytes.length == 0;
}
public void transferTo(File dest) throws IOException, IllegalStateException {
FileOutputStream fos = new FileOutputStream(dest);
fos.write(this.bytes);
fos.close();
}
}

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:http="http://www.springframework.org/schema/integration/http"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration/http
http://www.springframework.org/schema/integration/http/spring-integration-http.xsd">
<http:outbound-gateway request-channel="testChannel" auto-startup="false"/>
</beans>

View File

@@ -0,0 +1,72 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.http.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.integration.channel.MessagePublishingErrorHandler;
import org.springframework.integration.channel.NullChannel;
import org.springframework.integration.channel.PublishSubscribeChannel;
import org.springframework.integration.context.IntegrationContextUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Mark Fisher
* @since 1.0.3
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class DefaultConfigurationTests {
@Autowired
private ApplicationContext context;
@Test
public void verifyErrorChannel() {
Object errorChannel = context.getBean("errorChannel");
assertNotNull(errorChannel);
assertEquals(PublishSubscribeChannel.class, errorChannel.getClass());
}
@Test
public void verifyNullChannel() {
Object nullChannel = context.getBean("nullChannel");
assertNotNull(nullChannel);
assertEquals(NullChannel.class, nullChannel.getClass());
}
@Test
public void verifyTaskScheduler() {
Object taskScheduler = context.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME);
assertEquals(ThreadPoolTaskScheduler.class, taskScheduler.getClass());
Object errorHandler = new DirectFieldAccessor(taskScheduler).getPropertyValue("errorHandler");
assertEquals(MessagePublishingErrorHandler.class, errorHandler.getClass());
Object defaultErrorChannel = new DirectFieldAccessor(errorHandler).getPropertyValue("defaultErrorChannel");
assertEquals(context.getBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME), defaultErrorChannel);
}
}

View File

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration/http"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:si="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/http
http://www.springframework.org/schema/integration/http/spring-integration-http.xsd">
<si:channel id="requests">
<si:queue capacity="1"/>
</si:channel>
<inbound-channel-adapter id="defaultAdapter" channel="requests"/>
<inbound-channel-adapter id="postOnlyAdapter" channel="requests" supported-methods="POST"/>
<inbound-channel-adapter id="putOrDeleteAdapter" channel="requests" supported-methods="PUT, delete"/>
</beans:beans>

View File

@@ -0,0 +1,151 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.http.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.channel.PollableChannel;
import org.springframework.integration.core.Message;
import org.springframework.integration.http.HttpInboundEndpoint;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.MultiValueMap;
/**
* @author Mark Fisher
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class HttpInboundChannelAdapterParserTests {
@Autowired @Qualifier("requests")
private PollableChannel requests;
@Autowired @Qualifier("defaultAdapter")
private HttpInboundEndpoint defaultAdapter;
@Autowired @Qualifier("postOnlyAdapter")
private HttpInboundEndpoint postOnlyAdapter;
@Autowired @Qualifier("putOrDeleteAdapter")
private HttpInboundEndpoint putOrDeleteAdapter;
@Test
@SuppressWarnings("unchecked")
public void getRequestOk() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("GET");
request.setParameter("foo", "bar");
MockHttpServletResponse response = new MockHttpServletResponse();
defaultAdapter.handleRequest(request, response);
assertEquals(HttpServletResponse.SC_OK, response.getStatus());
Message<?> message = requests.receive(0);
assertNotNull(message);
Object payload = message.getPayload();
assertTrue(payload instanceof MultiValueMap);
MultiValueMap<String, String> map = (MultiValueMap<String, String>) payload;
assertEquals(1, map.size());
assertEquals("foo", map.keySet().iterator().next());
assertEquals(1, map.get("foo").size());
assertEquals("bar", map.getFirst("foo"));
}
@Test
public void getRequestNotAllowed() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("GET");
request.setParameter("foo", "bar");
MockHttpServletResponse response = new MockHttpServletResponse();
postOnlyAdapter.handleRequest(request, response);
assertEquals(HttpServletResponse.SC_METHOD_NOT_ALLOWED, response.getStatus());
Message<?> message = requests.receive(0);
assertNull(message);
}
@Test
public void postRequestWithTextContentOk() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("POST");
request.setContent("test".getBytes());
request.setContentType("text/plain");
MockHttpServletResponse response = new MockHttpServletResponse();
postOnlyAdapter.handleRequest(request, response);
assertEquals(HttpServletResponse.SC_OK, response.getStatus());
Message<?> message = requests.receive(0);
assertNotNull(message);
assertEquals("test", message.getPayload());
}
@Test
public void postRequestWithSerializedObjectContentOk() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("POST");
Object obj = new TestObject("testObject");
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
new ObjectOutputStream(byteStream).writeObject(obj);
request.setContent(byteStream.toByteArray());
request.setContentType("application/x-java-serialized-object");
MockHttpServletResponse response = new MockHttpServletResponse();
postOnlyAdapter.handleRequest(request, response);
assertEquals(HttpServletResponse.SC_OK, response.getStatus());
Message<?> message = requests.receive(0);
assertNotNull(message);
assertTrue(message.getPayload() instanceof TestObject);
assertEquals("testObject", ((TestObject) message.getPayload()).text);
}
@Test
@SuppressWarnings("unchecked")
public void putOrDeleteMethodsSupported() throws Exception {
DirectFieldAccessor accessor = new DirectFieldAccessor(putOrDeleteAdapter);
List<String> supportedMethods = (List<String>) accessor.getPropertyValue("supportedMethods");
assertEquals(2, supportedMethods.size());
assertTrue(supportedMethods.contains("PUT"));
assertTrue(supportedMethods.contains("DELETE"));
}
@SuppressWarnings("serial")
private static class TestObject implements Serializable {
String text;
TestObject(String text) {
this.text = text;
}
}
}

View File

@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration/http"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:si="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/http
http://www.springframework.org/schema/integration/http/spring-integration-http.xsd">
<si:publish-subscribe-channel id="requests"/>
<si:bridge output-channel="responses" input-channel="requests"/>
<si:channel id="responses"/>
<inbound-gateway id="inboundGateway" request-channel="requests"
reply-channel="responses" />
</beans:beans>

View File

@@ -0,0 +1,76 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.http.config;
import static org.hamcrest.CoreMatchers.any;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.channel.SubscribableChannel;
import org.springframework.integration.core.Message;
import org.springframework.integration.core.MessageChannel;
import org.springframework.integration.http.HttpInboundEndpoint;
import static org.springframework.integration.test.util.TestUtils.getPropertyValue;
import static org.springframework.integration.test.util.TestUtils.handlerExpecting;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.servlet.http.HttpServletResponse;
/**
* @author Mark Fisher
* @author Iwein Fuld
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class HttpInboundGatewayParserTests {
@Autowired
private HttpInboundEndpoint gateway;
@Qualifier("responses")
@Autowired
MessageChannel responses;
@Qualifier("requests")
@Autowired
SubscribableChannel requests;
@Test
public void checkConfig() {
assertNotNull(gateway);
assertThat((Boolean) getPropertyValue(gateway, "expectReply"), is(true));
}
@Test(timeout=1000)
public void checkFlow() throws Exception {
requests.subscribe(handlerExpecting(any(Message.class)));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("GET");
request.setParameter("foo", "bar");
MockHttpServletResponse response = new MockHttpServletResponse();
gateway.handleRequest(request, response);
assertThat(response.getStatus(), is(HttpServletResponse.SC_OK));
assertThat(response.getContentType(), is("application/x-java-serialized-object"));
}
}

View File

@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration/http"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:si="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/http
http://www.springframework.org/schema/integration/http/spring-integration-http.xsd">
<si:channel id="requests"/>
<outbound-gateway id="minimalConfig" request-channel="requests"/>
<si:channel id="replies">
<si:queue/>
</si:channel>
<outbound-gateway id="fullConfigWithMapper"
request-channel="requests"
request-mapper="mapper"
request-executor="executor"
request-timeout="1234"
reply-channel="replies"
order="77"
auto-startup="false"/>
<outbound-gateway id="fullConfigWithoutMapper"
request-channel="requests"
default-url="http://localhost/test"
extract-request-payload="false"
charset="UTF-8"
request-executor="executor"
request-timeout="1234"
reply-channel="replies"/>
<beans:bean id="mapper" class="org.springframework.integration.http.DefaultOutboundRequestMapper">
<beans:property name="defaultUrl" value="http://localhost/test"/>
<beans:property name="charset" value="UTF-8"/>
<beans:property name="extractPayload" value="false"/>
</beans:bean>
<beans:bean id="executor" class="org.springframework.integration.http.SimpleHttpRequestExecutor"/>
</beans:beans>

View File

@@ -0,0 +1,144 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.http.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URL;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.integration.core.MessageChannel;
import org.springframework.integration.endpoint.AbstractEndpoint;
import org.springframework.integration.http.DefaultOutboundRequestMapper;
import org.springframework.integration.http.HttpOutboundEndpoint;
import org.springframework.integration.http.HttpRequestExecutor;
import org.springframework.integration.http.OutboundRequestMapper;
import org.springframework.integration.http.SimpleHttpRequestExecutor;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Mark Fisher
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class HttpOutboundGatewayParserTests {
@Autowired @Qualifier("minimalConfig")
private AbstractEndpoint minimalConfigEndpoint;
@Autowired @Qualifier("fullConfigWithMapper")
private AbstractEndpoint fullConfigWithMapperEndpoint;
@Autowired @Qualifier("fullConfigWithoutMapper")
private AbstractEndpoint fullConfigWithoutMapperEndpoint;
@Autowired
private ApplicationContext applicationContext;
@Test
public void minimalConfig() {
HttpOutboundEndpoint gateway = (HttpOutboundEndpoint) new DirectFieldAccessor(
this.minimalConfigEndpoint).getPropertyValue("handler");
MessageChannel requestChannel = (MessageChannel) new DirectFieldAccessor(
this.minimalConfigEndpoint).getPropertyValue("inputChannel");
assertEquals(this.applicationContext.getBean("requests"), requestChannel);
DirectFieldAccessor accessor = new DirectFieldAccessor(gateway);
Object replyChannel = accessor.getPropertyValue("outputChannel");
assertNull(replyChannel);
OutboundRequestMapper mapper = (OutboundRequestMapper) accessor.getPropertyValue("requestMapper");
HttpRequestExecutor executor = (HttpRequestExecutor) accessor.getPropertyValue("requestExecutor");
assertTrue(mapper instanceof DefaultOutboundRequestMapper);
assertTrue(executor instanceof SimpleHttpRequestExecutor);
Object mapperBean = this.applicationContext.getBean("mapper");
assertNotSame(mapperBean, mapper);
DirectFieldAccessor mapperAccessor = new DirectFieldAccessor(mapper);
assertNull(mapperAccessor.getPropertyValue("defaultUrl"));
assertEquals("UTF-8", mapperAccessor.getPropertyValue("charset"));
assertEquals(true, mapperAccessor.getPropertyValue("extractPayload"));
}
@Test
public void fullConfigWithMapper() throws Exception {
DirectFieldAccessor endpointAccessor = new DirectFieldAccessor(this.fullConfigWithMapperEndpoint);
HttpOutboundEndpoint gateway = (HttpOutboundEndpoint) endpointAccessor.getPropertyValue("handler");
MessageChannel requestChannel = (MessageChannel) new DirectFieldAccessor(
this.fullConfigWithMapperEndpoint).getPropertyValue("inputChannel");
assertEquals(this.applicationContext.getBean("requests"), requestChannel);
DirectFieldAccessor accessor = new DirectFieldAccessor(gateway);
assertEquals(77, accessor.getPropertyValue("order"));
assertEquals(Boolean.FALSE, endpointAccessor.getPropertyValue("autoStartup"));
Object replyChannel = accessor.getPropertyValue("outputChannel");
assertNotNull(replyChannel);
assertEquals(this.applicationContext.getBean("replies"), replyChannel);
OutboundRequestMapper mapper = (OutboundRequestMapper) accessor.getPropertyValue("requestMapper");
HttpRequestExecutor executor = (HttpRequestExecutor) accessor.getPropertyValue("requestExecutor");
assertTrue(mapper instanceof DefaultOutboundRequestMapper);
assertTrue(executor instanceof SimpleHttpRequestExecutor);
Object mapperBean = this.applicationContext.getBean("mapper");
assertEquals(mapperBean, mapper);
DirectFieldAccessor mapperAccessor = new DirectFieldAccessor(mapper);
assertEquals(new URL("http://localhost/test"), mapperAccessor.getPropertyValue("defaultUrl"));
assertEquals("UTF-8", mapperAccessor.getPropertyValue("charset"));
assertEquals(false, mapperAccessor.getPropertyValue("extractPayload"));
Object executorBean = this.applicationContext.getBean("executor");
assertEquals(executorBean, executor);
Object sendTimeout = new DirectFieldAccessor(
accessor.getPropertyValue("channelTemplate")).getPropertyValue("sendTimeout");
assertEquals(new Long("1234"), sendTimeout);
}
@Test
public void fullConfigWithoutMapper() throws Exception {
HttpOutboundEndpoint gateway = (HttpOutboundEndpoint) new DirectFieldAccessor(
this.fullConfigWithoutMapperEndpoint).getPropertyValue("handler");
MessageChannel requestChannel = (MessageChannel) new DirectFieldAccessor(
this.fullConfigWithoutMapperEndpoint).getPropertyValue("inputChannel");
assertEquals(this.applicationContext.getBean("requests"), requestChannel);
DirectFieldAccessor accessor = new DirectFieldAccessor(gateway);
Object replyChannel = accessor.getPropertyValue("outputChannel");
assertNotNull(replyChannel);
assertEquals(this.applicationContext.getBean("replies"), replyChannel);
OutboundRequestMapper mapper = (OutboundRequestMapper) accessor.getPropertyValue("requestMapper");
HttpRequestExecutor executor = (HttpRequestExecutor) accessor.getPropertyValue("requestExecutor");
assertTrue(mapper instanceof DefaultOutboundRequestMapper);
assertTrue(executor instanceof SimpleHttpRequestExecutor);
Object mapperBean = this.applicationContext.getBean("mapper");
assertNotSame(mapperBean, mapper);
DirectFieldAccessor mapperAccessor = new DirectFieldAccessor(mapper);
assertEquals(new URL("http://localhost/test"), mapperAccessor.getPropertyValue("defaultUrl"));
assertEquals("UTF-8", mapperAccessor.getPropertyValue("charset"));
assertEquals(false, mapperAccessor.getPropertyValue("extractPayload"));
Object executorBean = this.applicationContext.getBean("executor");
assertEquals(executorBean, executor);
Object sendTimeout = new DirectFieldAccessor(
accessor.getPropertyValue("channelTemplate")).getPropertyValue("sendTimeout");
assertEquals(new Long("1234"), sendTimeout);
}
}

View File

@@ -0,0 +1,102 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.http.mapper;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.integration.core.Message;
import org.springframework.integration.http.DataBindingInboundRequestMapper;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
/**
* @author Mark Fisher
*/
public class DataBindingInboundRequestMapperTests {
@Test
public void bindToType() throws Exception {
DataBindingInboundRequestMapper mapper = new DataBindingInboundRequestMapper(TestBean.class);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("name", "testBean");
request.setParameter("age", "42");
Message<?> result = mapper.toMessage(request);
assertNotNull(result);
assertEquals(TestBean.class, result.getPayload().getClass());
TestBean payload = (TestBean) result.getPayload();
assertEquals("testBean", payload.name);
assertEquals(84, payload.age);
}
@Test
public void bindToTypeWithBindingInitializer() throws Exception {
DataBindingInboundRequestMapper mapper = new DataBindingInboundRequestMapper(TestBean.class);
ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
initializer.setDirectFieldAccess(true);
mapper.setWebBindingInitializer(initializer);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("name", "testBean");
request.setParameter("age", "42");
Message<?> result = mapper.toMessage(request);
assertNotNull(result);
assertEquals(TestBean.class, result.getPayload().getClass());
TestBean payload = (TestBean) result.getPayload();
assertEquals("testBean", payload.name);
assertEquals(42, payload.age);
}
@Test
public void bindToPrototypeBean() throws Exception {
StaticApplicationContext context = new StaticApplicationContext();
MutablePropertyValues properties = new MutablePropertyValues();
properties.addPropertyValue("name", "prototype");
context.registerPrototype("prototypeTarget", TestBean.class, properties);
DataBindingInboundRequestMapper mapper = new DataBindingInboundRequestMapper(TestBean.class);
mapper.setTargetBeanName("prototypeTarget");
mapper.setBeanFactory(context);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("age", "42");
Message<?> result = mapper.toMessage(request);
assertNotNull(result);
assertEquals(TestBean.class, result.getPayload().getClass());
TestBean payload = (TestBean) result.getPayload();
assertEquals("prototype", payload.name);
assertEquals(84, payload.age);
}
public static class TestBean {
String name;
int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age * 2;
}
}
}