WW-4835 Allows REST handlers to be configurable per action

This commit is contained in:
Lukasz Lenart
2017-08-03 16:04:53 +02:00
18 changed files with 143 additions and 43 deletions
@@ -21,6 +21,7 @@
package org.apache.struts2.rest;
import com.opensymphony.xwork2.ActionInvocation;
import org.apache.struts2.rest.handler.ContentTypeHandler;
import javax.servlet.http.HttpServletRequest;
@@ -59,10 +60,16 @@ public interface ContentTypeHandlerManager {
* @param target The object to return, usually the action object
* @return The new result code to process
* @throws IOException If unable to write to the response
*
* @deprecated use version which requires {@link ActionInvocation}
*/
@Deprecated
String handleResult(ActionConfig actionConfig, Object methodResult, Object target)
throws IOException;
String handleResult(ActionInvocation actionInvocation, Object methodResult, Object target)
throws IOException;
/**
* Finds the extension in the url
*
@@ -57,7 +57,7 @@ public class ContentTypeInterceptor extends AbstractInterceptor {
if (request.getContentLength() > 0) {
InputStream is = request.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
handler.toObject(reader, target);
handler.toObject(invocation, reader, target);
}
return invocation.invoke();
}
@@ -21,9 +21,12 @@
package org.apache.struts2.rest;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.rest.handler.ContentTypeHandler;
@@ -41,6 +44,8 @@ import java.util.Set;
*/
public class DefaultContentTypeHandlerManager implements ContentTypeHandlerManager {
private static final Logger LOG = LogManager.getLogger(DefaultContentTypeHandlerManager.class);
/** ContentTypeHandlers keyed by the extension */
Map<String, ContentTypeHandler> handlersByExtension = new HashMap<String, ContentTypeHandler>();
/** ContentTypeHandlers keyed by the content-type */
@@ -115,7 +120,7 @@ public class DefaultContentTypeHandlerManager implements ContentTypeHandlerManag
/**
* Gets the handler for the response by looking at the extension of the request
* @param req The request
* @param request The request
* @return The appropriate handler
*
* WW-4588: modified to get a handler for the response side and auto generate the response type
@@ -153,20 +158,28 @@ public class DefaultContentTypeHandlerManager implements ContentTypeHandlerManag
return handler;
}
@Override
public String handleResult(ActionConfig actionConfig, Object methodResult, Object target) throws IOException {
LOG.warn("This method is deprecated!");
return readResultCode(methodResult);
}
/**
* Handles the result using handlers to generate content type-specific content
*
* @param actionConfig The action config for the current request
* @param invocation The action invocation for the current request
* @param methodResult The object returned from the action method
* @param target The object to return, usually the action object
* @return The new result code to process
* @throws IOException If unable to write to the response
*/
public String handleResult(ActionConfig actionConfig, Object methodResult, Object target) throws IOException {
public String handleResult(ActionInvocation invocation, Object methodResult, Object target) throws IOException {
String resultCode = readResultCode(methodResult);
Integer statusCode = readStatusCode(methodResult);
HttpServletRequest req = ServletActionContext.getRequest();
HttpServletResponse res = ServletActionContext.getResponse();
ActionConfig actionConfig = invocation.getProxy().getConfig();
if(statusCode != null) {
res.setStatus(statusCode);
}
@@ -178,7 +191,7 @@ public class DefaultContentTypeHandlerManager implements ContentTypeHandlerManag
resultCode = extCode;
} else {
StringWriter writer = new StringWriter();
resultCode = handler.fromObject(target, resultCode, writer);
resultCode = handler.fromObject(invocation, target, resultCode, writer);
String text = writer.toString();
if (text.length() > 0) {
byte[] data = text.getBytes("UTF-8");
@@ -224,7 +224,7 @@ public class RestActionInvocation extends DefaultActionInvocation {
if (handler != null && !(handler instanceof HtmlHandler)) {
// Specific representation (json, xml...)
resultCode = handlerSelector.handleResult(this.getProxy().getConfig(), httpHeaders, target);
resultCode = handlerSelector.handleResult(this, httpHeaders, target);
} else {
// Normal struts execution (html o other struts result)
findResult();
@@ -221,7 +221,7 @@ public class RestWorkflowInterceptor extends MethodFilterInterceptor {
errors.put("actionErrors", validationAwareAction.getActionErrors());
errors.put("fieldErrors", validationAwareAction.getFieldErrors());
return manager.handleResult(invocation.getProxy().getConfig(), info, errors);
return manager.handleResult(invocation, info, errors);
}
}
@@ -0,0 +1,44 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.struts2.rest.handler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
abstract public class AbstractContentTypeHandler implements ContentTypeHandler {
private static final Logger LOG = LogManager.getLogger(AbstractContentTypeHandler.class);
@Override
public void toObject(Reader in, Object target) throws IOException {
LOG.warn("This method is deprecated!");
}
@Override
public String fromObject(Object obj, String resultCode, Writer stream) throws IOException {
LOG.warn("This method is deprecated!");
return null;
}
}
@@ -21,6 +21,8 @@
package org.apache.struts2.rest.handler;
import com.opensymphony.xwork2.ActionInvocation;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
@@ -35,9 +37,14 @@ public interface ContentTypeHandler {
* @param in The input stream, usually the body of the request
* @param target The target, usually the action class
* @throws IOException If unable to write to the output stream
*
* @deprecated use version which requires {@link ActionInvocation}
*/
@Deprecated
void toObject(Reader in, Object target) throws IOException;
void toObject(ActionInvocation invocation, Reader in, Object target) throws IOException;
/**
* Writes content to the stream
*
@@ -46,9 +53,14 @@ public interface ContentTypeHandler {
* @param stream The output stream, usually the response
* @return The new result code
* @throws IOException If unable to write to the output stream
*
* @deprecated use version which requires {@link ActionInvocation}
*/
@Deprecated
String fromObject(Object obj, String resultCode, Writer stream) throws IOException;
String fromObject(ActionInvocation invocation, Object obj, String resultCode, Writer stream) throws IOException;
/**
* Gets the content type for this handler
*
@@ -20,6 +20,8 @@
*/
package org.apache.struts2.rest.handler;
import com.opensymphony.xwork2.ActionInvocation;
import java.io.Writer;
import java.io.IOException;
import java.io.Reader;
@@ -34,11 +36,11 @@ import java.io.Reader;
* @see <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4">http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4</a>
*
*/
public class FormUrlEncodedHandler implements ContentTypeHandler {
public class FormUrlEncodedHandler extends AbstractContentTypeHandler {
public static final String CONTENT_TYPE = "application/x-www-form-urlencoded";
public String fromObject(Object obj, String resultCode, Writer out) throws IOException {
public String fromObject(ActionInvocation invocation, Object obj, String resultCode, Writer out) throws IOException {
throw new IOException("Conversion from Object to '"+getContentType()+"' is not supported");
}
@@ -48,7 +50,7 @@ public class FormUrlEncodedHandler implements ContentTypeHandler {
* @param in The input stream, usually the body of the request
* @param target The target, usually the action class
*/
public void toObject(Reader in, Object target) {
public void toObject(ActionInvocation invocation, Reader in, Object target) {
}
/**
@@ -21,6 +21,8 @@
package org.apache.struts2.rest.handler;
import com.opensymphony.xwork2.ActionInvocation;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
@@ -28,13 +30,13 @@ import java.io.Writer;
/**
* Handles HTML content, usually just a simple passthrough to the framework
*/
public class HtmlHandler implements ContentTypeHandler {
public class HtmlHandler extends AbstractContentTypeHandler {
public String fromObject(Object obj, String resultCode, Writer out) throws IOException {
public String fromObject(ActionInvocation invocation, Object obj, String resultCode, Writer out) throws IOException {
return resultCode;
}
public void toObject(Reader in, Object target) {
public void toObject(ActionInvocation invocation, Reader in, Object target) {
}
public String getExtension() {
@@ -24,6 +24,7 @@ package org.apache.struts2.rest.handler;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.inject.Inject;
import org.apache.struts2.StrutsConstants;
@@ -34,19 +35,19 @@ import java.io.Writer;
/**
* Handles JSON content using jackson-lib
*/
public class JacksonLibHandler implements ContentTypeHandler {
public class JacksonLibHandler extends AbstractContentTypeHandler {
private static final String DEFAULT_CONTENT_TYPE = "application/json";
private String defaultEncoding = "ISO-8859-1";
private ObjectMapper mapper = new ObjectMapper();
public void toObject(Reader in, Object target) throws IOException {
public void toObject(ActionInvocation invocation, Reader in, Object target) throws IOException {
mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
ObjectReader or = mapper.readerForUpdating(target);
or.readValue(in);
}
public String fromObject(Object obj, String resultCode, Writer stream) throws IOException {
public String fromObject(ActionInvocation invocation, Object obj, String resultCode, Writer stream) throws IOException {
mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
mapper.writeValue(stream, obj);
return null;
@@ -26,6 +26,7 @@ import java.io.Reader;
import java.io.Writer;
import java.util.Collection;
import com.opensymphony.xwork2.ActionInvocation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
@@ -37,12 +38,12 @@ import com.opensymphony.xwork2.inject.Inject;
/**
* Handles JSON content using json-lib
*/
public class JsonLibHandler implements ContentTypeHandler {
public class JsonLibHandler extends AbstractContentTypeHandler {
private static final String DEFAULT_CONTENT_TYPE = "application/json";
private String defaultEncoding = "ISO-8859-1";
public void toObject(Reader in, Object target) throws IOException {
public void toObject(ActionInvocation invocation, Reader in, Object target) throws IOException {
StringBuilder sb = new StringBuilder();
char[] buffer = new char[1024];
int len = 0;
@@ -63,7 +64,7 @@ public class JsonLibHandler implements ContentTypeHandler {
}
}
public String fromObject(Object obj, String resultCode, Writer stream) throws IOException {
public String fromObject(ActionInvocation invocation, Object obj, String resultCode, Writer stream) throws IOException {
if (obj != null) {
if (isArray(obj)) {
JSONArray jsonArray = JSONArray.fromObject(obj);
@@ -20,6 +20,8 @@
*/
package org.apache.struts2.rest.handler;
import com.opensymphony.xwork2.ActionInvocation;
import java.io.Writer;
import java.io.IOException;
import java.io.Reader;
@@ -34,11 +36,11 @@ import java.io.Reader;
*
* @see <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4">http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4</a>
*/
public class MultipartFormDataHandler implements ContentTypeHandler {
public class MultipartFormDataHandler extends AbstractContentTypeHandler {
public static final String CONTENT_TYPE = "multipart/form-data";
public String fromObject(Object obj, String resultCode, Writer out) throws IOException {
public String fromObject(ActionInvocation invocation, Object obj, String resultCode, Writer out) throws IOException {
throw new IOException("Conversion from Object to '"+getContentType()+"' is not supported");
}
@@ -48,7 +50,7 @@ public class MultipartFormDataHandler implements ContentTypeHandler {
* @param in The input stream, usually the body of the request
* @param target The target, usually the action class
*/
public void toObject(Reader in, Object target) {
public void toObject(ActionInvocation invocation, Reader in, Object target) {
}
/**
@@ -21,6 +21,7 @@
package org.apache.struts2.rest.handler;
import com.opensymphony.xwork2.ActionInvocation;
import com.thoughtworks.xstream.XStream;
import java.io.IOException;
@@ -30,9 +31,9 @@ import java.io.Writer;
/**
* Handles XML content
*/
public class XStreamHandler implements ContentTypeHandler {
public class XStreamHandler extends AbstractContentTypeHandler {
public String fromObject(Object obj, String resultCode, Writer out) throws IOException {
public String fromObject(ActionInvocation invocation, Object obj, String resultCode, Writer out) throws IOException {
if (obj != null) {
XStream xstream = createXStream();
xstream.toXML(obj, out);
@@ -40,7 +41,7 @@ public class XStreamHandler implements ContentTypeHandler {
return null;
}
public void toObject(Reader in, Object target) {
public void toObject(ActionInvocation invocation, Reader in, Object target) {
XStream xstream = createXStream();
xstream.fromXML(in, target);
}
@@ -24,10 +24,14 @@ package org.apache.struts2.rest;
import com.mockobjects.dynamic.C;
import com.mockobjects.dynamic.Mock;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.mock.MockActionInvocation;
import com.opensymphony.xwork2.mock.MockActionProxy;
import junit.framework.TestCase;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.rest.handler.AbstractContentTypeHandler;
import org.apache.struts2.rest.handler.ContentTypeHandler;
import org.apache.struts2.rest.handler.FormUrlEncodedHandler;
import org.springframework.mock.web.MockHttpServletRequest;
@@ -49,6 +53,7 @@ public class ContentTypeHandlerManagerTest extends TestCase {
private DefaultContentTypeHandlerManager mgr;
private MockHttpServletResponse mockResponse;
private MockHttpServletRequest mockRequest;
private MockActionInvocation invocation;
@Override
public void setUp() {
@@ -59,6 +64,9 @@ public class ContentTypeHandlerManagerTest extends TestCase {
ActionContext.setContext(new ActionContext(new HashMap()));
ServletActionContext.setRequest(mockRequest);
ServletActionContext.setResponse(mockResponse);
invocation = new MockActionInvocation();
invocation.setProxy(new MockActionProxy());
}
@Override
@@ -71,9 +79,9 @@ public class ContentTypeHandlerManagerTest extends TestCase {
public void testHandleResultOK() throws IOException {
String obj = "mystring";
ContentTypeHandler handler = new ContentTypeHandler() {
public void toObject(Reader in, Object target) {}
public String fromObject(Object obj, String resultCode, Writer stream) throws IOException {
ContentTypeHandler handler = new AbstractContentTypeHandler() {
public void toObject(ActionInvocation invocation, Reader in, Object target) {}
public String fromObject(ActionInvocation invocation, Object obj, String resultCode, Writer stream) throws IOException {
stream.write(obj.toString());
return resultCode;
}
@@ -82,7 +90,11 @@ public class ContentTypeHandlerManagerTest extends TestCase {
};
mgr.handlersByExtension.put("xml", handler);
mgr.setDefaultExtension("xml");
mgr.handleResult(new ActionConfig.Builder("", "", "").build(), new DefaultHttpHeaders().withStatus(SC_OK), obj);
ActionConfig actionConfig = new ActionConfig.Builder("", "", "").build();
MockActionProxy proxy = new MockActionProxy();
proxy.setConfig(actionConfig);
invocation.setProxy(proxy);
mgr.handleResult(invocation, new DefaultHttpHeaders().withStatus(SC_OK), obj);
assertEquals(obj.getBytes().length, mockResponse.getContentLength());
}
@@ -92,7 +104,7 @@ public class ContentTypeHandlerManagerTest extends TestCase {
Mock mockHandlerXml = new Mock(ContentTypeHandler.class);
mockHandlerXml.matchAndReturn("getExtension", "xml");
mgr.handlersByExtension.put("xml", (ContentTypeHandler) mockHandlerXml.proxy());
mgr.handleResult(null, new DefaultHttpHeaders().withStatus(SC_NOT_MODIFIED), new Object());
mgr.handleResult(invocation, new DefaultHttpHeaders().withStatus(SC_NOT_MODIFIED), new Object());
assertEquals(0, mockResponse.getContentLength());
}
@@ -1,8 +1,10 @@
package org.apache.struts2.rest;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Scope;
import org.apache.struts2.rest.handler.AbstractContentTypeHandler;
import org.apache.struts2.rest.handler.ContentTypeHandler;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -113,13 +115,13 @@ class DummyContainer implements Container {
private ContentTypeHandler handler;
DummyContainer(final String contentType, final String extension) {
handler = new ContentTypeHandler() {
handler = new AbstractContentTypeHandler() {
public void toObject(Reader in, Object target) throws IOException {
public void toObject(ActionInvocation invocation, Reader in, Object target) throws IOException {
}
public String fromObject(Object obj, String resultCode, Writer stream) throws IOException {
public String fromObject(ActionInvocation invocation, Object obj, String resultCode, Writer stream) throws IOException {
return null;
}
@@ -44,7 +44,6 @@ public class RestWorkflowInterceptorTest extends TestCase {
Mock mockActionInvocation = new Mock(ActionInvocation.class);
Mock mockActionProxy = new Mock(ActionProxy.class);
mockActionProxy.expectAndReturn("getConfig", null);
mockActionInvocation.expectAndReturn("getProxy", mockActionProxy.proxy());
mockActionInvocation.expectAndReturn("getAction", action);
Mock mockContentTypeHandlerManager = new Mock(ContentTypeHandlerManager.class);
mockContentTypeHandlerManager.expectAndReturn("handleResult", new AnyConstraintMatcher() {
@@ -21,6 +21,7 @@
package org.apache.struts2.rest.handler;
import com.opensymphony.xwork2.mock.MockActionInvocation;
import junit.framework.TestCase;
import java.io.IOException;
@@ -37,7 +38,7 @@ public class JacksonLibHandlerTest extends TestCase {
StringWriter writer = new StringWriter();
JacksonLibHandler handler = new JacksonLibHandler();
handler.fromObject(contact, "success", writer);
handler.fromObject(new MockActionInvocation(), contact, "success", writer);
String data = writer.toString();
assertTrue(data.startsWith("{"));
assertTrue(data.contains("\"age\":44"));
@@ -50,7 +51,7 @@ public class JacksonLibHandlerTest extends TestCase {
StringWriter writer = new StringWriter();
JacksonLibHandler handler = new JacksonLibHandler();
handler.fromObject(Arrays.asList(contact), "success", writer);
handler.fromObject(new MockActionInvocation(), Arrays.asList(contact), "success", writer);
String data = writer.toString();
assertTrue(data.startsWith("[{"));
@@ -65,7 +66,7 @@ public class JacksonLibHandlerTest extends TestCase {
Contact target = new Contact();
StringReader reader = new StringReader("{\"age\":44,\"important\":true,\"name\":\"bob\"}");
JacksonLibHandler handler = new JacksonLibHandler();
handler.toObject(reader, target);
handler.toObject(new MockActionInvocation(), reader, target);
assertEquals(contact, target);
}
@@ -78,7 +79,7 @@ public class JacksonLibHandlerTest extends TestCase {
List<Contact> target = new ArrayList<Contact>();
StringReader reader = new StringReader("[{\"age\":44,\"important\":true,\"name\":\"bob\"},{\"age\":33,\"important\":false,\"name\":\"john\"}]");
JacksonLibHandler handler = new JacksonLibHandler();
handler.toObject(reader, target);
handler.toObject(new MockActionInvocation(), reader, target);
assertEquals(source.size(), target.size());
}
@@ -26,6 +26,7 @@ import java.io.StringReader;
import java.io.StringWriter;
import java.util.Arrays;
import com.opensymphony.xwork2.mock.MockActionInvocation;
import junit.framework.TestCase;
public class JsonLibHandlerTest extends TestCase {
@@ -35,7 +36,7 @@ public class JsonLibHandlerTest extends TestCase {
StringWriter writer = new StringWriter();
JsonLibHandler handler = new JsonLibHandler();
handler.fromObject(contact, "success", writer);
handler.fromObject(new MockActionInvocation(), contact, "success", writer);
String data = writer.toString();
assertTrue(data.startsWith("{"));
assertTrue(data.contains("\"age\":44"));
@@ -48,7 +49,7 @@ public class JsonLibHandlerTest extends TestCase {
StringWriter writer = new StringWriter();
JsonLibHandler handler = new JsonLibHandler();
handler.fromObject(Arrays.asList(contact), "success", writer);
handler.fromObject(new MockActionInvocation(), Arrays.asList(contact), "success", writer);
String data = writer.toString();
assertTrue(data.startsWith("[{"));
@@ -63,7 +64,7 @@ public class JsonLibHandlerTest extends TestCase {
Contact target = new Contact();
StringReader reader = new StringReader("{\"age\":44,\"important\":true,\"name\":\"bob\"}");
JsonLibHandler handler = new JsonLibHandler();
handler.toObject(reader, target);
handler.toObject(new MockActionInvocation(), reader, target);
assertEquals(contact, target);
}