Handling MaxUploadSizeExceededException can not stop uploading file - java

I want to check size of uploading files and prevent files loaded in memory entirely. I'm using CommonsMultipartFile. The uploaded file will be processed and persisted in DB. AbstractCoupleUploadController class handles incoming request that containing files:
public abstract class AbstractCoupleUploadController<T extends Serializable> extends RemoteServiceServlet implements ServletContextAware,
UploadServlet<WorkshopHistoryModel>
{
...
#RequestMapping(method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView handleRequest(#RequestParam("firstFile") CommonsMultipartFile firstFile,
#RequestParam("secondFile") CommonsMultipartFile secondFile, HttpServletRequest request, HttpServletResponse response)
{
synchronized(this)
{
initThreads();
perThreadRequest.set(request);
perThreadResponse.set(response);
}
handleUpload(firstFile,secondFile,request,response);
response.getWriter().flush();
response.flushBuffer();
return null;
}
private void handleUpload(CommonsMultipartFile firstFile, CommonsMultipartFile secondFile, HttpServletRequest request,
HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
if(firstFile.getSize() == 0 || secondFile.getSize() == 0)
{
response.getWriter().print(AppConstants.UPLOAD_ZERO_SIZE_FILE);
return;
}
// other validations
// uploading:
try
{
String content = request.getParameter(CoupleUploadPanel.CONTENT);
T model = deserialize(content);
UploadResultModel resultModel = upload(model,firstFile,secondFile); // it's implemented in UploadFileServletImpl
if(resultModel.hasCriticalError())
{
response.getWriter().print(AppConstants.UPLOAD_FAIL + "," + String.valueOf(resultModel.getWorkshopHistoryId()));
}
else
{
response.getWriter().print(AppConstants.UPLOAD_SUCCESS + "," + String.valueOf(resultModel.getWorkshopHistoryId()));
}
}
catch(ProcessRequestException e)
{
// write upload error description in response.getWriter()
}
catch(Exception e)
{
e.printStackTrace();
response.getWriter().print(AppConstants.UPLOAD_UNKOWN_ERROR);
}
}
...
}
I have a multipartResolver bean in my app-servlet.xml (file.upload.max_size=9437184), And also a maxUploadSizeExceededExceptionHandler bean for handling UploadSizeExceededExceptions:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="${file.upload.max_size}" />
</bean>
<bean id="maxUploadSizeExceededExceptionHandler" class="com.insurance.ui.server.uploadfile.MaxUploadSizeExceededExceptionHandler">
<property name="order" value="1"/>
</bean>
My maxUploadSizeExceededExceptionHandler:
public class MaxUploadSizeExceededExceptionHandler implements HandlerExceptionResolver, Ordered
{
private int order;
#Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
{
if(ex instanceof MaxUploadSizeExceededException)
{
try
{
response.getWriter().print(ErrorConstants.UPLOAD_SIZE_EXCEED + "," + (((MaxUploadSizeExceededException) ex).getMaxUploadSize()/(1024*1024)));
response.getWriter().flush();
response.flushBuffer();
return new ModelAndView();
}
catch(IOException e)
{
}
}
return null;
}
...
}
When i upload a very large file (more than ${file.upload.max_size}, about 700MB), CommonsMultipartResolver throws MaxUploadSizeExceededException immediately which I'm catching and handling it (writing in response.getWriter()) .But My problem: My browser upload-progress bar shows the file is still uploading!! Why?
UPDATE: I'm using:
Spring-*-3.0.5.RELEASE
commons-fileupload-1.1.1
and also tried:
Spring-*-3.1.2.RELEASE
commons-fileupload-1.3
and my AS:
Tomcat 6 (in development)
Jboss 7 (in production)
UPDATE 2: In the client side, i'm using GWT (I think it doesn't matter):
Uploading is started by clicking submitRequestButton:
#UiHandler("submitRequestButton")
public void submitRequestButtonClick(ClickEvent event)
{
try
{
// some validation
submitRequestButton.setEnabled(false);
uploadPanel.upload(model.getWorkshopHistoryModel()); // uploadPanel is from the CoupleUploadPanel type
}
catch(ValidationException exception)
{
// handle validation errors
}
catch(SerializationException e)
{
// handle serialization errors
}
}
I have a CoupleUploadPanel Widget for uploading (two files):
public class CoupleUploadPanel<T extends Serializable> extends FormPanel
{
public final static String CONTENT = "content";
private static final String FIRST_FILE = "firstFile";
private static final String SECOND_FILE = "secondFile";
private Hidden contentInput;
private FileUpload firstFileUploadInput;
private FileUpload secondFileUploadInput;
private SerializationStreamFactory factory;
public CoupleUploadPanel(UploadServletAsync<T> factory)
{
this(null,factory);
}
public CoupleUploadPanel(String url, UploadServletAsync<T> factory)
{
this.factory = (SerializationStreamFactory) factory;
if(url != null)
{
setAction(url);
}
init();
}
public CoupleUploadPanel(String target, String url, UploadServletAsync<T> factory)
{
super(target);
this.factory = (SerializationStreamFactory) factory;
if(url != null)
{
setAction(url);
}
init();
}
private void init()
{
setMethod("POST");
setEncoding(ENCODING_MULTIPART);
firstFileUploadInput = new FileUpload();
firstFileUploadInput.setName(CoupleUploadPanel.FIRST_FILE);
secondFileUploadInput = new FileUpload();
secondFileUploadInput.setName(CoupleUploadPanel.SECOND_FILE);
contentInput = new Hidden();
contentInput.setName(CONTENT);
VerticalPanel panel = new VerticalPanel();
panel.add(firstFileUploadInput);
panel.add(secondFileUploadInput);
panel.add(contentInput);
add(panel);
}
public void upload(T input) throws SerializationException
{
contentInput.setValue(serialize(input));
submit();
}
private String serialize(T input) throws SerializationException
{
SerializationStreamWriter writer = factory.createStreamWriter();
writer.writeObject(input);
return writer.toString();
}
}
We should pass a UploadServletAsync to CoupleUploadPanel constructor. UploadServletAsync and UploadServlet interfaces:
public interface UploadServletAsync<T extends Serializable>
{
void upload(T model, AsyncCallback<Void> callback);
}
public interface UploadServlet<T extends Serializable> extends RemoteService
{
void upload(T model);
}
So the uploadPanel will be instantiated in this way:
uploadPanel= new CoupleUploadPanel<WorkshopHistoryModel>((UploadFileServletAsync) GWT.create(UploadFileServlet.class));
uploadPanel.setAction(UploadFileServlet.URL);
And a SubmitCompeleteHandler added to uploadPanel (onSumbitComplete() will be called when submit completed and results passed to the client side):
uploadPanel.addSubmitCompleteHandler(new SubmitCompleteHandler()
{
#Override
public void onSubmitComplete(SubmitCompleteEvent event)
{
String s = event.getResults(); //contains whatever written by response.getWriter()
if(s == null)
{
// navigate to request list page
}
else
{
String[] response = s.split(",");
// based on response:
// show error messages if any error occurred in file upload
// else: navigate to upload result page
}
}
});
UploadFileServlet and UploadFileServletAsync interfaces:
public interface UploadFileServlet extends UploadServlet<WorkshopHistoryModel>
{
String URL = "**/uploadFileService.mvc";
}
public interface UploadFileServletAsync extends UploadServletAsync<WorkshopHistoryModel>
{
public static final UploadFileServletAsync INSTANCE = GWT.create(UploadFileServlet.class);
}
In the server side: the UploadFileServletImpl extends AbstractCoupleUploadController and implements the upload() method (upload process):
#RequestMapping(UploadFileServlet.URL)
public class UploadFileServletImpl extends AbstractCoupleUploadController<WorkshopHistoryModel>
{
...
#Override
protected UploadResultModel upload(WorkshopHistoryModel model, MultipartFile firstFile, MultipartFile secondFile)
throws ProcessRequestException
{
return workshopHistoryService.submitList(model.getWorkshop(),firstFile,secondFile);
}
...
}

