file uploading issues in open-shift .multipart-form data in jboss7 - file-upload

My rest method for accepting multipart-form data is not working in my openshift
projects deployed in jboss7. 405 status code is coming but it is working fine in my
localhost server.
#POST
#Path("/file")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response addFile(final #Context UriInfo uriInfo,#FormDataParam("file")
InputStream uploadedFile, #FormDataParam("file") FormDataContentDisposition
fileDetail)
{
try {
AddFileRequest rqst = new AddFileRequest();
if(uploadedFile!=null){
rqst.setUploadedFile(uploadedFile);
rqst.setFileName(fileDetail.getFileName());}
addFile(rqst);
return Response.ok().build();
} catch (Exception e) {
e.printStackTrace();
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}

Related

POST service in ASP.NET Core WebAPI

I'm trying to write very simple multi-platform app (iOS & Android) in visual studio. This app uses web service, uploaded on my web hosting.
This is code that call WebAPI (get & post):
async void post_async(object sender, System.EventArgs e)
{
Console.WriteLine("POST");
try
{
HttpClient httpClient = new HttpClient();
var BaseAddress = "https://mywebsite";
var response = await httpClient.PostAsync(BaseAddress, null);
var message = await response.Content.ReadAsStringAsync();
Console.WriteLine($"RESPONSE: " + message);
}
catch (Exception er)
{
Console.WriteLine($"ERROR: " + er.ToString());
}
}
async void get_async(object sender, System.EventArgs e)
{
try
{
HttpClient httpClient = new HttpClient();
var BaseAddress = "https://mywebsite";
var response = await httpClient.GetAsync(BaseAddress);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine($"RESPONSE: " + content);
}
}
catch (Exception er)
{
Console.WriteLine($"ERROR: " + er.ToString());
}
}
This is very simple code for Web Api:
[HttpGet]
public ActionResult<string> Get()
{
return "get method ok";
}
[HttpPost]
public ActionResult<string> Post()
{
return "post method ok";
}
Very strange issue because for every void I always obtain "get method ok". So "get" is ok, but I don't understand why I cannot call post method.
I tried to use Postman: same issue.
I'm using this very simple code:
[ActionName("getmet")]
public ActionResult<string> getmet()
{
return "get method ok";
}
[ActionName("postmet")]
public ActionResult<string> postmet()
{
return "post method ok";
}
Now of course I can call https://mywebsite/getmet or postmet and it works using postman.
If I use [HttpPost] for postmet method, on Postman I get "404 not found". Why?
var BaseAddress = "https://mywebsite"; //
URL hits get method by difualt, thats means works as https://mywebsite/Get where as your actual post method URL is https://mywebsite/Post
instead of calling a different method use code like below.
[HttpPost]
[HttpGet]
public ActionResult<string> Get()
{
return "method ok";
}
OR you can use API ROUTE
OR
[AcceptVerbs(HttpVerbs.Get|HttpVerbs.Post)]

Quarkus ExceptionMapper does not handle WebApplicationException

I'm trying to understand if this is a feature or a bug... :-)
For the below controller and exception mapper, for a rest client that will fail with a 401 response, I would expect the exception handler to be invoked for both cases. However it's not invoked for the WebApplicationException. Why is that and how are you meant to register an exception handler for them cases. This is using Quarkus version 0.21.2
#Path("/failable")
public class FailableResource {
#Inject
#RestClient
private SomeHttpClient httpClient;
#GET
#Path("fails")
#Produces(MediaType.TEXT_PLAIN)
public String fails() {
try {
return httpClient.someQuery();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
#GET
#Path("works")
#Produces(MediaType.TEXT_PLAIN)
public String works() {
try {
return httpClient.someQuery();
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("Not a WebApplicationException");
}
}
}
And the ExceptionMapper
#Provider
public class HandleMySillyError implements ExceptionMapper<Throwable> {
#Override
public Response toResponse(Throwable e) {
e.printStackTrace();
return Response.ok("Some handled response").build();
}
}
I found out when running in quarkus:dev mode the exception mapper is not invoked. It seems that this is caused by an exception mapper from quarkus that is only used in DEV mode (see https://github.com/quarkusio/quarkus/issues/7883).
I launched my code local as normal a normal java program, causing my exception handler to work as expected. Also when running the code on Openshift, my custom exception mapper is used as well.
note: I used quarkus version 1.8.3

WebAPI 2.0 call monitoring

Using ASP.NET WebAPI 2.0 and have a conceptual issue.
Would like to keep a global record of any API that is called by any user/ client and it would be awesome if this was stored in the database.
What would be the best mechanism to accomplish this?
I' using a DelegatingHandler for a long time in several projects which is doing just fine.
public class ApiCallLogHandler : DelegatingHandler {
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
var started = DateTime.UtcNow;
HttpResponseMessage response = null;
Exception baseException = null;
try {
response = await base.SendAsync(request, cancellationToken);
} catch(Exception exception) {
CommonLogger.Logger.LogError(exception);
baseException = exception;
}
try {
var callModel = await GetCallModelAsync(request, response);
if(baseException != null)
callModel.Exception = baseException
callModel.ExecutionTime = (DateTime.UtcNow - started).ToString();
await CommonLogger.Logger.LogApiCallAsync(callModel);
} catch (Exception exception) {
CommonLogger.Logger.LogError(exception);
}
return response;
}
private async Task<ApiCallModel> GetCallModelAsync(HttpRequestMessage request, HttpResponseMessage response) {
// parse request and response and create a model to store in database...
}
}
By this approach you are able to track all requests, exceptions during execution, and even full-response of each API call.
ApiCallModel is just a simple POCO class which you should fill it with your required data from request and response.
CommonLogger.Logger.* is your logging mechanism.
And, you have to register the handler with this snippet:
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
config.MessageHandlers.Add(new ApiCallLogHandler());
}
}

