HTTP 400 Bad Request : javax.ws.rs.BadRequestException - java

I create a RESTful web service and write a client to use it . but when I run it i take HTTP 400 Bad Request : javax.ws.rs.BadRequestException exeption . this is my client code :
String webserviceURI = "http://localhost:8084/fsc-access";
ClientConfig clientConfig = new ClientConfig();
Client client = ClientBuilder.newClient(clientConfig);
URI serviceURI = UriBuilder.fromUri(webserviceURI).build();
WebTarget webTarget = client.target(serviceURI);
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("plate", plate);
formData.add("startTime", start.toString());
formData.add("endTime", end.toString());
Weightings weightings = new Weightings();
weightings.getWeightings().addAll((Collection<? extends Weighting>) webTarget.path("rest").path("report").path("loadWeightingByPlate").
request().accept(MediaType.APPLICATION_XML).post(javax.ws.rs.client.Entity.form(formData), Weightings.class));
and this is my web Service :
#Path("/report")
public class WeightingRESTfulService {
#POST
#Path("/loadWeightingByPlate")
#Produces(MediaType.APPLICATION_XML)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Weightings LoadWeightingInSpecTimeInSpecPlate(
#FormParam("plate") String plate,
#FormParam("startTime") String _startTime,
#FormParam("endTime") String _endTime,
#Context HttpServletRequest req) {
Long startTime = new Long(_startTime);
Long endTime = new Long(_endTime);
try {
Weightings weightings = new Weightings();
weightings.getWeightings().addAll(Weighting.LoadWeightingInSpecTimeInSpecPlate(startTime, endTime, plate));
System.out.println("no error");
return weightings;
} catch (Exception ex) {
System.out.println("Exception = " + ex);
return null;
}
}
}
can any one help me to use this web Service ?
there is some warning :
21-Aug-2015 23:18:11.797 WARNING [http-nio-8084-exec-123] org.glassfish.jersey.servlet.WebComponent.filterFormParameters A servlet request to the URI http://localhost:8084/fsc-access/rest/report/loadWeightingByPlate contains form parameters in the request body but the request body has been consumed by the servlet or a servlet filter accessing the request parameters. Only resource methods using #FormParam will work as expected. Resource methods consuming the request body by other means will not work as expected.
and there is som exeprions :
Exception in thread "C3P0PooledConnectionPoolManager[identityToken->1hge1379bmmvkmpse6n4w|7936e088]-AdminTaskTimer" java.lang.IllegalStateException: Can't overwrite cause with java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already. Could not load com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask. The eventual following stack trace is caused by an error thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access, and has no functional impact.
at java.lang.Throwable.initCause(Throwable.java:457)
at org.apache.catalina.loader.WebappClassLoader.checkStateForClassLoading(WebappClassLoader.java:1335)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1216)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1177)
at com.mchange.v2.resourcepool.BasicResourcePool.destroyResource(BasicResourcePool.java:1040)
at com.mchange.v2.resourcepool.BasicResourcePool.removeResource(BasicResourcePool.java:1507)
at com.mchange.v2.resourcepool.BasicResourcePool.removeResource(BasicResourcePool.java:1477)
at com.mchange.v2.resourcepool.BasicResourcePool.cullExpired(BasicResourcePool.java:1565)
at com.mchange.v2.resourcepool.BasicResourcePool.access$1900(BasicResourcePool.java:44)
at com.mchange.v2.resourcepool.BasicResourcePool$CullTask.run(BasicResourcePool.java:2089)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
Caused by: java.lang.ClassNotFoundException
at org.apache.catalina.loader.WebappClassLoader.checkStateForClassLoading(WebappClassLoader.java:1334)
... 10 more
Exception in thread "C3P0PooledConnectionPoolManager[identityToken->1hge1379bmmw228sz1sso|53826b99]-AdminTaskTimer" java.lang.IllegalStateException: Can't overwrite cause with java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already. Could not load com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask. The eventual following stack trace is caused by an error thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access, and has no functional impact.
at java.lang.Throwable.initCause(Throwable.java:457)
at org.apache.catalina.loader.WebappClassLoader.checkStateForClassLoading(WebappClassLoader.java:1335)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1216)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1177)
at com.mchange.v2.resourcepool.BasicResourcePool.destroyResource(BasicResourcePool.java:1040)
at com.mchange.v2.resourcepool.BasicResourcePool.removeResource(BasicResourcePool.java:1507)
at com.mchange.v2.resourcepool.BasicResourcePool.removeResource(BasicResourcePool.java:1477)
at com.mchange.v2.resourcepool.BasicResourcePool.cullExpired(BasicResourcePool.java:1565)
at com.mchange.v2.resourcepool.BasicResourcePool.access$1900(BasicResourcePool.java:44)
at com.mchange.v2.resourcepool.BasicResourcePool$CullTask.run(BasicResourcePool.java:2089)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
Caused by: java.lang.ClassNotFoundException
at org.apache.catalina.loader.WebappClassLoader.checkStateForClassLoading(WebappClassLoader.java:1334)
... 10 more
loggingfilter :
22-Aug-2015 00:32:32.969 INFO [http-nio-8084-exec-37] org.glassfish.jersey.filter.LoggingFilter.log 1 * Sending client request on thread http-nio-8084-exec-37
1 > POST http://localhost:8084/fsc-access/rest/report/loadWeightingByPlate
1 > Accept: application/xml
1 > Content-Type: application/x-www-form-urlencoded
22-Aug-2015 00:32:33.015 INFO [http-nio-8084-exec-37] org.glassfish.jersey.filter.LoggingFilter.log 2 * Client response received on thread http-nio-8084-exec-37
2 < 200
2 < Content-Length: 1026
2 < Content-Type: application/xml
2 < Date: Fri, 21 Aug 2015 19:54:48 GMT
2 < Server: Apache-Coyote/1.1

