HandlerExceptionResolver, MaxUploadSizeExceededException - Upload continues and error not returned immediately - spring

I am using Spring 3.1.1. I have a file upload feature and have implemented HandlerExceptionResolver to handle file size limit. I have configured the size in spring mvc xml with "maxUploadSize" attribute. My application uses spring security with open id.
I am using the code below in resolveException() of that upload controller. RestResponse is a pojo with error message and status
ModelAndView mav = new ModelAndView();
mav.setView(new MappingJacksonJsonView());
RestResponse fail_response = new RestResponse();
fail_response.setMessage("Max upload limit failure.");
fail_response.setStatus("FAIL");
mav.addObject("restResponse", fail_response);
return mav;
I can see from the logs that, the resolveException() is invoked, however the json response is not shown in the rest api client/browser. I can see the exception in the log (Maximum upload size of 10485760 bytes exceeded; nested exception is org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (30611515) exceeds the configured maximum (10485760)) immediately after the upload, but the upload still continues and after a while the json error message (available above) is shown in the browser.
I did check for this problem in stackoverflow and other portals and could not find why it is not shown or response is returned to the UI.

See this issue and this SO. If still not clear, refer to this link
and search for maxFileSize and maxRequestSize. Add same settings in your application.yml

Related

SocketTimeOutException not thrown when making a rest-call inside AWS lamda (java)

