I am new in Rest API's. I am trying to run this test function in IntelliJ IDEA to test OMDB API:
#Test
public void shouldNotGetResponseWithoutApiKey(){
Response response = RestAssured.given()
.queryParam("t", "Harry Potter")
.get("http://www.omdbapi.com")
.then()
.statusCode(401)
.extract().response();
assertThat(response.getBody().jsonPath().getString("Error"), Matchers.containsString(errorMessage));
}
Here the logic is: I want this test to give status code 401 since the API Key is not given to the Rest Assured. It's very straight forward. But I receive this error:
io.restassured.internal.http.HttpResponseException: Unauthorized
at io.restassured.internal.http.HTTPBuilder.defaultFailureHandler(HTTPBuilder.java:627)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:107)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:323)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1268)
...
I searched for the error but I couldn't find a solution. I would be very happy if someone can direct me.
Thanks a lot 🙌
Related
Working on a project where there is a frontend (React) and a backend (Java/Quarkus). Keycloak is used as the auth tool. It is configured with a realm that has a public client on it. This allows the user to login via the browser and then make api requests to the backend with a bearer token attached to the request.
Running into a problem where we want to add users to our application. This means we also need to add them to keycloak. Doing this programatically, this is in its own mini module and it uses the keycloak-admin-client library.
I initiate the instance with
instance = KeycloakBuilder.builder()
.serverUrl(props.getProperty(PropertyConstants.SERVER_URL))
.realm(props.getProperty(PropertyConstants.REALM))
.grantType(OAuth2Constants.PASSWORD)
.clientId(props.getProperty(PropertyConstants.CLIENT_ID))
.username(props.getProperty(PropertyConstants.USERNAME))
.password(props.getProperty(PropertyConstants.PASSWORD))
.build();
realmResource = instance.realm(props.getProperty(PropertyConstants.REALM));
usersResource = realmResource.users();
UserRepresentation user = createUserRep();
Response response = usersResource.create(user);
The stacktrace is;
org.jboss.resteasy.spi.UnhandledException: javax.ws.rs.ProcessingException: RESTEASY004655: Unable to invoke request: javax.ws.rs.ProcessingException: RESTEASY003215: could not find writer for content-type application/x-www-form-urlencoded type: javax.ws.rs.core.Form$1
at org.jboss.resteasy.core.ExceptionHandler.handleApplicationException(ExceptionHandler.java:106)
at org.jboss.resteasy.core.ExceptionHandler.handleException(ExceptionHandler.java:372)
at org.jboss.resteasy.core.SynchronousDispatcher.writeException(SynchronousDispatcher.java:218)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:519)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:261)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:161)
at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364)
at org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:164)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:247)
at io.quarkus.resteasy.runtime.standalone.RequestDispatcher.service(RequestDispatcher.java:73)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.dispatch(VertxRequestHandler.java:136)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.access$000(VertxRequestHandler.java:40)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler$1.run(VertxRequestHandler.java:97)
at io.quarkus.runtime.CleanableExecutor$CleaningRunnable.run(CleanableExecutor.java:231)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:2046)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1578)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1452)
at org.jboss.threads.DelegatingRunnable.run(DelegatingRunnable.java:29)
at org.jboss.threads.ThreadLocalResettingRunnable.run(ThreadLocalResettingRunnable.java:29)
at java.base/java.lang.Thread.run(Thread.java:829)
at org.jboss.threads.JBossThread.run(JBossThread.java:479)
Caused by: javax.ws.rs.ProcessingException: RESTEASY004655: Unable to invoke request: javax.ws.rs.ProcessingException: RESTEASY003215: could not find writer for content-type application/x-www-form-urlencoded type: javax.ws.rs.core.Form$1
at org.jboss.resteasy.client.jaxrs.engines.ManualClosingApacheHttpClient43Engine.invoke(ManualClosingApacheHttpClient43Engine.java:287)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:488)
at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invokeSync(ClientInvoker.java:149)
at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invoke(ClientInvoker.java:112)
at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientProxy.invoke(ClientProxy.java:76)
at com.sun.proxy.$Proxy89.grantToken(Unknown Source)
at org.keycloak.admin.client.token.TokenManager.grantToken(TokenManager.java:90)
at org.keycloak.admin.client.token.TokenManager.getAccessToken(TokenManager.java:70)
at org.keycloak.admin.client.token.TokenManager.getAccessTokenString(TokenManager.java:65)
at org.keycloak.admin.client.resource.BearerAuthFilter.filter(BearerAuthFilter.java:52)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.filterRequest(ClientInvocation.java:683)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:485)
at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invokeSync(ClientInvoker.java:149)
at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invoke(ClientInvoker.java:112)
at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientProxy.invoke(ClientProxy.java:76)
at com.sun.proxy.$Proxy96.create(Unknown Source)
at com.demservices.KeycloakWrapper.addUser(KeycloakWrapper.java:56)
at com.demservices.services.UserService.addUser(UserService.java:27)
at com.demservices.services.UserService_Subclass.addUser$$superaccessor2(UserService_Subclass.zig:492)
at com.demservices.services.UserService_Subclass$$function$$2.apply(UserService_Subclass$$function$$2.zig:33)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:54)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:127)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:100)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired.doIntercept(TransactionalInterceptorRequired.java:32)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.intercept(TransactionalInterceptorBase.java:53)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired.intercept(TransactionalInterceptorRequired.java:26)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired_Bean.intercept(TransactionalInterceptorRequired_Bean.zig:340)
at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:41)
at io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:32)
at com.demservices.services.UserService_Subclass.addUser(UserService_Subclass.zig:440)
at com.demservices.services.UserService_ClientProxy.addUser(UserService_ClientProxy.zig:251)
at com.demservices.controllers.UserController.createNewUser(UserController.java:35)
at com.demservices.controllers.UserController_Subclass.createNewUser$$superaccessor1(UserController_Subclass.zig:234)
at com.demservices.controllers.UserController_Subclass$$function$$1.apply(UserController_Subclass$$function$$1.zig:33)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:54)
at io.quarkus.hibernate.validator.runtime.interceptor.AbstractMethodValidationInterceptor.validateMethodInvocation(AbstractMethodValidationInterceptor.java:69)
at io.quarkus.hibernate.validator.runtime.jaxrs.JaxrsEndPointValidationInterceptor.validateMethodInvocation(JaxrsEndPointValidationInterceptor.java:35)
at io.quarkus.hibernate.validator.runtime.jaxrs.JaxrsEndPointValidationInterceptor_Bean.intercept(JaxrsEndPointValidationInterceptor_Bean.zig:392)
at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:41)
at io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:32)
at com.demservices.controllers.UserController_Subclass.createNewUser(UserController_Subclass.zig:191)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:170)
at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:130)
at org.jboss.resteasy.core.ResourceMethodInvoker.internalInvokeOnTarget(ResourceMethodInvoker.java:643)
at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTargetAfterFilter(ResourceMethodInvoker.java:507)
at org.jboss.resteasy.core.ResourceMethodInvoker.lambda$invokeOnTarget$2(ResourceMethodInvoker.java:457)
at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364)
at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:459)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:419)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:393)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:68)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:492)
... 20 more
Caused by: javax.ws.rs.ProcessingException: RESTEASY003215: could not find writer for content-type application/x-www-form-urlencoded type: javax.ws.rs.core.Form$1
at org.jboss.resteasy.core.interception.jaxrs.ClientWriterInterceptorContext.throwWriterNotFoundException(ClientWriterInterceptorContext.java:50)
at org.jboss.resteasy.core.interception.jaxrs.AbstractWriterInterceptorContext.getWriter(AbstractWriterInterceptorContext.java:302)
at org.jboss.resteasy.core.interception.jaxrs.AbstractWriterInterceptorContext.syncProceed(AbstractWriterInterceptorContext.java:240)
at org.jboss.resteasy.core.interception.jaxrs.AbstractWriterInterceptorContext.proceed(AbstractWriterInterceptorContext.java:224)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.writeRequestBody(ClientInvocation.java:440)
at org.jboss.resteasy.client.jaxrs.engines.ManualClosingApacheHttpClient43Engine.writeRequestBodyToOutputStream(ManualClosingApacheHttpClient43Engine.java:589)
at org.jboss.resteasy.client.jaxrs.engines.ManualClosingApacheHttpClient43Engine.buildEntity(ManualClosingApacheHttpClient43Engine.java:548)
at org.jboss.resteasy.client.jaxrs.engines.ManualClosingApacheHttpClient43Engine.loadHttpMethod(ManualClosingApacheHttpClient43Engine.java:455)
at org.jboss.resteasy.client.jaxrs.engines.ManualClosingApacheHttpClient43Engine.invoke(ManualClosingApacheHttpClient43Engine.java:265)
... 77 more
I see in any example that a clientSecret is required but that is for confidential clients. I don't want this, I need the client to be public.
How can I have a public client while also being able to make API calls to it?
-I am getting Exception with STANDARD_AUTHENTICATION_PROVIDER
org.apache.chemistry.opencmis.commons.exceptions.CmisUnauthorizedException: Unauthorized
while createSession.
-previously it was working fine but suddenly stopped working,Also NTLM is working fine in my case.
-Also when once authenticated with NTLM and if changing to Basic again Session is getting generated but while retrieving folder details are Unauthorized.
-CMIS producer is Active at Sharepoint repo end.
parameter.put(SessionParameter.AUTHENTICATION_PROVIDER_CLASS, CmisBindingFactory.STANDARD_AUTHENTICATION_PROVIDER);
Stacktrace:
org.apache.chemistry.opencmis.commons.exceptions.CmisUnauthorizedException: Unauthorized
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.convertStatusCode(AbstractAtomPubService.java:477)
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.read(AbstractAtomPubService.java:645)
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.getRepositoriesInternal(AbstractAtomPubService.java:808)
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.RepositoryServiceImpl.getRepositoryInfo(RepositoryServiceImpl.java:69)
at org.apache.chemistry.opencmis.client.bindings.impl.RepositoryServiceImpl.getRepositoryInfo(RepositoryServiceImpl.java:74)
at org.apache.chemistry.opencmis.client.runtime.SessionImpl.connect(SessionImpl.java:1051)
at org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl.createSession(SessionFactoryImpl.java:106)
at org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl.createSession(SessionFactoryImpl.java:68)
at com.dms.externaldriver.cmisdriver.interfaceimpl.DMSClientInterfaceImpl.getSession(DMSClientInterfaceImpl.java:193)
at com.dms.externaldriver.cmisdriver.interfaceimpl.DMSClientInterfaceImpl.<init>(DMSClientInterfaceImpl.java:148)
at com.dms.driver.action.DMSExternalAction.getDMSExternalListTreeXML(DMSExternalAction.java:656)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:899)
at ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1544)
at ognl.ObjectMethodAccessor.callMethod(ObjectMethodAccessor.java:68)
at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethodWithDebugInfo(XWorkMethodAccessor.java:98)
at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethod(XWorkMethodAccessor.java:90)
at ognl.OgnlRuntime.callMethod(OgnlRuntime.java:1620)
at ognl.ASTMethod.getValueBody(ASTMethod.java:91)
at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
at ognl.SimpleNode.getValue(SimpleNode.java:258)
at ognl.Ognl.getValue(Ognl.java:470)
at ognl.Ognl.getValue(Ognl.java:434)
at com.opensymphony.xwork2.ognl.OgnlUtil$3.execute(OgnlUtil.java:401)
at com.opensymphony.xwork2.ognl.OgnlUtil.compileAndExecuteMethod(OgnlUtil.java:453)
at com.opensymphony.xwork2.ognl.OgnlUtil.callMethod(OgnlUtil.java:399)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:438)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:293)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:254)
at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:196)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
Closing this question as it is resolved now.
Re-entered the credential on server end and server was restarted.
I've deployed a Neo4j unmanaged extension. The unmanaged extension can be called using REST Client and successfully returned the result. The problem is when I try to call / invoke the unmanaged extension from another java class, it keep on throwing the 401 Unauthorized.
I used Spring RestTemplate to invoke the unmanaged extension.
My codes :
RestTemplate restTemplate = new RestTemplate();
PostPhotoRest postPhotoRest = restTemplate.getForObject("http://myneo4jusername:myneo4jpassword#localhost:7474/extension/servicetwo/postphoto/55b12d35-94fd-4297-bb18-e6040d7b7109", PostPhotoRest.class);
Full Error :
Caused by: org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) ~[spring-web-4.3.0.RC2.jar:4.3.0.RC2]
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:668) ~[spring-web-4.3.0.RC2.jar:4.3.0.RC2]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:621) ~[spring-web-4.3.0.RC2.jar:4.3.0.RC2]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:581) ~[spring-web-4.3.0.RC2.jar:4.3.0.RC2]
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:288) ~[spring-web-4.3.0.RC2.jar:4.3.0.RC2]
at my.winapp.hashtagmanipulation.worker.RabbitMQWorker.processMessage(RabbitMQWorker.java:76) ~[classes/:na]
at sun.reflect.GeneratedMethodAccessor27.invoke(Unknown Source) ~[na:na]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_66]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_66]
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) ~[spring-messaging-4.3.0.RC2.jar:4.3.0.RC2]
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:115) ~[spring-messaging-4.3.0.RC2.jar:4.3.0.RC2]
at org.springframework.amqp.rabbit.listener.adapter.HandlerAdapter.invoke(HandlerAdapter.java:48) ~[spring-rabbit-1.5.5.RELEASE.jar:na]
at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:112) ~[spring-rabbit-1.5.5.RELEASE.jar:na]
... 12 common frames omitted
The driver configuration can supply the URI and credentials configured in ogm.properties.
Components.driver().getConfiguration().getURI();
Components.driver().getConfiguration().getCredentials();
I'm writing the integration for a couple API service calls; one of those services was simple. A quick Item item = restTemplate.getForObject(url, Item.class) where Item is just a POJO and everything was mapped right into that object.
The other service is problematic. The call is almost the same: Attribute[] attribute = restTemplate.getForObject(url, Attribute[].class) with the difference being that the JSON response has a top level array. Here's the Attribute class:
#Data public class ItemAttributes {
private Long id;
private Attribute[] attributes;
#Data
private static class Attribute {
private String name;
//a bunch of other fields
}
}
All my digging says the above should work. Instead I get this:
org.springframework.http.converter.HttpMessageNotReadableException: Could not read
document: javax.xml.stream.XMLStreamException:
ParseError at [row,col]:[1,1]
Message: Content is not allowed in prolog.; nested exception is java.io.IOException: javax.xml.stream.XMLStreamException:
ParseError at [row,col]:[1,1]
Message: Content is not allowed in prolog.
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:224)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:208)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:95)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:599)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:264)
at com.homedepot.order.gateway.resource.ItemAttributeServiceResource.getItemAttributes(ItemAttributeServiceResource.java:37)
at com.homedepot.order.gateway.resource.ItemAttributeServiceResource.getItemAttributes(ItemAttributeServiceResource.java:32)
at com.homedepot.order.gateway.resource.ItemAttributeServiceResourceTest.testStuffOneItem(ItemAttributeServiceResourceTest.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:639)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:821)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1131)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:124)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
at org.testng.TestRunner.privateRun(TestRunner.java:773)
at org.testng.TestRunner.run(TestRunner.java:623)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:357)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:352)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:310)
at org.testng.SuiteRunner.run(SuiteRunner.java:259)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1185)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1110)
at org.testng.TestNG.run(TestNG.java:1018)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:122)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.io.IOException: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,1]
Message: Content is not allowed in prolog.
at com.fasterxml.jackson.dataformat.xml.util.StaxUtil.throwXmlAsIOException(StaxUtil.java:24)
at com.fasterxml.jackson.dataformat.xml.XmlFactory._createParser(XmlFactory.java:539)
at com.fasterxml.jackson.dataformat.xml.XmlFactory._createParser(XmlFactory.java:29)
at com.fasterxml.jackson.core.JsonFactory.createParser(JsonFactory.java:802)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2810)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:221)
... 36 more
Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,1]
Message: Content is not allowed in prolog.
at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:596)
at com.fasterxml.jackson.dataformat.xml.XmlFactory._initializeXmlReader(XmlFactory.java:648)
at com.fasterxml.jackson.dataformat.xml.XmlFactory._createParser(XmlFactory.java:537)
... 40 more
And additional digging has just lead me in circles. First, that's an XML specific Exception for what I've double-checked is actually a JSON response. Second, even if it was XML, RestTemplate should automatically register the correct HttpMessageConverter and mapper. (Right? That's what the documentation says.)
If I use ResponseEntity<String> response = restTemplate.getForEntity(url, String.class) and print response.getBody().toString() I get something that looks like this:
[{"id":12345678,"attributes":[{"f1":"value1","f2":"value2","f3":"value3"},
{"f1":"value4","f2":"value5","f3":"value6"}]}]
I know I could run with that, create an ObjectMapper and a parser and grab what I want, but that doesn't address the bigger question of why the other approach isn't working, and why it's throwing that exception.
Any help will be greatly appreciated.
Two potential issues:
1) Are you certain that the generic version of RestTemplate.getForObject can accept an array class ? Passing "Attribute[].class" seems incorrect...
2) The JSON coming back is not an array, it's a map. Even if passing an array class to RestTemplate worked, the data coming back is not going to match and the parse will fail.
~NCM
My mistake. Despite assurances from the API team that the response was definitely "application/json" I should have done my due diligence first and checked the Content-Type on the header on the response because it was set to "text/plain". Once they fixed that the problem was resolved.
I've been struggling to solve this issue here, and i can't find what i am doing wrong.
I am trying to make a simple JSON Post, using Spring RestTemplate, and sending all information as String to be simple all the way around as follows:
RestTemplate restTemplate = new RestTemplate();
JSONObject issue = getJSONIssue(redmine);
try {
String response = restTemplate.postForObject(redmineProperties.getUrl()+"/issues.json?key="+redmineProperties.getKey(), issue.toJSONString(), String.class);
}catch(RestClientException e){
e.printStackTrace();
}
My JSONObject looks like:
{"issue":
{"priority_id":4,
"description":"asdasdasdasd",
"subject":"adasdad",
"project_id":4
}
}
This is the data i am trying to sendo via Post, and the server keep sending me the error:
[http-bio-8080-exec-7] WARN org.springframework.web.client.RestTemplate - POST request for "http://xxx.com.br/issues.json?key=b8143da980578fee4db0b33bd3cd3eec511797d6" resulted in 422 (Unprocessable Entity); invoking error handler
org.springframework.web.client.HttpClientErrorException: 422 Unprocessable Entity
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:589)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:547)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:503)
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:331)
at br.com.cubbes.docmidia.controller.redmine.RedmineController.saveUser(RedmineController.java:101)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
when i send the same data via a client like insomnia by Google Chrome, the servers resolves without a problem.
Do anyone know what i could be doing wrong here?
For anyone coming here for 422 Unprocessable Entity, as suggested in one of the comments, setting the content-type:application/json fixed the error for me.
RequestEntity<ValidationRequest> requestEntity = RequestEntity.post(validatorUri)
.contentType(MediaType.APPLICATION_JSON)
.body(validationRequest);
JsonNode validationResponse = restTemplate.exchange(requestEntity, JsonNode.class).getBody();
I ended up using a specific library to manipulate this REST calls:
http://www.redmine.org/projects/redmine/wiki/Rest_api_with_java
Thanks guys