Your resource is returning an instance of Weightings, so you just need to cast it, you don't need to do the addAll()
Weightings weightings = new Weightings();
weightings.getWeightings().addAll((Collection<? extends Weighting>) webTarget.path("rest").path("report").path("loadWeightingByPlate").
request().accept(MediaType.APPLICATION_XML).post(javax.ws.rs.client.Entity.form(formData), Weightings.class));
Should be:
Weightings weightings = (Weightings) webTarget.path("rest").path("report").path("loadWeightingByPlate").
request().accept(MediaType.APPLICATION_XML).post(javax.ws.rs.client.Entity.form(formData), Weightings.class));
It won't fix your 400 exception, but you'll get a ClassCastException without it.

Related

VMware vCenter API exception:The request refers to an unexpected or unknown type?

The console shows exception:"The request refers to an unexpected or unknown type" when I create a cluster.please help me. code shows the following:
vimPort.login(serviceContent.getSessionManager(),
userName, password, null);
ManagedObjectReference data = getDatacenterByName2("Datacenter");
String name = "cluster_hi";
ClusterConfigSpec spec = new ClusterConfigSpec();
ClusterDasConfigInfo value = new ClusterDasConfigInfo();
value.setAdmissionControlEnabled(true);
value.setEnabled(true);
spec.setDasConfig(value);
vimPort.createCluster(data, name, spec);
Exception in thread "main" javax.xml.ws.soap.SOAPFaultException:
The request refers to an unexpected or unknown type.
at com.sun.xml.internal.ws.fault.SOAP11Fault.getProtocolException(SOAP11Fault.java:178)
at com.sun.xml.internal.ws.fault.SOAPFaultBuilder.createException(SOAPFaultBuilder.java:119)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:108)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:78)
at com.sun.xml.internal.ws.client.sei.SEIStub.invoke(SEIStub.java:129)
at com.sun.proxy.$Proxy35.createCluster(Unknown Source)
at com.huawei.robo.common.vcenterclient.VcenterClientImpl.main(VcenterClientImpl.java:162)

Spring cloud kafka and avro serialization issue