Is ContainerResponseFilter executed if an exception is thrown somewhere in a controller?

I have a RestEasy based service in which I am doing some cleanup work in a ContainerResponseFilter. The problem is that if an unknown runtime exception (i.e. an exception for which I do not have a mapper) is thrown by a resource, the ContainerResponseFilter is never executed.
Is this the expected behavior? Is there a workaround to this? I was looking at the following question (answer by Jonas):
How should I log uncaught exceptions in my RESTful JAX-RS web service?
and that made it seem like the ContainerResponseFilter is executed even when an exception is thrown in the controller?
Am I missing something?
Didn't work for me either. This claims it should work: https://github.com/Graylog2/graylog2-server/issues/1826
I didn't want to investigate further, and simply use a plain old javax.servlet.Filter, but of course there it's hard to set the reponses-headers (after chain.doFilter(), ... grr..
So used a Spring solution:
public static class MyFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.setHeader("MyHeader", "MyValue");
filterChain.doFilter(request, response);
}
}
Base on the source code of SynchronousDispatcher in RestEasy.
protected void writeResponse(HttpRequest request, HttpResponse response, Response jaxrsResponse) {
try {
ServerResponseWriter.writeNomapResponse((BuiltResponse)jaxrsResponse, request, response, this.providerFactory);
} catch (Exception var5) {
this.writeException(request, response, var5);
}
}
public void writeException(HttpRequest request, HttpResponse response, Throwable e) {
if (response.isCommitted()) {
throw new UnhandledException("Response is committed, can't handle exception", e);
} else {
Response handledResponse = (new ExceptionHandler(this.providerFactory, this.unwrappedExceptions)).handleException(request, e);
if (handledResponse == null) {
throw new UnhandledException(e);
} else {
try {
ServerResponseWriter.writeNomapResponse((BuiltResponse)handledResponse, request, response, this.providerFactory);
} catch (Exception var6) {
throw new UnhandledException(var6);
}
}
}
}
ContainerResponseFilter will not execute.
If you want to set headers when exceptions happen, you need an exception handler to deal with it.

Spring for android RestTemplate object instantiation failed

I am using spring for android in order to communicate with an existing RestAPI service. I am following this tutorial :
http://spring.io/guides/gs/consuming-rest-android/
I already have my android app, and I integrated this HttpRequestTask in one of my activities
private class HttpRequestTask extends AsyncTask<Void, Void, Greeting> {
protected Greeting doInBackground(Void... params) {
try {
final String url = "http://rest-service.guides.spring.io/greeting";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Greeting greeting = restTemplate.getForObject(url, Greeting.class);
return greeting;
} catch (Exception e) {
Log.e("MainActivity", e.getMessage(), e);
}
return null;
}
protected void onPostExecute(Greeting greeting) {
....
}
}
and I then call execute method within the onStart method
#Override
protected void onStart() {
super.onStart();
new HttpRequestTask().execute();
}
Once I access this activity, the app crashes. I debuged it and found that the RestTemplate object fails in the instantiation line:
RestTemplate restTemplate = new RestTemplate();
I'am using spring 1.0.1.RELEASE core and rest jars.
The problem was that the added external jars are not deployed with the app at runtime, this link solves this issue:
How can I use external JARs in an Android project?