Browse files

Enable field name based filtering for json serialization

git-svn-id: https://svn.apache.org/repos/asf/tuscany/sca-java-2.x/trunk@1383129 13f79535-47bb-0310-9956-ffa450edef68
  • Loading branch information...
1 parent 69e6cdc commit e8f7c7471762335a2c2742808a14b44fd43d016e @raymondfeng raymondfeng committed Sep 10, 2012
View
49 ...me/src/main/java/org/apache/tuscany/sca/binding/rest/provider/DataBindingJAXRSWriter.java
@@ -24,6 +24,10 @@
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
@@ -32,6 +36,8 @@
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
+import org.apache.tuscany.sca.common.http.HTTPContext;
+import org.apache.tuscany.sca.common.http.ThreadHTTPContext;
import org.apache.tuscany.sca.core.ExtensionPointRegistry;
import org.apache.tuscany.sca.interfacedef.DataType;
import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl;
@@ -40,7 +46,7 @@
* The generic JAX-RS message body writer based on Tuscany's databindingframework
*/
@Provider
-@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML, MediaType.WILDCARD})
+@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML, MediaType.WILDCARD})
public class DataBindingJAXRSWriter<T> extends DataBindingJAXRSProvider implements MessageBodyWriter<T> {
public DataBindingJAXRSWriter(ExtensionPointRegistry registry) {
@@ -73,8 +79,7 @@ public void writeTo(T t,
dataBinding = OutputStream.class.getName();
} else if ("application/x-protobuf".equals(mediaType.toString())) {
dataBinding = mediaType.toString() + "#" + OutputStream.class.getName();
- }
- else {
+ } else {
dataBinding = dataType.getDataBinding();
write(entityStream, t, type);
return;
@@ -85,7 +90,43 @@ public void writeTo(T t,
introspectAnnotations(annotations, targetDataType);
- mediator.mediate(t, entityStream, dataType, targetDataType, Collections.<String, Object> emptyMap());
+ Map<String, Object> metadata = getFields();
+ mediator.mediate(t, entityStream, dataType, targetDataType, metadata);
+ }
+
+ private Map<String, Object> getFields() {
+ Map<String, Object> metadata = Collections.<String, Object> emptyMap();
+ HTTPContext context = ThreadHTTPContext.getHTTPContext();
+ if (context != null) {
+ metadata = new HashMap<String, Object>();
+ String included = context.getHttpRequest().getParameter("includedFields");
+ String excluded = context.getHttpRequest().getParameter("excludedFields");
+ Set<String> includedFields = tokenize(included);
+ if (includedFields != null) {
+ metadata.put("includedFields", includedFields);
+ }
+ Set<String> excludedFields = tokenize(excluded);
+ if (excludedFields != null) {
+ metadata.put("excludedFields", excludedFields);
+ }
+
+ }
+ return metadata;
+ }
+
+ private Set<String> tokenize(String included) {
+ if (included == null) {
+ return null;
+ }
+ String[] fields = included.split("(,| )+");
+ Set<String> includedFields = new HashSet<String>();
+ for (String f : fields) {
+ String field = f.trim();
+ if (field.length() > 0) {
+ includedFields.add(field);
+ }
+ }
+ return includedFields;
}
}
View
229 ...rc/main/java/org/apache/tuscany/sca/binding/rest/provider/RESTBindingListenerServlet.java
@@ -39,6 +39,7 @@
import org.apache.tuscany.sca.common.http.HTTPContentTypeMapper;
import org.apache.tuscany.sca.common.http.HTTPContext;
import org.apache.tuscany.sca.common.http.HTTPHeader;
+import org.apache.tuscany.sca.common.http.ThreadHTTPContext;
import org.apache.tuscany.sca.common.http.cors.CORSHeaderProcessor;
import org.apache.tuscany.sca.invocation.Invoker;
import org.apache.tuscany.sca.invocation.Message;
@@ -72,62 +73,68 @@
* Constructs a new RESTServiceListenerServlet.
*/
public RESTBindingListenerServlet(Binding binding, Invoker bindingInvoker, MessageFactory messageFactory) {
- this.binding = (RESTBinding) binding;
+ this.binding = (RESTBinding)binding;
this.bindingInvoker = bindingInvoker;
this.messageFactory = messageFactory;
}
@Override
- protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
+ IOException {
if (binding.isCORS()) {
CORSHeaderProcessor.processCORS(binding.getCORSConfiguration(), request, response);
}
- if( binding.getOperationSelector() != null || binding.getRequestWireFormat() != null) {
- HTTPContext bindingContext = new HTTPContext();
- bindingContext.setHttpRequest(request);
- bindingContext.setHttpResponse(response);
+ HTTPContext bindingContext = new HTTPContext();
+ bindingContext.setHttpRequest(request);
+ bindingContext.setHttpResponse(response);
+ ThreadHTTPContext.setHTTPContext(bindingContext);
- // Dispatch the service interaction to the service invoker
- Message requestMessage = messageFactory.createMessage();
- requestMessage.setBindingContext(bindingContext);
+ try {
- requestMessage.setBody(new Object[] {request.getInputStream()});
+ if (binding.getOperationSelector() != null || binding.getRequestWireFormat() != null) {
+ // Dispatch the service interaction to the service invoker
+ Message requestMessage = messageFactory.createMessage();
+ requestMessage.setBindingContext(bindingContext);
- Message responseMessage = bindingInvoker.invoke(requestMessage);
+ requestMessage.setBody(new Object[] {request.getInputStream()});
- // return response to client
- if (responseMessage.isFault()) {
- // Turn a fault into an exception
- Throwable e = (Throwable)responseMessage.getBody();
- response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
- } else {
+ Message responseMessage = bindingInvoker.invoke(requestMessage);
+
+ // return response to client
+ if (responseMessage.isFault()) {
+ // Turn a fault into an exception
+ Throwable e = (Throwable)responseMessage.getBody();
+ response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
+ } else {
- for(HTTPHeader header : binding.getHttpHeaders()) {
- //treat special headers that need to be calculated
- if(header.getName().equalsIgnoreCase("Expires")) {
- GregorianCalendar calendar = new GregorianCalendar();
- calendar.setTime(new Date());
+ for (HTTPHeader header : binding.getHttpHeaders()) {
+ //treat special headers that need to be calculated
+ if (header.getName().equalsIgnoreCase("Expires")) {
+ GregorianCalendar calendar = new GregorianCalendar();
+ calendar.setTime(new Date());
- calendar.add(Calendar.HOUR, Integer.parseInt(header.getValue()));
+ calendar.add(Calendar.HOUR, Integer.parseInt(header.getValue()));
+
+ response.setHeader("Expires", HTTPCacheContext.RFC822DateFormat.format(calendar.getTime()));
+ } else {
+ //default behaviour to pass the header value to HTTP response
+ response.setHeader(header.getName(), header.getValue());
+ }
- response.setHeader("Expires", HTTPCacheContext.RFC822DateFormat.format( calendar.getTime() ));
- } else {
- //default behaviour to pass the header value to HTTP response
- response.setHeader(header.getName(), header.getValue());
}
+ //handle void operations
+ write(response.getOutputStream(), responseMessage.getBody());
+ response.getOutputStream().flush();
+ response.getOutputStream().close();
}
-
- //handle void operations
- write(response.getOutputStream(), responseMessage.getBody());
- response.getOutputStream().flush();
- response.getOutputStream().close();
+ } else {
+ super.service(request, response);
}
- } else {
- super.service(request, response);
+ } finally {
+ ThreadHTTPContext.removeHTTPContext();
}
-
}
@Override
@@ -156,16 +163,16 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) t
}
// Route message based on availability of cache info and cache methods
- if (( cacheContext != null ) && (cacheContext.isEnabled()) && (conditionalGetInvoker != null )) {
- if(id != null && id.length() > 0) {
+ if ((cacheContext != null) && (cacheContext.isEnabled()) && (conditionalGetInvoker != null)) {
+ if (id != null && id.length() > 0) {
requestMessage.setBody(new Object[] {id, cacheContext});
} else {
requestMessage.setBody(new Object[] {cacheContext});
}
responseMessage = conditionalGetInvoker.invoke(requestMessage);
} else {
- if(id != null && id.length() > 0) {
+ if (id != null && id.length() > 0) {
requestMessage.setBody(new Object[] {id});
} else {
//requestMessage.setBody(new Object[] {id});
@@ -178,29 +185,29 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) t
Object body = responseMessage.getBody();
int index = -1;
- if ( -1 < (index = body.getClass().getName().indexOf( "NotModifiedException")) ) {
- if ( index > -1 ) {
- response.sendError( HttpServletResponse.SC_NOT_MODIFIED, body.toString().substring( index ));
+ if (-1 < (index = body.getClass().getName().indexOf("NotModifiedException"))) {
+ if (index > -1) {
+ response.sendError(HttpServletResponse.SC_NOT_MODIFIED, body.toString().substring(index));
} else {
- response.sendError( HttpServletResponse.SC_NOT_MODIFIED );
+ response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
}
return;
- } else if ( -1 < (index = body.getClass().getName().indexOf( "PreconditionFailedException")) ) {
- if ( index > -1 ) {
- response.sendError( HttpServletResponse.SC_PRECONDITION_FAILED, body.toString().substring( index ));
+ } else if (-1 < (index = body.getClass().getName().indexOf("PreconditionFailedException"))) {
+ if (index > -1) {
+ response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, body.toString().substring(index));
} else {
- response.sendError( HttpServletResponse.SC_PRECONDITION_FAILED );
+ response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
}
return;
}
throw new ServletException((Throwable)responseMessage.getBody());
}
- if(response.getContentType() == null || response.getContentType().length() == 0){
+ if (response.getContentType() == null || response.getContentType().length() == 0) {
// Calculate content-type based on extension
String contentType = HTTPContentTypeMapper.getContentType(id);
- if(contentType != null && contentType.length() >0) {
+ if (contentType != null && contentType.length() > 0) {
response.setContentType(contentType);
}
}
@@ -221,10 +228,11 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) t
}
@Override
- protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException,
+ IOException {
// Get the request path
String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8");
- if (path.length() ==0) {
+ if (path.length() == 0) {
// Redirect to a URL ending with / to make relative hrefs work
// relative to the served resource.
response.sendRedirect(request.getRequestURL().append('/').toString());
@@ -243,7 +251,7 @@ protected void doDelete(HttpServletRequest request, HttpServletResponse response
}
// Route message based on availability of cache info and cache methods
- if (( cacheContext != null ) && (cacheContext.isEnabled()) && (conditionalDeleteInvoker != null )) {
+ if ((cacheContext != null) && (cacheContext.isEnabled()) && (conditionalDeleteInvoker != null)) {
requestMessage.setBody(new Object[] {id, cacheContext});
responseMessage = conditionalDeleteInvoker.invoke(requestMessage);
} else {
@@ -254,18 +262,18 @@ protected void doDelete(HttpServletRequest request, HttpServletResponse response
Object body = responseMessage.getBody();
int index = -1;
- if ( -1 < (index = body.getClass().getName().indexOf( "NotModifiedException")) ) {
- if ( index > -1 ) {
- response.sendError( HttpServletResponse.SC_NOT_MODIFIED, body.toString().substring( index ));
+ if (-1 < (index = body.getClass().getName().indexOf("NotModifiedException"))) {
+ if (index > -1) {
+ response.sendError(HttpServletResponse.SC_NOT_MODIFIED, body.toString().substring(index));
} else {
- response.sendError( HttpServletResponse.SC_NOT_MODIFIED );
+ response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
}
return;
- } else if ( -1 < (index = body.getClass().getName().indexOf( "PreconditionFailedException")) ) {
- if ( index > -1 ) {
- response.sendError( HttpServletResponse.SC_PRECONDITION_FAILED, body.toString().substring( index ));
+ } else if (-1 < (index = body.getClass().getName().indexOf("PreconditionFailedException"))) {
+ if (index > -1) {
+ response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, body.toString().substring(index));
} else {
- response.sendError( HttpServletResponse.SC_PRECONDITION_FAILED );
+ response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
}
return;
}
@@ -292,7 +300,7 @@ protected void doDelete(HttpServletRequest request, HttpServletResponse response
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Get the request path
String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8");
- if (path.length() ==0) {
+ if (path.length() == 0) {
// Redirect to a URL ending with / to make relative hrefs work
// relative to the served resource.
response.sendRedirect(request.getRequestURL().append('/').toString());
@@ -311,7 +319,7 @@ protected void doPut(HttpServletRequest request, HttpServletResponse response) t
}
// Route message based on availability of cache info and cache methods
- if (( cacheContext != null ) && (cacheContext.isEnabled()) && (conditionalPutInvoker != null )) {
+ if ((cacheContext != null) && (cacheContext.isEnabled()) && (conditionalPutInvoker != null)) {
requestMessage.setBody(new Object[] {id, cacheContext});
responseMessage = conditionalPutInvoker.invoke(requestMessage);
} else {
@@ -322,18 +330,18 @@ protected void doPut(HttpServletRequest request, HttpServletResponse response) t
Object body = responseMessage.getBody();
int index = -1;
- if ( -1 < (index = body.getClass().getName().indexOf( "NotModifiedException")) ) {
- if ( index > -1 ) {
- response.sendError( HttpServletResponse.SC_NOT_MODIFIED, body.toString().substring( index ));
+ if (-1 < (index = body.getClass().getName().indexOf("NotModifiedException"))) {
+ if (index > -1) {
+ response.sendError(HttpServletResponse.SC_NOT_MODIFIED, body.toString().substring(index));
} else {
- response.sendError( HttpServletResponse.SC_NOT_MODIFIED );
+ response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
}
return;
- } else if ( -1 < (index = body.getClass().getName().indexOf( "PreconditionFailedException")) ) {
- if ( index > -1 ) {
- response.sendError( HttpServletResponse.SC_PRECONDITION_FAILED, body.toString().substring( index ));
+ } else if (-1 < (index = body.getClass().getName().indexOf("PreconditionFailedException"))) {
+ if (index > -1) {
+ response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, body.toString().substring(index));
} else {
- response.sendError( HttpServletResponse.SC_PRECONDITION_FAILED );
+ response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
}
return;
}
@@ -357,10 +365,11 @@ protected void doPut(HttpServletRequest request, HttpServletResponse response) t
}
@Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
+ IOException {
// Get the request path
String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8");
- if (path.length() ==0) {
+ if (path.length() == 0) {
// Redirect to a URL ending with / to make relative hrefs work
// relative to the served resource.
response.sendRedirect(request.getRequestURL().append('/').toString());
@@ -374,59 +383,57 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
Message responseMessage = null;
HTTPCacheContext cacheContext = null;
try {
- cacheContext = HTTPCacheContext.createCacheContextFromRequest(request);
+ cacheContext = HTTPCacheContext.createCacheContextFromRequest(request);
} catch (ParseException e) {
}
// Route message based on availability of cache info and cache methods
- if (( cacheContext != null ) && (cacheContext.isEnabled()) && (conditionalPostInvoker != null )) {
- requestMessage.setBody(new Object[] {cacheContext});
- responseMessage = conditionalPostInvoker.invoke(requestMessage);
+ if ((cacheContext != null) && (cacheContext.isEnabled()) && (conditionalPostInvoker != null)) {
+ requestMessage.setBody(new Object[] {cacheContext});
+ responseMessage = conditionalPostInvoker.invoke(requestMessage);
} else {
- requestMessage.setBody(new Object[] {});
- responseMessage = postInvoker.invoke(requestMessage);
+ requestMessage.setBody(new Object[] {});
+ responseMessage = postInvoker.invoke(requestMessage);
}
if (responseMessage.isFault()) {
- Object body = responseMessage.getBody();
-
- int index = -1;
- if ( -1 < (index = body.getClass().getName().indexOf( "NotModifiedException")) ) {
- if ( index > -1 )
- response.sendError( HttpServletResponse.SC_NOT_MODIFIED, body.toString().substring( index ));
- else
- response.sendError( HttpServletResponse.SC_NOT_MODIFIED );
- return;
- } else if ( -1 < (index = body.getClass().getName().indexOf( "PreconditionFailedException")) ) {
- if ( index > -1 )
- response.sendError( HttpServletResponse.SC_PRECONDITION_FAILED, body.toString().substring( index ));
- else
- response.sendError( HttpServletResponse.SC_PRECONDITION_FAILED );
- return;
+ Object body = responseMessage.getBody();
+
+ int index = -1;
+ if (-1 < (index = body.getClass().getName().indexOf("NotModifiedException"))) {
+ if (index > -1)
+ response.sendError(HttpServletResponse.SC_NOT_MODIFIED, body.toString().substring(index));
+ else
+ response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
+ return;
+ } else if (-1 < (index = body.getClass().getName().indexOf("PreconditionFailedException"))) {
+ if (index > -1)
+ response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, body.toString().substring(index));
+ else
+ response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
+ return;
}
throw new ServletException((Throwable)responseMessage.getBody());
}
-
// Test if the ETag and LastModified are returned as a cache context.
- Object body = responseMessage.getBody();
- if ( body.getClass() == HTTPCacheContext.class ) {
- // Transfer to header if so.
- HTTPCacheContext cc = (HTTPCacheContext)responseMessage.getBody();
- if (( cc != null ) && ( cc.isEnabled() )) {
- String eTag = cc.getETag();
- if ( eTag != null ) {
- response.setHeader( "ETag", cc.getETag() );
- }
- String lastModified = cc.getLastModified();
- if ( lastModified != null) {
- response.setHeader( "LastModified", cc.getLastModified() );
- }
- }
- }
+ Object body = responseMessage.getBody();
+ if (body.getClass() == HTTPCacheContext.class) {
+ // Transfer to header if so.
+ HTTPCacheContext cc = (HTTPCacheContext)responseMessage.getBody();
+ if ((cc != null) && (cc.isEnabled())) {
+ String eTag = cc.getETag();
+ if (eTag != null) {
+ response.setHeader("ETag", cc.getETag());
+ }
+ String lastModified = cc.getLastModified();
+ if (lastModified != null) {
+ response.setHeader("LastModified", cc.getLastModified());
+ }
+ }
+ }
}
-
public void setInvoker(Invoker invoker) {
this.invoker = invoker;
}
@@ -435,7 +442,6 @@ public Invoker getInvoker() {
return invoker;
}
-
/**
* @return the getInvoker
*/
@@ -554,8 +560,6 @@ public void setConditionalDeleteInvoker(Invoker conditionalDeleteInvoker) {
*
*/
-
-
private void write(OutputStream out, Object obj) throws IOException {
if (obj == null) {
return;
@@ -579,5 +583,4 @@ private void write(OutputStream out, Object obj) throws IOException {
}
}
-
}
View
69 ...rc/main/java/org/apache/tuscany/sca/binding/rest/provider/RESTServiceListenerServlet.java
@@ -36,6 +36,7 @@
import org.apache.tuscany.sca.common.http.HTTPCacheContext;
import org.apache.tuscany.sca.common.http.HTTPContext;
import org.apache.tuscany.sca.common.http.HTTPHeader;
+import org.apache.tuscany.sca.common.http.ThreadHTTPContext;
import org.apache.tuscany.sca.common.http.cors.CORSHeaderProcessor;
import org.apache.tuscany.sca.invocation.Invoker;
import org.apache.tuscany.sca.invocation.Message;
@@ -48,19 +49,19 @@
* @version $Rev$ $Date$
*/
public class RESTServiceListenerServlet extends HttpServlet implements Servlet {
-
+
private static final long serialVersionUID = -5543706958107836637L;
-
+
transient private RESTBinding binding;
transient private ServletConfig config;
transient private MessageFactory messageFactory;
transient private Invoker serviceInvoker;
-
+
/**
* Constructs a new HTTPServiceListenerServlet.
*/
public RESTServiceListenerServlet(Binding binding, Invoker serviceInvoker, MessageFactory messageFactory) {
- this.binding = (RESTBinding) binding;
+ this.binding = (RESTBinding)binding;
this.serviceInvoker = serviceInvoker;
this.messageFactory = messageFactory;
}
@@ -78,7 +79,7 @@ public void init(ServletConfig config) throws ServletException {
}
public void destroy() {
-
+
}
@Override
@@ -89,34 +90,40 @@ public void service(HttpServletRequest request, HttpServletResponse response) th
HTTPContext bindingContext = new HTTPContext();
bindingContext.setHttpRequest(request);
bindingContext.setHttpResponse(response);
-
- // Dispatch the service interaction to the service invoker
- Message requestMessage = messageFactory.createMessage();
- requestMessage.setBindingContext(bindingContext);
- requestMessage.setBody(new Object[]{request, response});
- Message responseMessage = serviceInvoker.invoke(requestMessage);
- if (responseMessage.isFault()) {
- // Turn a fault into an exception
- //throw new ServletException((Throwable)responseMessage.getBody());
- Throwable e = (Throwable)responseMessage.getBody();
- ((HttpServletResponse)response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
- } else {
- //handles declarative headers configured on the composite
- for(HTTPHeader header : binding.getHttpHeaders()) {
- //treat special headers that need to be calculated
- if(header.getName().equalsIgnoreCase("Expires")) {
- GregorianCalendar calendar = new GregorianCalendar();
- calendar.setTime(new Date());
-
- calendar.add(Calendar.HOUR, Integer.parseInt(header.getValue()));
-
- response.setHeader("Expires", HTTPCacheContext.RFC822DateFormat.format( calendar.getTime() ));
- } else {
- //default behaviour to pass the header value to HTTP response
- response.setHeader(header.getName(), header.getValue());
- }
+ ThreadHTTPContext.setHTTPContext(bindingContext);
+ try {
+
+ // Dispatch the service interaction to the service invoker
+ Message requestMessage = messageFactory.createMessage();
+ requestMessage.setBindingContext(bindingContext);
+ requestMessage.setBody(new Object[] {request, response});
+ Message responseMessage = serviceInvoker.invoke(requestMessage);
+ if (responseMessage.isFault()) {
+ // Turn a fault into an exception
+ //throw new ServletException((Throwable)responseMessage.getBody());
+ Throwable e = (Throwable)responseMessage.getBody();
+ ((HttpServletResponse)response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
+ } else {
+ //handles declarative headers configured on the composite
+ for (HTTPHeader header : binding.getHttpHeaders()) {
+ //treat special headers that need to be calculated
+ if (header.getName().equalsIgnoreCase("Expires")) {
+ GregorianCalendar calendar = new GregorianCalendar();
+ calendar.setTime(new Date());
+
+ calendar.add(Calendar.HOUR, Integer.parseInt(header.getValue()));
+
+ response.setHeader("Expires", HTTPCacheContext.RFC822DateFormat.format(calendar.getTime()));
+ } else {
+ //default behaviour to pass the header value to HTTP response
+ response.setHeader(header.getName(), header.getValue());
+ }
+
+ }
}
+ } finally {
+ ThreadHTTPContext.removeHTTPContext();
}
}
}
View
40 ...test/java/org/apache/tuscany/sca/binding/rest/wireformat/json/CatalogServiceTestCase.java
@@ -42,11 +42,14 @@
public class CatalogServiceTestCase {
private static final String SERVICE_URL = "http://localhost:8085/Catalog";
- private static final String GET_RESPONSE = "{\"items\":[{\"price\":\"$1.55\",\"name\":\"Pear\"},{\"price\":\"$2.99\",\"name\":\"Apple\"},{\"price\":\"$3.55\",\"name\":\"Orange\"}]}";
+ private static final String GET_RESPONSE =
+ "{\"items\":[{\"price\":\"$1.55\",\"name\":\"Pear\"},{\"price\":\"$2.99\",\"name\":\"Apple\"},{\"price\":\"$3.55\",\"name\":\"Orange\"}]}";
private static final String NEW_ITEM = "{\"price\":\"$4.35\",\"name\":\"Grape\"}\"";
- private static final String GET_NEW_RESPONSE = "{\"items\":[{\"price\":\"$1.55\",\"name\":\"Pear\"},{\"price\":\"$2.99\",\"name\":\"Apple\"},{\"price\":\"$3.55\",\"name\":\"Orange\"},{\"price\":\"$4.35\",\"name\":\"Grape\"}]}";
+ private static final String GET_NEW_RESPONSE =
+ "{\"items\":[{\"price\":\"$1.55\",\"name\":\"Pear\"},{\"price\":\"$2.99\",\"name\":\"Apple\"},{\"price\":\"$3.55\",\"name\":\"Orange\"},{\"price\":\"$4.35\",\"name\":\"Grape\"}]}";
private static final String UPDATED_ITEM = "{\"price\":\"$1.35\",\"name\":\"Grape\"}\"";
- private static final String GET_UPDATED_RESPONSE = "{\"items\":[{\"price\":\"$1.55\",\"name\":\"Pear\"},{\"price\":\"$2.99\",\"name\":\"Apple\"},{\"price\":\"$3.55\",\"name\":\"Orange\"},{\"price\":\"$1.35\",\"name\":\"Grape\"}]}";
+ private static final String GET_UPDATED_RESPONSE =
+ "{\"items\":[{\"price\":\"$1.55\",\"name\":\"Pear\"},{\"price\":\"$2.99\",\"name\":\"Apple\"},{\"price\":\"$3.55\",\"name\":\"Orange\"},{\"price\":\"$1.35\",\"name\":\"Grape\"}]}";
private static Node node;
@@ -64,7 +67,7 @@ public static void init() throws Exception {
@AfterClass
public static void destroy() throws Exception {
- if(node != null) {
+ if (node != null) {
node.stop();
}
}
@@ -84,15 +87,29 @@ public void testGetInvocation() throws Exception {
Assert.assertEquals(200, response.getResponseCode());
Assert.assertNotNull(response.getText());
- Assert.assertTrue(validateJsonResponse(GET_RESPONSE,response.getText()));
+ Assert.assertTrue(validateJsonResponse(GET_RESPONSE, response.getText()));
}
+ @Test
+ public void testGetInvocationWithFilter() throws Exception {
+ WebConversation wc = new WebConversation();
+ WebRequest request = new GetMethodWebRequest(SERVICE_URL + "?excludedFields=price");
+ request.setHeaderField("Content-Type", "application/json");
+ WebResponse response = wc.getResource(request);
+
+ Assert.assertEquals(200, response.getResponseCode());
+ String json = response.getText();
+ Assert.assertNotNull(json);
+ Assert.assertFalse(json.contains("price"));
+ }
@Test
public void testPostInvocation() throws Exception {
//Add new item to catalog
WebConversation wc = new WebConversation();
- WebRequest request = new PostMethodWebRequest(SERVICE_URL, new ByteArrayInputStream(NEW_ITEM.getBytes("UTF-8")),"application/json");
+ WebRequest request =
+ new PostMethodWebRequest(SERVICE_URL, new ByteArrayInputStream(NEW_ITEM.getBytes("UTF-8")),
+ "application/json");
request.setHeaderField("Content-Type", "application/json");
WebResponse response = wc.getResource(request);
@@ -109,14 +126,16 @@ public void testPostInvocation() throws Exception {
Assert.assertEquals(200, response.getResponseCode());
Assert.assertNotNull(response.getText());
- Assert.assertTrue(validateJsonResponse(GET_NEW_RESPONSE,response.getText()));
+ Assert.assertTrue(validateJsonResponse(GET_NEW_RESPONSE, response.getText()));
}
@Test
public void testPutInvocation() throws Exception {
//Add new item to catalog
WebConversation wc = new WebConversation();
- WebRequest request = new PostMethodWebRequest(SERVICE_URL, new ByteArrayInputStream(UPDATED_ITEM.getBytes("UTF-8")),"application/json");
+ WebRequest request =
+ new PostMethodWebRequest(SERVICE_URL, new ByteArrayInputStream(UPDATED_ITEM.getBytes("UTF-8")),
+ "application/json");
request.setHeaderField("Content-Type", "application/json");
WebResponse response = wc.getResource(request);
@@ -133,15 +152,14 @@ public void testPutInvocation() throws Exception {
Assert.assertEquals(200, response.getResponseCode());
Assert.assertNotNull(response.getText());
- Assert.assertTrue(validateJsonResponse(GET_UPDATED_RESPONSE,response.getText()));
+ Assert.assertTrue(validateJsonResponse(GET_UPDATED_RESPONSE, response.getText()));
}
-
private boolean validateJsonResponse(String expected, String actual) throws JSONException {
JSONObject jsonExpected = new JSONObject(expected);
JSONObject jsonActual = new JSONObject(actual);
- if(jsonExpected.getJSONArray("items").length() != jsonActual.getJSONArray("items").length()) {
+ if (jsonExpected.getJSONArray("items").length() != jsonActual.getJSONArray("items").length()) {
return false;
}

0 comments on commit e8f7c74

Please sign in to comment.