I use spring-cloud-stream-schema to read avro messages from kafka. I configured input channel in MessagesChannels:
#Input("topicName1")
SubscribableChannel fromInput1();
I have configuration file like that:
#Configuration
#EnableBinding(MessagesChannels.class)
#EnableSchemaRegistryClient
public class MessageConfiguration {
#Bean
public MessageConverter topic1MessageConverter() throws IOException {
return new AvroSchemaMessageConverter(MimeType.valueOf("avro/bytes"));
}
}
And my consumer is called with
fromInput1().subscribe(this::onMessage);
void onMessage(Message message) {
}
When I actually sent message I got this error:
nested exception is java.lang.ClassCastException:
org.apache.avro.generic.GenericData$Record cannot be cast to [B
Actually raw bytes are parsed correctly into org.apache.avro.generic.GenericData$Record. But spring requires Message class. How to cast GenericData$Record to Message or how to cast GenericData$Record directly to generated by avro-tools class?
More details:
2017-03-06 11:23:10.695 ERROR 19690 --- [afka-listener-1] o.s.kafka.listener.LoggingErrorHandler : Error while processing: ConsumerRecord(topic = topic1, partition = 0, offset = 7979, CreateTime = 1488784987569, checksum = 623709057, serialized key size = -1, serialized value size = 36, key = null, value = {"foor": "bar"})
org.springframework.messaging.MessageHandlingException: error occurred in message handler [org.springframework.cloud.stream.binder.AbstractMessageChannelBinder$ReceivingHandler#4bf9d802]; nested exception is java.lang.ClassCastException: org.apache.avro.generic.GenericData$Record cannot be cast to [B
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:139)
at org.springframework.integration.channel.FixedSubscriberChannel.send(FixedSubscriberChannel.java:70)
at org.springframework.integration.channel.FixedSubscriberChannel.send(FixedSubscriberChannel.java:64)
I think you need to set the contentType for the incoming message channel to use application/*+avro as specified here

Unable to find a MessageBodyReader of content-type application/octet-stream

I'm struggling with an REST-Service written with JAX-RS.
I want to create and bind a client with the following code:
final String DEFAULT_RESOURCE_URL = "http://someURL:8180/";
try {
ResteasyClient client = new ResteasyClientBuilder().build().register(ClientResponseLoggingFilter.class);
ResteasyWebTarget target = client.target(DEFAULT_RESOURCE_URL).path(
"service/document/getdrawingbrowser/{documentId}/{documentType}/{partDocumentId}/{documentVersion}/{userName}");
HashMap<String, Object> keyValuesMap = new HashMap<String, Object>();
keyValuesMap.put("documentId", "xxxx");
keyValuesMap.put("documentType", "yyy");
keyValuesMap.put("partDocumentId", "000");
keyValuesMap.put("documentVersion", "000");
keyValuesMap.put("userName", "user");
Builder responseBuilder = target.resolveTemplates(keyValuesMap).request();
Response response = responseBuilder.get();
if (response.getStatus() == 200) {
byte[][] documents = response.readEntity(byte[][].class);
for (int i = 0; i < documents.length; i++) {
displayProperties(documents[i]);
}
} else {
Object entity = response.getEntity();
System.out.println(entity);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
The REST-Service responds correctly I guess:
status: 200
date: Mon Sep 14 10:53:02 CEST 2015
last-modified: null
location: null
headers:
Connection :keep-alive,
Content-Disposition :attachment; filename=someFile.pdf,
Content-Type :application/octet-stream,
Date :Mon, 14 Sep 2015 08:53:02 GMT,
Server :WildFly/8,
Transfer-Encoding :chunked,
X-Powered-By :Undertow/1,
media-type: application
But in line 102 byte[][] documents = response.readEntity(byte[][].class); I'm getting an javax.ws.rs.ProcessingException which says:
javax.ws.rs.ProcessingException: Unable to find a MessageBodyReader of content-type application/octet-stream and type class [[B
at org.jboss.resteasy.core.interception.ClientReaderInterceptorContext.throwReaderNotFound(ClientReaderInterceptorContext.java:39)
at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.getReader(AbstractReaderInterceptorContext.java:73)
at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.proceed(AbstractReaderInterceptorContext.java:50)
at org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor.aroundReadFrom(GZIPDecodingInterceptor.java:59)
at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.proceed(AbstractReaderInterceptorContext.java:53)
at org.jboss.resteasy.client.jaxrs.internal.ClientResponse.readFrom(ClientResponse.java:248)
at org.jboss.resteasy.client.jaxrs.internal.ClientResponse.readEntity(ClientResponse.java:181)
at org.jboss.resteasy.specimpl.BuiltResponse.readEntity(BuiltResponse.java:217)
at DocumentTest.main(DocumentTest.java:102)
I have tried several .jar files and some approaches from here and here, but sadly, none of them worked out...
Any ideas?
Try to change you Content-Type to application/pdf.

Promise timeouts and WS.get Timeout in PlayFramework 2.1 JAVA

I am trying to access to an URL using WS on Play Framework 2.1 using JAVA api.
Here is what I want:
Some where in the code, start a WS request using WS.get() (I set timeout 1000ms)
If WS.get times out or another exception happens, I don't want my Promise throw an exception (since my flow reqiures it that way) So I use Promise.recover() to wrap that promise with another. Which returns a null Reponse object in case of failures.
Some where else in code I want to "get" my Response. I wait for 5000ms but what I get is java.util.concurrent.TimeoutException: Futures timed out after [5000 milliseconds]
How? WS.get() timesout after 1000ms and since it throws an java.util.concurrent.TimeoutException: No response received after 1000 it is catched by my recover function. It returns a null response instead of an exception.
So promise is "completed" after 1000ms at most. Why it times out and throws an exception after 5000 ms?
Code:
Logger.info("Fetch started: " + new Date().toString());
Promise<WS.Response> p1 = WS.url("http://athena.ics.forth.gr:9090/RDF/VRP/Examples/tap.rdf").setTimeout(1000).get();
Promise<WS.Response> p2 = p1.recover(new Function<Throwable, WS.Response>() {
#Override
public Response apply(Throwable a) throws Throwable {
Logger.error("Promise thrown an exception so I will return null. " + new Date().toString() + " " + System.currentTimeMillis(), a);
return null;
}
});
try {
/* This should return null or valid response but shouldn't throw an exception */
Response r = p2.get(5000L);
Logger.info(r.toString());
} catch (Exception e) {
/* Sholdn't happen! */
Logger.error("Outer exception: " + " " + System.currentTimeMillis(), e);
}
Logger.error("Fetch finished: " + new Date().toString() + " " + System.currentTimeMillis());
Output I get:
[info] application - Fetch started: Tue Mar 19 10:04:42 EET 2013
[error] application - Outer exception: 1363680287626
java.util.concurrent.TimeoutException: Futures timed out after [5000 milliseconds]
at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:96) ~[scala-library.jar:na]
at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:58) ~[scala-library.jar:na]
at scala.concurrent.Await$$anonfun$ready$1.apply(package.scala:86) ~[scala-library.jar:na]
at scala.concurrent.Await$$anonfun$ready$1.apply(package.scala:86) ~[scala-library.jar:na]
at akka.dispatch.MonitorableThreadFactory$AkkaForkJoinWorkerThread$$anon$3.block(ThreadPoolBuilder.scala:173) ~[akka-actor_2.10.jar:na]
at scala.concurrent.forkjoin.ForkJoinPool.managedBlock(ForkJoinPool.java:2803) [scala-library.jar:na]
[error] application - Fetch finished: Tue Mar 19 10:04:47 EET 2013 1363680287627
[error] application - Promise thrown an exception so I will return null. Tue Mar 19 10:04:47 EET 2013 1363680287627
java.util.concurrent.TimeoutException: No response received after 1000
at com.ning.http.client.providers.netty.NettyAsyncHttpProvider$ReaperFuture.run(NettyAsyncHttpProvider.java:1809) ~[async-http-client.jar:na]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) ~[na:1.7.0_11]
at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:351) ~[na:1.7.0_11]
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:178) ~[na:1.7.0_11]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178) ~[na:1.7.0_11]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) ~[na:1.7.0_11]
Even I wait for promise2 and promise2 is "recover wrapped promise1" recover function runs AFTER exception is thrown.