In my current project we are using aws-lambda to make a rest call to external service and consume the response. Happy path works fine but when it comes to connection-timeout or socket-timeout it is not working as expected. Little more details below
When making a call to external system and if the read-timeout scenario happens (external system connection got established but did not receive any response from the system within 15 sec) the aws lambda keeps waiting for the response till lambda-timeout (25 sec) and returns error.
But I expect the rest-call code invoked within lamda to throw the SocketTimeOutException or related one which is not happening.
Same thing, when I tried using a sample java code (using apache's http-client implementation which is what I have used in lambda) it works perfectly fine and I am getting proper exception thrown.
Initially we tried with jersey implementation for making rest-call and thought this is having issue and changed to http-client implementation, but none of them thrown the exception as it does in sample java code.
Please let me know your suggestions or solutions if faced already.
Below is the code snippet that I use in both lambda as well as sample program for making the rest call. (this whole block is wrapped under try-catch)
HttpPost post = new HttpPost(URL);
RequestJSONObject request = new RequestJSONObject();
//setting required request payload
ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writeValueAsString(request);
post.setEntity(new StringEntity(jsonStr));
post.addHeader("content-type", "application/json");
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(1000)
.setSocketTimeout(3000).build();
CloseableHttpClient httpClient =
HttpClientBuilder.create().setDefaultRequestConfig(config).build();
CloseableHttpResponse response = httpClient.execute(post);
Thanks,
Ganesh Karthik C.

Swagger does not show real error message

We are on .NET WebAPI framework and we are using swagger on top of web api for annotations and out of the box UI experience. So far, it just has been working great. However, when I return an error from WebAPI(Http 400) as following code:
return BadRequest("Some error");
However, when I do that, it seems like Swagger is not able to parse the error properly. It basically, show response 0. Which is wrong for sure because when I go to Chrome DevTools, I see that my request had a response of HTTP 400 as I expected.
How can I configure Swagger so that it is able to show the errors correctly? Or should I be throwing my errors a little bit differently to be able to see it in swagger?
You can annotate your actions like this
[ProducesResponseType(typeof(ResponseObjectTypeHere), 200)]
[ProducesResponseType(typeof(ErrorResponseObjectTypeHere), 400)]
You can also add something like this in the xml documentation if you enable swagger to read and use xml documentation
/// <response code="200">Description</response>
/// <response code="400">Description of error</response>
I used those in the .net core web api project with swagger, should be the same for regular .net web api project as well.
You can simply send the exception details to the client by enabling one of ABP's configurations (SendAllExceptionsToClients) in ***.Web.Core Module, like this:
public override void PreInitialize()
{
if (_env.EnvironmentName.ToLower() == "development")
Configuration.Modules.AbpWebCommon().SendAllExceptionsToClients = true;
}
Then you get the exception details on the client. Recommended only during development.

Adding IE browser compatibility to HtmlUnit

There is an application which works only in IE, not with any other browsers. I am using HtmlUnit to send the request by setting the mandatory field and clicking on the submit button, which is giving me Error Message -
An internal error has occurred during processing
Though i have specified browserversion while creating the webClient object, like this
WebClient webClient = null;
BrowserVersion bv = BrowserVersion.INTERNET_EXPLORER_11;
webClient = new WebClient(bv);
Can anybody please tell me what else am i missing here ?
Please let me know if there is any other way of getting this done here using HtmlUnit.

Enabling Jersey trace logging causes MaxHeaderCountExceededException

I am trying to debug my jersey 2 app on Payara 162, but on every request, after the trace information is printed I get this exception and the client gets no response:
org.glassfish.grizzly.http.util.MimeHeaders$MaxHeaderCountExceededException: Illegal attempt to exceed the configured maximum number of headers: 100
at org.glassfish.grizzly.http.util.MimeHeaders.createHeader(MimeHeaders.java:396)
at org.glassfish.grizzly.http.util.MimeHeaders.addValue(MimeHeaders.java:422)
at org.glassfish.grizzly.http.HttpHeader.addHeader(HttpHeader.java:707)
at org.glassfish.grizzly.http.server.Response.addHeader(Response.java:1177)
at org.apache.catalina.connector.Response.addHeader(Response.java:1221)
at org.apache.catalina.connector.ResponseFacade.addHeader(ResponseFacade.java:579)
at org.glassfish.jersey.servlet.internal.ResponseWriter.writeResponseStatusAndHeaders(ResponseWriter.java:165)
at org.glassfish.jersey.server.ServerRuntime$Responder$1.getOutputStream(ServerRuntime.java:701)
at org.glassfish.jersey.message.internal.CommittingOutputStream.commitStream(CommittingOutputStream.java:200)
at org.glassfish.jersey.message.internal.CommittingOutputStream.flushBuffer(CommittingOutputStream.java:305)
at org.glassfish.jersey.message.internal.CommittingOutputStream.commit(CommittingOutputStream.java:261)
at org.glassfish.jersey.message.internal.CommittingOutputStream.close(CommittingOutputStream.java:276)
at org.glassfish.jersey.message.internal.OutboundMessageContext.close(OutboundMessageContext.java:839)
at org.glassfish.jersey.server.ContainerResponse.close(ContainerResponse.java:412)
at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:784)
at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:444)
at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:434)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:329)
In my jersey I app I configured trace as so:
public class RestApplication extends ResourceConfig {
public RestApplication() {
super();
packages(true, "com.example");
register(JacksonFeature.class);
register(JsonProvider.class);
register(RolesAllowedDynamicFeature.class);
property("jersey.config.server.tracing.type", "ON_DEMAND");
property("jersey.config.server.tracing.threshold", "VERBOSE");
}
}
I enabled the logger in my logback.xml (I have configured Payara to use logback), and I see the full trace info in my server log when I enable it on demand by adding the X-Jersey-Tracing-Accept header to my request, but then I get the exception. When I don't add the header to the request everything works but of course I don't get the trace.
I'm wondering if there is anything I can change to fix this or is it a bug?
The problem is that tracing adds a header into the REST response for each event.
Grizzly imposes a limit on number of headers in the response.
Payara Server by default defines 100 as maximum number of headers in the response. You need to increase this number to allow all tracing info in the response.
To set a higher number for maximum number of headers, you need to use asadmin. There is no option to set this in the GUI admin console, it is missing in the screen to configure the HTTP protocol.
If your configuration is named server-config and the network listener is http-listener-1, then execute the following asadmin command to set it to 1000:
asadmin> set
configs.config.server-config.network-config.protocols.protocol.http-listener-1.http.max-response-headers=1000
You can use a similar command to set all Grizzly network listener propertiesoptions, just replace max-response-headers to the name of the option you want to set, using - as a word separator instead of camel case.

Catching server side ajax handling errors in browser

Let's say I have some ajax based component, whose handler in server throws for some reason an exception (e.g. programming error, can't access database). And basically server responds with internal server error or some such. How can I catch this situation in browser and display for examplen an error message somewhere.
When user clicks this link, the server will show an error page and the browser should detect based on http status code that something went wrong and somehow to react to it.
new AjaxLink<Link>("link") {
public void onClick(AjaxRequestTarget target) {
throw new RuntimeException();
}
}
See org.apache.wicket.settings.IExceptionSettings#getAjaxErrorHandlingStrategy.
There is an example of this at http://www.wicket-library.com/wicket-examples/ajax/links (failure and exception links).
Normally, Wicket Ajax classes like AjaxFallbackLink for example, have a method
updateAjaxAttributes(AjaxRequestAttributes attributes)
where you can register error handlers, that execute javascript within the browser.
Override this method, create an AjaxCallListener and call
AjaxCallListener listener = new AjaxCallListener();
listener.onFailure(ADD_JAVASCRIPT_TO_EXECUTE_HERE);
attributes.getAjaxCallListeners().add(listener);
see the documentation of
org.apache.wicket.ajax.attributes.AjaxCallListener.getFailureHandler(Component component)

Resources