Well, afaik Spring (a servlet and some filters) does not observe the uploading process, but only handle the result of the finished process. That's because the upload is processed by Tomcat itself (hint: there is an upload size limit option in the web.xml). So it can be possible to make an upload failure (which Spring would not be noticed) or to upload a file which is too large. And only when 2nd happend, the specific filter/interceptor could deny the process.
In my last setup, I had used Nginx as proxy in front of a Tomcat:
If your browser sends the actual file size (modern browsers do, at least IE7? or IE8? does not), than Nginx will send a 500 if the size exceeds the defined limit.
I'm not 100% sure: If the uploaded size exceeds the specified limit, Nginx will send a 500 too. That would cancel the underlaying connection to the Tomcat, too.

We use the following method:
public class MultipartResolver extends CommonsMultipartResolver {
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
String encoding = determineEncoding(request);
FileUpload fileUpload = prepareFileUpload(encoding);
try {
List fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
MultipartParsingResult parsingResult = parseFileItems(fileItems, encoding);
return new DefaultMultipartHttpServletRequest(
request, parsingResult.getMultipartFiles(), parsingResult.getMultipartParameters(), parsingResult.getMultipartParameterContentTypes());
} catch (FileUploadBase.SizeLimitExceededException ex) {
throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
}
catch (FileUploadException ex) {
throw new MultipartException("Could not parse multipart servlet request", ex);
}
}
public void cleanupMultipart(MultipartHttpServletRequest request) {
super.cleanupMultipart(request);
}
public void setFileSizeMax(long fileSizeMax) {
getFileUpload().setSizeMax(-1);
getFileUpload().setFileSizeMax(fileSizeMax);
}
}

As a first try I would call response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) in MaxUploadSizeExceededExceptionHandler.
Then I would check one or two SO questions to see whether they would contain some helpful information I could try out.
If this doesn't help I would investigate the sources of GwtUpload and see how they implemented it (or just start using their implementation).

yourfile.getFile().getSize() > Long.parseLong(153600);
This code will approve to upload a file less than 150 kb.
If it exceeds 150 kb you can send any error msg.

Related

Redirect using Java Jersey rest filters

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.

#FormParameter data becomes null after reading and setting the same data in ContainerRequestContext entityStream

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");
}

Modifying request body in Zuul pre filter not working

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.

Customizing Zuul Exception

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
}
}
}
}
}

How enable JSONP in RESTEasy?

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

Categories

Resources