grizzly2 jersey REST app returns 404 on first request, then success on all others

I have a very simple Java REST app that uses grizzly2 (jersey-grizzly2 1.12) and jersey (jersey-bundle 1.12)
When I make my first http request, I get a 404 response (but the mapped method still executes on the server). If I make the identical request again, then I get the expected 200 response.
The crazy part is, that even for the 404 error, the mapped method still executes.
Perhaps there is a bug? Or I've misconfigured my server? This is the first time i've tried grizzly2, so any insight is welcome!
I start the server like this:
final ResourceConfig rc = new DefaultResourceConfig(
TestResource.class
);
rc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true);
rc.getFeatures().put(ResourceConfig.FEATURE_TRACE, true);
URI path = UriBuilder.fromPath(baseUri).build();
HttpServer httpServer = GrizzlyServerFactory.createHttpServer(path, rc);
httpServer.start();
And my resource looks like this:
#Path("/test")
public class TestResource {
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("go")
public Integer startSomethingElse() {
return new Integer(4);
}
}
And my sample connection examples:
C:\Users\Paul>curl -v -H "Accept: application/json" http://10.0.0.156:9998/test/go
* About to connect() to 10.0.0.156 port 9998 (#0)
* Trying 10.0.0.156... connected
> GET /test/go HTTP/1.1
> User-Agent: curl/7.23.1 (x86_64-pc-win32) libcurl/7.23.1 OpenSSL/0.9.8r zlib/1.2.5
> Host: 10.0.0.156:9998
> Accept: application/json
>
< HTTP/1.1 404 Not Found
< Content-Type: text/html
< Date: Tue, 12 Jun 2012 17:49:24 GMT
< Content-Length: 1061
<
<html><head><title>Grizzly/2.1</title><style><!--div.header {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#003300;font-size:22px;-moz-border-radius-topleft: 10px;border-top-left-radius: 10px;-moz-border-radius-topright: 10px;border-top-right-radius: 10px;padding-left: 5px}div.body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:#FFFFCC;font-size:16px;padding-top:10px;padding-bottom:10px;padding-left:10px}div.footer {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#666633;font-size:14px;-moz-border-radius-bottomleft: 10px;border-bottom-left-radius: 10px;-moz-border-radius-bottomright: 10px;border-bottom-right-radius: 10px;padding-left: 5px}BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;}B {font-family:Tahoma,Arial,sans-serif;color:black;}A {color : black;}HR {color : #999966;}--></style> </head><body><div class="header">Not Found</div><div class="body">Resource identified by path '/test/go', does not exist.</div><div class="footer">Grizzly/2.1</div></body></html>* Connection #0 to host 10.0.0.156 left intact
Closing connection #0
Then the second try (exact same request, immediately after the first)
C:\Users\Paul>curl -v -H "Accept: application/json" http://10.0.0.156:9998/test/go
About to connect() to 10.0.0.156 port 9998 (#0)
Trying 10.0.0.156... connected
> GET /test/go HTTP/1.1
> User-Agent: curl/7.23.1 (x86_64-pc-win32) libcurl/7.23.1 OpenSSL/0.9.8r zlib/1.2.5
> Host: 10.0.0.156:9998
> Accept: application/json
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< X-Jersey-Trace-000: accept root resource classes: "/test/go"
< X-Jersey-Trace-001: match path "/test/go" -> "/application\.wadl(/.*)?", "/test(/.*)?"
< X-Jersey-Trace-002: accept right hand path java.util.regex.Matcher[pattern=/test(/.*)? region=0,8 lastmatch=/test/go]: "/test/go" -> "/test" : "/go"
< X-Jersey-Trace-003: accept resource: "test" -> #Path("/test") com.subserveo.skyhook.http.resource.TestResource#30813486
< X-Jersey-Trace-004: match path "/go" -> "/go2(/)?", "/go(/)?", ""
< X-Jersey-Trace-005: accept right hand path java.util.regex.Matcher[pattern=/go(/)? region=0,3 lastmatch=/go]: "/go" -> "/go" : ""
< X-Jersey-Trace-006: accept sub-resource methods: "test" : "/go", GET -> com.subserveo.skyhook.http.resource.TestResource#30813486
< X-Jersey-Trace-007: matched sub-resource method: #Path("/go") public java.lang.Integer com.subserveo.skyhook.http.resource.TestResource.startSomethingElse()
< X-Jersey-Trace-008: matched message body writer: java.lang.Integer#4, "application/json" -> com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy#576f8789
< Date: Tue, 12 Jun 2012 17:49:26 GMT
< Transfer-Encoding: chunked
<
4* Connection #0 to host 10.0.0.156 left intact
* Closing connection #0

Categories

Resources