I am trying to request a new call from the request pre-matching filter. I need to initiate the new request from the start so that this new requested will again go through the filters and route to a different process.
#Provider
#PreMatching
public class SSOFilter implements ContainerRequestFilter
{
#Override
public void filter(ContainerRequestContext requestContext) throws IOException
{
URI ssoUri = null;
try
{
String requestedQueryString = requestContext.getUriInfo().getRequestUri().getQuery();
ssoUri = new URI(requestContext.getUriInfo().getBaseUri()+"/saml/SSO?"+ requestedQueryString);
}
catch (URISyntaxException e)
{
Debug.println(Debug.ERROR, "Error encountered in generating SSO URI " + e.getMessage());
}
Response.status(Status.TEMPORARY_REDIRECT).location(ssoUri).build();
}
}
I want this call to happen only on the server so that browser shouldn't be aware of what's happening here, Also the browser URL shouldn't update.
I have implemented filter and I have called getEntityStream of ContainerRequestContext and set the exact value back by using setEntitystream. If i use this filter then #FormParameter data becomes null and if i don't use filter then everything will be fine (as I am not calling getEntityStream) and i have to use filter to capture request data.
Note: I am getting form params from MultivaluedMap formParams but not from #FormParameter.
Environment :- Rest Easy API with Jboss Wildfly 8 server.
#Provider
#Priority(Priorities.LOGGING)
public class CustomLoggingFilter implements ContainerRequestFilter, ContainerResponseFilter{
final static Logger log = Logger.getLogger(CustomLoggingFilter.class);
#Context
private ResourceInfo resourceInfo;
#Override
public void filter(ContainerRequestContext requestContext)
throws IOException {
MDC.put("start-time", String.valueOf(System.currentTimeMillis()));
String entityParameter = readEntityStream(requestContext);
log.info("Entity Parameter :"+entityParameter);
}
private String readEntityStream(ContainerRequestContext requestContext){
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
final InputStream inputStream = requestContext.getEntityStream();
final StringBuilder builder = new StringBuilder();
int read=0;
final byte[] data = new byte[4096];
try {
while ((read = inputStream.read(data)) != -1) {
outStream.write(data, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
byte[] requestEntity = outStream.toByteArray();
if (requestEntity.length == 0) {
builder.append("");
} else {
builder.append(new String(requestEntity));
}
requestContext.setEntityStream(new ByteArrayInputStream(requestEntity) );
return builder.toString();
}
return null;
}
}
class customResource
{
//// This code is not working
#POST
#Path("voiceCallBack")
#ApiOperation(value = "Voice call back from Twilio")
public void voiceCallback(#FormParam("param") String param)
{
log.info("param:" + param);
}
// This code is working
#POST
#Path("voiceCallBackMap")
#ApiOperation(value = "Voice call back from Twilio")
public void voiceCallbackMap(final MultivaluedMap<String, String> formParams)
{
String param = formParams.getFirst("param");
}
}
please suggest me solution & Thanks in Advance.
I found during run time that instance of the entity stream (from http request) is of type org.apache.catalina.connector.CoyoteInputStream (I am using jboss-as-7.1.1.Final). But we are setting entity stream with the instance of java.io.ByteArrayInputStream. So Resteasy is unable to bind individual formparmeters.
There are two solutions for this you can use any one of them :
Use this approach How to read JBoss Resteasy's servlet request twice while maintaing #FormParam binding?
Get form parameters like this:
#POST
#Path("voiceCallBackMap")
#ApiOperation(value = "Voice call back from Twilio")
public void voiceCallbackMap(final MultivaluedMap<String, String> formParams)
{
String param = formParams.getFirst("param");
}
In my app I am using netflix zuul to route a request from a microservice (gateway) to another. The requests are being routed fine but I also want to introduce some parameters in the request body before it is routed to the appropriate microservice. For this I am using Zuul pre filter like this.
public class SimpleFilter extends ZuulFilter {
private static Logger log = LoggerFactory.getLogger(SimpleFilter.class);
#Override
public String filterType() {
return "pre";
}
#Override
public int filterOrder() {
return 1;
}
#Override
public boolean shouldFilter() {
return true;
}
#Override
public Object run() {
try {
RequestContext context = RequestContext.getCurrentContext();
InputStream in = (InputStream) context.get("requestEntity");
if (in == null) {
in = context.getRequest().getInputStream();
}
String body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
// body = "request body modified via set('requestEntity'): "+ body;
body = body.toUpperCase();
context.set("requestEntity", new ByteArrayInputStream(body.getBytes("UTF-8")));
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return null;
}
}
For now I am just trying to change the body to upper case but the microservice to which this request is routed doesn't receive the modified body (upper case). Instead it receives the original one. Am I doing something wrong. Any help would be appreciated. Thanks !!
Was able to do the following - transform a GET request to a POST request, and add body content to the (proxied) POST request.
public Object run() throws ZuulException {
RequestContext context = RequestContext.getCurrentContext();
context.addZuulRequestHeader("Content-Type", "application/x-www-form-urlencoded");
String body = String.format("a=%s&b=%s", a, b);
final byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
context.setRequest(new HttpServletRequestWrapper(context.getRequest()) {
#Override
public ServletInputStream getInputStream() {
return new ServletInputStreamWrapper(bytes);
}
#Override
public int getContentLength() {
return bytes.length;
}
#Override
public long getContentLengthLong() {
return bytes.length;
}
#Override
public String getMethod() {
return "POST";
}
});
return null;
}
try this one It's may be work in your case .
requestContext.getCurrentContext().put("requestEntity", new ByteArrayInputStream(body.getBytes("UTF-8")));
Turned out this method cannot change the request body within the requestContext. Truly in the requestContext, a new field "requestEntity" is added, however, the request body from context.getRequest().getInputStream() remains the same after this operation.
You can modify the request body, see this answer for an example. You just need to wrap the new request data and make sure you correctly report it's new content length.
I have a scenario in Zuul where the service that the URL is routed too might be down . So the reponse body gets thrown with 500 HTTP Status and ZuulException in the JSON body response.
{
"timestamp": 1459973637928,
"status": 500,
"error": "Internal Server Error",
"exception": "com.netflix.zuul.exception.ZuulException",
"message": "Forwarding error"
}
All I want to do is to customise or remove the JSON response and maybe change the HTTP status Code.
I tried to create a exception Handler with #ControllerAdvice but the exception is not grabbed by the handler.
UPDATES:
So I extended the Zuul Filter I can see it getting into the run method after the error has been executed how do i change the response then. Below is what i got so far. I read somewhere about SendErrorFilter but how do i implement that and what does it do?
public class CustomFilter extends ZuulFilter {
#Override
public String filterType() {
return "post";
}
#Override
public int filterOrder() {
return 1;
}
#Override
public boolean shouldFilter() {
return true;
}
#Override
public Object run() {
final RequestContext ctx = RequestContext.getCurrentContext();
final HttpServletResponse response = ctx.getResponse();
if (HttpStatus.INTERNAL_SERVER_ERROR.value() == ctx.getResponse().getStatus()) {
try {
response.sendError(404, "Error Error"); //trying to change the response will need to throw a JSON body.
} catch (final IOException e) {
e.printStackTrace();
} ;
}
return null;
}
Added this to the class that has #EnableZuulProxy
#Bean
public CustomFilter customFilter() {
return new CustomFilter();
}
We finally got this working [Coded by one of my colleague]:-
public class CustomErrorFilter extends ZuulFilter {
private static final Logger LOG = LoggerFactory.getLogger(CustomErrorFilter.class);
#Override
public String filterType() {
return "post";
}
#Override
public int filterOrder() {
return -1; // Needs to run before SendErrorFilter which has filterOrder == 0
}
#Override
public boolean shouldFilter() {
// only forward to errorPath if it hasn't been forwarded to already
return RequestContext.getCurrentContext().containsKey("error.status_code");
}
#Override
public Object run() {
try {
RequestContext ctx = RequestContext.getCurrentContext();
Object e = ctx.get("error.exception");
if (e != null && e instanceof ZuulException) {
ZuulException zuulException = (ZuulException)e;
LOG.error("Zuul failure detected: " + zuulException.getMessage(), zuulException);
// Remove error code to prevent further error handling in follow up filters
ctx.remove("error.status_code");
// Populate context with new response values
ctx.setResponseBody(“Overriding Zuul Exception Body”);
ctx.getResponse().setContentType("application/json");
ctx.setResponseStatusCode(500); //Can set any error code as excepted
}
}
catch (Exception ex) {
LOG.error("Exception filtering in custom error filter", ex);
ReflectionUtils.rethrowRuntimeException(ex);
}
return null;
}
}
The Zuul RequestContext doesn't contain the error.exception as mentioned in this answer.
Up to date the Zuul error filter:
#Component
public class ErrorFilter extends ZuulFilter {
private static final Logger LOG = LoggerFactory.getLogger(ErrorFilter.class);
private static final String FILTER_TYPE = "error";
private static final String THROWABLE_KEY = "throwable";
private static final int FILTER_ORDER = -1;
#Override
public String filterType() {
return FILTER_TYPE;
}
#Override
public int filterOrder() {
return FILTER_ORDER;
}
#Override
public boolean shouldFilter() {
return true;
}
#Override
public Object run() {
final RequestContext context = RequestContext.getCurrentContext();
final Object throwable = context.get(THROWABLE_KEY);
if (throwable instanceof ZuulException) {
final ZuulException zuulException = (ZuulException) throwable;
LOG.error("Zuul failure detected: " + zuulException.getMessage());
// remove error code to prevent further error handling in follow up filters
context.remove(THROWABLE_KEY);
// populate context with new response values
context.setResponseBody("Overriding Zuul Exception Body");
context.getResponse().setContentType("application/json");
// can set any error code as excepted
context.setResponseStatusCode(503);
}
return null;
}
}
I had the same problem and was able to solve it in simpler way
Just put this into you Filter run() method
if (<your condition>) {
ZuulException zuulException = new ZuulException("User message", statusCode, "Error Details message");
throw new ZuulRuntimeException(zuulException);
}
and SendErrorFilter will deliver to the user the message with the desired statusCode.
This Exception in an Exception pattern does not look exactly nice, but it works here.
Forwarding is often done by a filter, in this case the request does not even reach a controller. This would explain why your #ControllerAdvice does not work.
If you forward in the controller than the #ControllerAdvice should work.
Check if spring creates an instance of the class annotated with #ControllerAdvice. For that place a breakpoint in the class and see whether it is hit.
Add a breakpoint also in the controller method where the forwarding should happen. May be you accidently invoke another controller method than you inspect ?
These steps should help you resolve the issue.
In your class annotated with #ControllerAdvice add an ExceptionHandler method annotated with #ExceptionHandler(Exception.class), that should catch every Exception.
EDIT :
You can try to add your own filter that converts the error response returned by the Zuulfilter. There you can change the response as you like.
How the error response can be customized is explained here :
exception handling for filter in spring
Placing the filter correctly may be a little tricky.
Not exactly sure about the correct position, but you should be aware of the order of your filters and the place where you handle the exception.
If you place it before the Zuulfilter, you have to code your error handling after calling doFilter().
If you place it after the Zuulfilter, you have to code your error handling before calling doFilter().
Add breakpoints in your filter before and after doFilter() may help to find the correct position.
Here are the steps to do it with #ControllerAdvice:
First add a filter of type error and let it be run before the SendErrorFilter in zuul itself.
Make sure to remove the key associated with the exception from the RequestContext to prevent the SendErrorFilter from executing.
Use RequestDispatcher to forward the request to the ErrorController -- explained below.
Add a #RestController class and make it extends AbstractErrorController, and re-throw the exception again (add it in the step of executing your new error filter with (key, exception), get it from the RequestContext in your controller).
The exception will now be caught in your #ControllerAdvice class.
The simplest solution is to follow first 4 steps.
1. Create your own CustomErrorController extends
AbstractErrorController which will not allow the
BasicErrorController to be called.
2. Customize according to your need refer below method from
BasicErrorController.
<pre><code>
#RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request,
isIncludeStackTrace(request, MediaType.ALL));
HttpStatus status = getStatus(request);
return new ResponseEntity<>(body, status);
}
</pre></code>
4. You can control whether you want exception / stack trace to be printed or not can do as mentioned below:
<pre><code>
server.error.includeException=false
server.error.includeStacktrace=ON_TRACE_PARAM
</pre></code>
====================================================
5. If you want all together different error response re-throw your custom exception from your CustomErrorController and implement the Advice class as mentioned below:
<pre><code>
#Controller
#Slf4j
public class CustomErrorController extends BasicErrorController {
public CustomErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties,
List<ErrorViewResolver> errorViewResolvers) {
super(errorAttributes, serverProperties.getError(), errorViewResolvers);
log.info("Created");
}
#Override
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
HttpStatus status = getStatus(request);
throw new CustomErrorException(String.valueOf(status.value()), status.getReasonPhrase(), body);
}
}
#ControllerAdvice
public class GenericExceptionHandler {
// Exception handler annotation invokes a method when a specific exception
// occurs. Here we have invoked Exception.class since we
// don't have a specific exception scenario.
#ExceptionHandler(CustomException.class)
#ResponseBody
public ErrorListWsDTO customExceptionHandle(
final HttpServletRequest request,
final HttpServletResponse response,
final CustomException exception) {
LOG.info("Exception Handler invoked");
ErrorListWsDTO errorData = null;
errorData = prepareResponse(response, exception);
response.setStatus(Integer.parseInt(exception.getCode()));
return errorData;
}
/**
* Prepare error response for BAD Request
*
* #param response
* #param exception
* #return
*/
private ErrorListWsDTO prepareResponse(final HttpServletResponse response,
final AbstractException exception) {
final ErrorListWsDTO errorListData = new ErrorListWsDTO();
final List<ErrorWsDTO> errorList = new ArrayList<>();
response.setStatus(HttpStatus.BAD_REQUEST.value());
final ErrorWsDTO errorData = prepareErrorData("500",
"FAILURE", exception.getCause().getMessage());
errorList.add(errorData);
errorListData.setErrors(errorList);
return errorListData;
}
/**
* This method is used to prepare error data
*
* #param code
* error code
* #param status
* status can be success or failure
* #param exceptionMsg
* message description
* #return ErrorDTO
*/
private ErrorWsDTO prepareErrorData(final String code, final String status,
final String exceptionMsg) {
final ErrorWsDTO errorDTO = new ErrorWsDTO();
errorDTO.setReason(code);
errorDTO.setType(status);
errorDTO.setMessage(exceptionMsg);
return errorDTO;
}
}
</pre></code>
This is what worked for me. RestExceptionResponse is the class which is used within the #ControllerAdvice, so we have an identical exception response in case of internal ZuulExceptions.
#Component
#Log4j
public class CustomZuulErrorFilter extends ZuulFilter {
private static final String SEND_ERROR_FILTER_RAN = "sendErrorFilter.ran";
#Override
public String filterType() {
return ERROR_TYPE;
}
#Override
public int filterOrder() {
return SEND_ERROR_FILTER_ORDER - 1; // Needs to run before SendErrorFilter which has filterOrder == 0
}
#Override
public boolean shouldFilter() {
RequestContext ctx = RequestContext.getCurrentContext();
Throwable ex = ctx.getThrowable();
return ex instanceof ZuulException && !ctx.getBoolean(SEND_ERROR_FILTER_RAN, false);
}
#Override
public Object run() {
try {
RequestContext ctx = RequestContext.getCurrentContext();
ZuulException ex = (ZuulException) ctx.getThrowable();
// log this as error
log.error(StackTracer.toString(ex));
String requestUri = ctx.containsKey(REQUEST_URI_KEY) ? ctx.get(REQUEST_URI_KEY).toString() : "/";
RestExceptionResponse exceptionResponse = new RestExceptionResponse(HttpStatus.INTERNAL_SERVER_ERROR, ex, requestUri);
// Populate context with new response values
ctx.setResponseStatusCode(500);
this.writeResponseBody(ctx.getResponse(), exceptionResponse);
ctx.set(SEND_ERROR_FILTER_RAN, true);
}
catch (Exception ex) {
log.error(StackTracer.toString(ex));
ReflectionUtils.rethrowRuntimeException(ex);
}
return null;
}
private void writeResponseBody(HttpServletResponse response, Object body) throws IOException {
response.setContentType("application/json");
try (PrintWriter writer = response.getWriter()) {
writer.println(new JSonSerializer().toJson(body));
}
}
}
The output looks like this:
{
"timestamp": "2020-08-10 16:18:16.820",
"status": 500,
"error": "Internal Server Error",
"path": "/service",
"exception": {
"message": "Filter threw Exception",
"exceptionClass": "com.netflix.zuul.exception.ZuulException",
"superClasses": [
"com.netflix.zuul.exception.ZuulException",
"java.lang.Exception",
"java.lang.Throwable",
"java.lang.Object"
],
"stackTrace": null,
"cause": {
"message": "com.netflix.zuul.exception.ZuulException: Forwarding error",
"exceptionClass": "org.springframework.cloud.netflix.zuul.util.ZuulRuntimeException",
"superClasses": [
"org.springframework.cloud.netflix.zuul.util.ZuulRuntimeException",
"java.lang.RuntimeException",
"java.lang.Exception",
"java.lang.Throwable",
"java.lang.Object"
],
"stackTrace": null,
"cause": {
"message": "Forwarding error",
"exceptionClass": "com.netflix.zuul.exception.ZuulException",
"superClasses": [
"com.netflix.zuul.exception.ZuulException",
"java.lang.Exception",
"java.lang.Throwable",
"java.lang.Object"
],
"stackTrace": null,
"cause": {
"message": "Load balancer does not have available server for client: template-scalable-service",
"exceptionClass": "com.netflix.client.ClientException",
"superClasses": [
"com.netflix.client.ClientException",
"java.lang.Exception",
"java.lang.Throwable",
"java.lang.Object"
],
"stackTrace": null,
"cause": null
}
}
}
}
}
Title say about my issue. I need wrap DTO in to a javascript method callback. Currently I return on request JSON. But problem with using this in Ajax because I send GET to other domain. and of course security police.
I have idea to create addition provide. Have you any example, links or suggestion how can do this.
There's no explicit support for JSONP in RESTEasy, however one easy way to enable JSONP in your application is to write a Servlet Filter.
Here's a few links that can help you write a filter:
jsonp-java: server side filter wraps any response into a jsonp callback
Serving up JSONP from your JAX-RS Web Services
Implementing a Servlet Filter for JSONP callback with Spring’s DelegatingFilterProxy (if you're using Spring)
When I had this requirement I ended up writing my own since none of the examples I found seemed to quite nail it. Here's my advice for writing your own filter:
only wrap the response if a callback parameter is specified (obviously)
only wrap the response if the response content type is application/json (or if you want to support a wider selection of variants, only wrap if the response content type is application/json or application/*+json)
use an HttpServletResponseWrapper so that you can invoke the forward chain (chain.doFilter) without writing any data to the real response. Once the forward chain is complete you can then check the content type, make sure you want to wrap the response as JSONP, then write the captured data into the real response, along with the JSONP prefix and suffix.
when you do decide to wrap the response as JSONP, make sure you change the response content type to text/javascript
If you haven't done much with Java EE Filters before, you may want to read the relevant section of the Java EE tutorial first: Filtering Requests and Responses.
I make draft workaround for this problem. Try it. This solution takes data via http get parameters and translate to virtual POST request.
JQuery:
function call(){
var val = '{"routes":[{"arrivalAddress":{"fullAddress":"DME"},"destinationAddress":{"fullAddress":"SVO"}}],"carsCount":"1"}';
var jHandler = "doMap";
$.getJSON("http://xxx:yyy/app-0.0.0.1/rest/requestPrice?callback=" + jHandler + "&json=" + encodeURIComponent(val)+"&jsoncallback=?", null, null, "json");
}
function doMap(obj){
alert(obj);
}
Declaration in Service interface
#POST
#Path("requestPrice")
#Produces("application/json")
#Consumes("application/json")
PriceResponse requestPrice(PriceRequest request) throws ServiceException;
Filter class:
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class JSONPRequestFilter implements Filter {
private String callbackParameter;
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (!(request instanceof HttpServletRequest)) {
throw new ServletException("This filter can " +
" only process HttpServletRequest requests");
}
final HttpServletRequest httpRequest = (HttpServletRequest) request;
final HttpServletResponse httpResponse = (HttpServletResponse) response;
if (isJSONPRequest(httpRequest)) {
RequestWrapper requestWrapper = new RequestWrapper(httpRequest);
requestWrapper.setContentType("application/json; charset=UTF-8");
requestWrapper.setHeader("cache-control", "no-cache");
requestWrapper.setHeader("accept", "application/json");
requestWrapper.setCharacterEncoding("UTF-8");
requestWrapper.setBody(httpRequest.getParameter("json"));
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(httpResponse) {
#Override
public ServletOutputStream getOutputStream() throws IOException {
return new ServletOutputStream() {
#Override
public void write(int b) throws IOException {
baos.write(b);
}
};
}
#Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(baos);
}
public String getData() {
return baos.toString();
}
};
chain.doFilter(requestWrapper, responseWrapper);
response.getOutputStream().write((getCallbackParameter(httpRequest) + "(").getBytes());
response.getOutputStream().write(baos.toByteArray());
response.getOutputStream().write(");".getBytes());
response.setContentType("text/javascript");
} else {
chain.doFilter(request, response);
}
}
private String getCallbackMethod(HttpServletRequest httpRequest) {
return httpRequest.getParameter(callbackParameter);
}
private boolean isJSONPRequest(HttpServletRequest httpRequest) {
String callbackMethod = getCallbackMethod(httpRequest);
return (callbackMethod != null && callbackMethod.length() > 0);
}
private String getCallbackParameter(HttpServletRequest request) {
return request.getParameter(callbackParameter);
}
public void init(FilterConfig filterConfig) throws ServletException {
callbackParameter = filterConfig.getInitParameter("callbackParameter");
}
public void destroy() {
}
void printRequest(HttpServletRequest request) throws IOException {
{
System.out.println("--------------Headers---------------");
Enumeration en = request.getHeaderNames();
while (en.hasMoreElements()) {
String val = en.nextElement().toString();
System.out.println(val + " :");
Enumeration en1 = request.getHeaders(val);
while (en1.hasMoreElements()) {
System.out.println("\t" + en1.nextElement());
}
}
}
{
System.out.println("------------Parameters--------------");
Enumeration en = request.getParameterNames();
while (en.hasMoreElements()) {
String val = en.nextElement().toString();
System.out.println(val + " :");
String[] en1 = request.getParameterValues(val);
for (String val1 : en1) {
System.out.println("\t" + val1);
}
}
}
System.out.println("---------------BODY--------------");
BufferedReader is = request.getReader();
String line;
while ((line = is.readLine()) != null) {
System.out.println(line);
}
System.out.println("---------------------------------");
System.out.println("ContentType: " + request.getContentType());
System.out.println("ContentLength: " + request.getContentLength());
System.out.println("characterEncodings: " + request.getCharacterEncoding());
System.out.println("AuthType: " + request.getAuthType());
System.out.println("ContextPath: " + request.getContextPath());
System.out.println("Method: " + request.getMethod());
}
public static class RequestWrapper extends HttpServletRequestWrapper {
Map<String, String> headers = new HashMap<String, String>();
int contentLength;
BufferedReader reader;
public RequestWrapper(HttpServletRequest request) {
super(request);
}
public void setHeader(String key, String value) {
headers.put(key, value);
}
ByteArrayInputStream bais;
public void setBody(String body) {
bais = new ByteArrayInputStream(body.getBytes());
contentLength = body.length();
headers.put("content-length", Integer.toString(contentLength));
}
#Override
public BufferedReader getReader() throws IOException {
reader = new BufferedReader(new InputStreamReader(bais));
return reader;
}
#Override
public ServletInputStream getInputStream() throws IOException {
return new ServletInputStream() {
#Override
public int read() throws IOException {
return bais.read();
}
};
}
#Override
public String getMethod() {
return "POST";
}
private String contentType;
public void setContentType(String contentType) {
this.contentType = contentType;
headers.put("content-type", contentType);
}
#Override
public String getContentType() {
return contentType;
}
#Override
public int getContentLength() {
return contentLength;
}
#Override
public String getHeader(String name) {
String val = headers.get(name);
if (val != null) {
return val;
}
return super.getHeader(name); //To change body of overridden methods use File | Settings | File Templates.
}
#Override
public Enumeration getHeaders(final String name) {
return super.getHeaders(name);
}
#Override
public Enumeration getHeaderNames() {
final Enumeration en1 = super.getHeaderNames();
final Iterator it = headers.keySet().iterator();
return new Enumeration() {
public boolean hasMoreElements() {
return en1.hasMoreElements() || it.hasNext();
}
public Object nextElement() {
return en1.hasMoreElements() ? en1.nextElement() : (it.hasNext() ? it.next() : null);
}
};
}
#Override
public int getIntHeader(String name) {
String val = headers.get(name);
if (val == null) {
return super.getIntHeader(name);
} else {
return Integer.parseInt(val);
}
}
}
}
web.xml
<filter>
<filter-name>JSONPRequestFilter</filter-name>
<filter-class>xxxxx.JSONPRequestFilter</filter-class>
<init-param>
<param-name>callbackParameter</param-name>
<param-value>callback</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>JSONPRequestFilter</filter-name>
<url-pattern>/rest/*</url-pattern>
</filter-mapping>
An enhancement to support JSONP is scheduled to be released in RESTEasy 2.3.6 Final/3.0-beta-4 (https://issues.jboss.org/browse/RESTEASY-342). I was able to "backport" it my project which uses RESTEasy 2.3.5 by simply copying their code from GitHub.
RESTEasy automatically picks up the new provider based on the annotation. It works automatically by wrapping your results in a js callback once it sees a query parameter named "callback" in the url. This is compatible with what JQuery sends to the server for JSONP requests.
To follow on from #talawahdotnet, I'm using RestEasy 3.0.9.Final and there is support for JSONP, once enabled, any request with a "callback" query parameter will be wrapped as JSONP. I'm using JBoss so the full docs are here for other containers. Here's the steps I had to do:
In your web.xml add:
<context-param>
<param-name>resteasy.providers</param-name>
<param-value>org.jboss.resteasy.plugins.providers.jackson.JacksonJsonpInterceptor</param-value>
</context-param>
Make sure you have a WEB-INF/jboss-deployment-structure.xml with:
<jboss-deployment-structure>
<deployment>
<dependencies>
<module name="org.jboss.resteasy.resteasy-jackson-provider" services="import" annotations="true"/>
</dependencies>
</deployment>
</jboss-deployment-structure>
Make sure you have a resteasy-jackson-provider dependency in your pom.xml, something like:
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<scope>provided</scope>
</dependency>
Resteasy claims to support JSONP out of the box in 3.x version:
If you're using Jackson, Resteasy has JSONP that you can turn on by
adding the provider
org.jboss.resteasy.plugins.providers.jackson.JacksonJsonpInterceptor
(Jackson2JsonpInterceptor if you're using the Jackson2 provider) to
your deployments. If the media type of the response is json and a
callback query parameter is given, the response will be a javascript
snippet with a method call of the method defined by the callback
parameter. For example:
GET /resources/stuff?callback=processStuffResponse will produce this
response:
processStuffResponse() This supports the default
behavior of jQuery.
You can change the name of the callback parameter by setting the
callbackQueryParameter property.
However, it seems that it is broken due to RESTEASY-1168: Jackson2JsonpInterceptor does not render closing bracket
So
foo({"foo":"bar"}
is rendered instead of
foo({"foo":"bar"})
And that causes "Uncaught SyntaxError: Unexpected Identifier" error
I have submitted a pull-request with a fix and hopefully it should get into next release 3.0.12
I know that this question is pretty old, but it is shown on the first page of Google when you search for resteasy jsonp problems, so I decided to update it