Problem mapping JSON data to a POJO class. The Customer Class has 2 fields "customerId, isTrue). I'm using JacksonMixInAnnotations for each field.
JUnit Test is OK without the first part of JSON ({ \"customer\":"). It fails if included, (null for customer.getCustomerId()).
Thanks
#Test
public void test() {
mockServer.expect(requestTo("..."))
.andExpect(method(GET))
.andRespond(withSuccess(str, MediaType.APPLICATION_JSON));
Customer customer = api.operations().getCustomer();
assertEquals("foo", customer.getCustomerId());
assertEquals("TRUE"),customer.isTrue());
}
String str = "{ \"customer\": { \"customer-id\": \"foo\",\"is-true\": \"TRUE\" }}";
#Override
protected MappingJacksonHttpMessageConverter getJsonMessageConverter() {
MappingJacksonHttpMessageConverter converter = super.getJsonMessageConverter();
objectMapper = new ObjectMapper();
objectMapper.registerModule(new TestModule());
converter.setObjectMapper(objectMapper);
return converter;
}
If I add a "customer" field to POJO then I get the following error:
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of java.lang.String out of START_OBJECT token
at [Source: java.io.ByteArrayInputStream#1d8835d; line: 1, column: 3]; nested exception is org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
at [Source: java.io.ByteArrayInputStream#1d8835d; line: 1, column: 3]
at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readJavaType(MappingJacksonHttpMessageConverter.java:169)
at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.read(MappingJacksonHttpMessageConverter.java:161)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:94)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:491)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:460)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:228)
at org.springframework.social.test.api.impl.CustomerTemplate.getCustomer(CustomerTemplate.java:24)
at org.springframework.social.test.api.impl.CustomerTemplateTest.getCustomer_current_user(CustomerTemplateTest.java:20)
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:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
at [Source: java.io.ByteArrayInputStream#1d8835d; line: 1, column: 3]
at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:219)
at org.codehaus.jackson.map.deser.std.StringDeserializer.deserialize(StringDeserializer.java:44)
at org.codehaus.jackson.map.deser.std.StringDeserializer.deserialize(StringDeserializer.java:13)
at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:299)
at org.codehaus.jackson.map.deser.BeanDeserializer._deserializeUsingPropertyBased(BeanDeserializer.java:905)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObjectUsingNonDefault(BeanDeserializer.java:739)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:683)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1923)
at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readJavaType(MappingJacksonHttpMessageConverter.java:166)
... 31 more
Have a look at the #JsonRootName annotation (add it to your Customer.class) and enable the DeserializationFeature UNWRAP_ROOT_VALUE on the ObjectMapper with the method enable(DeserializationFeature feature).
Related
I'm trying to post a json using feign but i get an error from the url that parameters were not sent. This is my code:
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "Rabbit SEO");
jsonObject.put("price", "10");
jsonObject.put("test", "true");
jsonObject.put("return_url", "https://www.rabbitseo.com/shopifyPaidGuest");
String content = jsonObject.toString();
System.out.println("content = " + content);
String result = myClient.postRecurringPayment(content);
#RequestLine("POST /admin/recurring_application_charges.json")
#Headers("Content-Type: application/json")
String postRecurringPayment(String content);
return Feign.builder()
.requestInterceptors(requestInterceptors)
.target(MyApiClient.class, myShopifyUrl);
I tried also with the gson decoder and encoder:
return Feign.builder()
.decoder(new GsonDecoder())
.encoder(new GsonEncoder())
.requestInterceptors(requestInterceptors)
.target(MyApiClient.class, myShopifyUrl);
Error:
feign.FeignException: status 400 reading MyApiClient#postRecurringPayment(String); content:
{"errors":{"recurring_application_charge":"Required parameter missing or invalid"}}
at feign.FeignException.errorStatus(FeignException.java:62)
at feign.codec.ErrorDecoder$Default.decode(ErrorDecoder.java:91)
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:126)
at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:74)
at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:94)
at com.sun.proxy.$Proxy4.postRecurringPayment(Unknown Source)
at com.test.TestOauth.testShopifyProducts2(TestOauth.java:49)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:62)
Looking at log http error code 400 mean BadRequest
"errors":{"recurring_application_charge":"Required parameter missing or invalid"
You must pass recurring_application_charge as part of JSON to be accepted by API
But, you need to post complete error log and MyClient class would help advise more.
I am trying to test my CXF web-service - which has in-interceptors and it has the task to modify the JSON received from UI and pass it to a 3rd Party Rest Service.
I am mostly using EasyMock, but since I have to mock the Http rest call too, and the code uses the static class org.apache.http.impl.client.HttpClients, So I am going for PowerMock along with EasyMock.
But I am facing an issue of similar kind like this: PowerMock PrepareForTest annotation causing problems with AmazonSQSClient constructor
Following the solution I have added the
#PowerMockIgnore({ "org.apache.cxf.jaxws.*,sun.security.ssl.*,org.apache.cxf.configuration.jsse.*" })
Still the issue is not getting resolved. I want to understand which packages do I need to include to get rid of this. The error stack trace is:
javax.xml.ws.WebServiceException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '*.*': Cannot create inner bean '(inner bean)' of type [org.apache.cxf.configuration.jsse.TLSClientParametersConfig] while setting bean property 'tlsClientParameters'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public static org.apache.cxf.configuration.jsse.TLSClientParameters org.apache.cxf.configuration.jsse.TLSClientParametersConfig.createTLSClientParametersFromType(org.apache.cxf.configuration.security.TLSClientParametersType) throws java.security.GeneralSecurityException,java.io.IOException] threw exception; nested exception is java.security.NoSuchAlgorithmException: class configured for KeyManagerFactory: sun.security.ssl.KeyManagerFactoryImpl$SunX509 not a KeyManagerFactory
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:154)
at com.sun.proxy.$Proxy72.invokeService(Unknown Source)
at com.uhg.pdr.consumer.SelectProfessionalsByIdTypeConsumer.invokeService(SelectProfessionalsByIdTypeConsumer.java:72)
at com.uhg.pdr.providerinfo.SelectProfessionalsByIdTypeProvider.getAssociatedProviders(SelectProfessionalsByIdTypeProvider.java:212)
at com.uhg.util.rest.PropelUtil.getProvidersByMpin(PropelUtil.java:212)
at com.uhg.pdr.interceptor.service.MppBaseInterceptorServiceImpl.getProviders(MppBaseInterceptorServiceImpl.java:302)
at com.uhg.pdr.interceptor.MppBaseInterceptor.handleMessage(MppBaseInterceptor.java:79)
at com.uhg.pdr.bundling.transactions.ProviderLanguageTransactionTest.handleMessageTest(ProviderLanguageTransactionTest.java:129)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner$2.call(DelegatingPowerMockRunner.java:148)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner$2.call(DelegatingPowerMockRunner.java:140)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner.withContextClassLoader(DelegatingPowerMockRunner.java:131)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner.run(DelegatingPowerMockRunner.java:140)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:121)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '*.*': Cannot create inner bean '(inner bean)' of type [org.apache.cxf.configuration.jsse.TLSClientParametersConfig] while setting bean property 'tlsClientParameters'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public static org.apache.cxf.configuration.jsse.TLSClientParameters org.apache.cxf.configuration.jsse.TLSClientParametersConfig.createTLSClientParametersFromType(org.apache.cxf.configuration.security.TLSClientParametersType) throws java.security.GeneralSecurityException,java.io.IOException] threw exception; nested exception is java.security.NoSuchAlgorithmException: class configured for KeyManagerFactory: sun.security.ssl.KeyManagerFactoryImpl$SunX509 not a KeyManagerFactory
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:281)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:125)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1360)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.configureBean(AbstractAutowireCapableBeanFactory.java:314)
at org.springframework.beans.factory.wiring.BeanConfigurerSupport.configureBean(BeanConfigurerSupport.java:146)
at org.apache.cxf.configuration.spring.ConfigurerImpl.configureBean(ConfigurerImpl.java:151)
at org.apache.cxf.configuration.spring.ConfigurerImpl.configureWithWildCard(ConfigurerImpl.java:176)
at org.apache.cxf.configuration.spring.ConfigurerImpl.configureBean(ConfigurerImpl.java:131)
at org.apache.cxf.configuration.spring.ConfigurerImpl.configureBean(ConfigurerImpl.java:115)
at org.apache.cxf.transport.http.HTTPTransportFactory.configure(HTTPTransportFactory.java:187)
at org.apache.cxf.transport.http.HTTPTransportFactory.getConduit(HTTPTransportFactory.java:270)
at org.apache.cxf.binding.soap.SoapTransportFactory.getConduit(SoapTransportFactory.java:239)
at org.apache.cxf.binding.soap.SoapTransportFactory.getConduit(SoapTransportFactory.java:246)
at org.apache.cxf.endpoint.AbstractConduitSelector.getSelectedConduit(AbstractConduitSelector.java:103)
at org.apache.cxf.endpoint.UpfrontConduitSelector.prepare(UpfrontConduitSelector.java:63)
at org.apache.cxf.endpoint.ClientImpl.prepareConduitSelector(ClientImpl.java:851)
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:526)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:464)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:367)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:320)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:89)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:134)
... 43 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public static org.apache.cxf.configuration.jsse.TLSClientParameters org.apache.cxf.configuration.jsse.TLSClientParametersConfig.createTLSClientParametersFromType(org.apache.cxf.configuration.security.TLSClientParametersType) throws java.security.GeneralSecurityException,java.io.IOException] threw exception; nested exception is java.security.NoSuchAlgorithmException: class configured for KeyManagerFactory: sun.security.ssl.KeyManagerFactoryImpl$SunX509 not a KeyManagerFactory
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:581)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1015)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:911)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:270)
... 65 more
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public static org.apache.cxf.configuration.jsse.TLSClientParameters org.apache.cxf.configuration.jsse.TLSClientParametersConfig.createTLSClientParametersFromType(org.apache.cxf.configuration.security.TLSClientParametersType) throws java.security.GeneralSecurityException,java.io.IOException] threw exception; nested exception is java.security.NoSuchAlgorithmException: class configured for KeyManagerFactory: sun.security.ssl.KeyManagerFactoryImpl$SunX509 not a KeyManagerFactory
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:169)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:570)
... 70 more
Caused by: java.security.NoSuchAlgorithmException: class configured for KeyManagerFactory: sun.security.ssl.KeyManagerFactoryImpl$SunX509 not a KeyManagerFactory
at sun.security.jca.GetInstance.checkSuperClass(GetInstance.java:258)
at sun.security.jca.GetInstance.getInstance(GetInstance.java:237)
at sun.security.jca.GetInstance.getInstance(GetInstance.java:164)
at javax.net.ssl.KeyManagerFactory.getInstance(KeyManagerFactory.java:139)
at org.apache.cxf.configuration.jsse.TLSParameterJaxBUtils.getKeyManagers(TLSParameterJaxBUtils.java:274)
at org.apache.cxf.configuration.jsse.TLSClientParametersConfig.createTLSClientParametersFromType(TLSClientParametersConfig.java:110)
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.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:149)
... 71 more
Here is my Test class :
#RunWith(PowerMockRunner.class)
#PrepareForTest(ProviderAddressUpdateController.class)
#PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
#PowerMockIgnore({ "org.apache.cxf.jaxws.*,sun.security.ssl.*,org.apache.cxf.configuration.jsse.*" })
#ContextConfiguration(locations = { "classpath:application-context-test.xml" })
public class ProviderLanguageTransactionTest {
.....
.....
.....
#Before
public void setUp() {
.....
.....
}
#Test
public void handleMessageTest() throws Exception {
....
....
}
Issue got resolved by adding #PowerMockIgnore({ "javax.net.ssl.*" })
Also the class inside #PrepareForTest annotation should be the class mocked by PowerMock - not the controller. If you are mocking the HttpClients class,then you should write #PrepareForTest(HttpClients.class) before that method inside which you are mocking.
I’m using Jackson 1.9.5. I have this attribute in my JSON
{"Difficulty Level":["Medium”,”Hard”]}
How do I use Jackson annotations to read the above into my field “difficultyArr”, shown in my object below …
#JsonIgnoreProperties(ignoreUnknown = true)
public class ThirdPartyQuestionsDto implements Serializable{
#JsonProperty("Difficulty Level")
private List<String> difficultyArr = new ArrayList<String>();
…
public List<String> getDifficultyArr() {
return difficultyArr;
}
public void setDifficultyArr(List<String> difficultyArr) {
this.difficultyArr = difficultyArr;
}
Here is how I’m trying to get the data into my object …
import org.codehaus.jackson.map.ObjectMapper;
…
final ObjectMapper mapper = new ObjectMapper();
final ThirdPartyQuestionsDto itemDto = mapper.readValue(itemJson, ThirdPartyQuestionsDto.class);
but unfortunately I get the following error
[ERROR]: org.mainco.subco.myproject.controllers.MyController - Unexpected character ('T' (code 84)): was expecting comma to separate OBJECT entries
at [Source: java.io.StringReader#555b3ec9; line: 1, column: 294]
org.codehaus.jackson.JsonParseException: Unexpected character ('T' (code 84)): was expecting comma to separate OBJECT entries
at [Source: java.io.StringReader#555b3ec9; line: 1, column: 294]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1432)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:521)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportUnexpectedChar(JsonParserMinimalBase.java:442)
at org.codehaus.jackson.impl.ReaderBasedParser.nextToken(ReaderBasedParser.java:406)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:690)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2725)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1856)
at org.mainco.subco.myproject.controllers.MyController.postUploadActivitiesPage(MyController.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 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:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:685)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:855)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:168)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:136)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:141)
at org.mainco.subco.myproject.controllers.MyControllerIT.testUploadLearnosityActivities(MyControllerIT.java:98)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.powermock.modules.junit4.rule.PowerMockStatement.evaluate(PowerMockRule.java:63)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
If you copy-pasted that text from somewhere, it's not valid JSON. The first problem is that it's not enclosed by braces. The second problem is that some of your double-quotes are not actually double-quotes. If you look closely, you'll see that they are different.
The following is valid JSON:
{
"Difficulty Level": ["Medium", "Hard"]
}
This question already has answers here:
JPA Criteria API group_concat usage
(3 answers)
Closed 5 years ago.
I’m using JPA 2.1, Hibernate 4.3.6.Final, and MySQL 5.5. I read JPA 2.1 supports invoking native DB functions, but I’m having trouble figuring out how to invoke MySQL's “GROUP_CONCAT.” I have the following code …
final CriteriaBuilder builder = m_entityManager.getCriteriaBuilder();
final CriteriaQuery criteria = StringUtils.equals(orderByCol, "organization") ? builder.createQuery(Tuple.class) : builder.createQuery(User.class);
final Root<User> user = criteria.from(User.class);
…
final SetJoin<User, Organization> orgsJoin = orderByRoot.join(User_.organizations, JoinType.LEFT);
final Expression groupConcatExpr = builder.function("GROUP_CONCAT", String.class, orgsJoin.get(Organization_.name));
criteria.select(builder.tuple(user, groupConcatExpr))
.groupBy(user);
…
orderByExpr = orgsJoin.get(Organization_.name);
criteria.orderBy(orderByAscending == null || orderByAscending == true ? builder.asc(orderByExpr) : builder.desc(orderByExpr));
but I get the following exception …
java.lang.IllegalStateException: No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode
\-[METHOD_CALL] MethodNode: 'function (GROUP_CONCAT)'
+-[METHOD_NAME] IdentNode: 'GROUP_CONCAT' {originalText=GROUP_CONCAT}
\-[EXPR_LIST] SqlNode: 'exprList'
\-[DOT] DotNode: 'organizati2_.NAME' {propertyName=name,dereferenceType=PRIMITIVE,getPropertyPath=name,path=generatedAlias1.name,tableAlias=organizati2_,className=org.mainco.subco.organization.domain.Organization,classAlias=generatedAlias1}
+-[ALIAS_REF] IdentNode: 'organizati2_.id' {alias=generatedAlias1, className=org.mainco.subco.organization.domain.Organization, tableAlias=organizati2_}
\-[IDENT] IdentNode: 'name' {originalText=name}
at org.hibernate.hql.internal.ast.tree.SelectClause.initializeExplicitSelectClause(SelectClause.java:174)
at org.hibernate.hql.internal.ast.HqlSqlWalker.useSelectClause(HqlSqlWalker.java:924)
at org.hibernate.hql.internal.ast.HqlSqlWalker.processQuery(HqlSqlWalker.java:692)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:665)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:301)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:249)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:278)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:167)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1800)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:568)
at org.hibernate.jpa.criteria.CriteriaQueryImpl$1.buildCompiledQuery(CriteriaQueryImpl.java:336)
at org.hibernate.jpa.criteria.compile.CriteriaCompiler.compile(CriteriaCompiler.java:147)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:736)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
at com.sun.proxy.$Proxy68.createQuery(Unknown Source)
at org.mainco.subco.user.repo.UserDaoImpl.findUsers(UserDaoImpl.java:120)
at org.mainco.subco.user.repo.UserDao2IT.testFindOrderByOrganizationAsc(UserDao2IT.java:624)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
To user GROUP_CONCAT in JPA, below are the steps:
1.) Create a class "GroupConcatFunction" as below:
import java.util.List;
import org.hibernate.QueryException;
import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.Type;
public class GroupConcatFunction implements SQLFunction {
#Override
public boolean hasArguments() {
return true;
}
#Override
public boolean hasParenthesesIfNoArguments() {
return true;
}
#Override
public Type getReturnType(Type firstArgumentType, Mapping mapping)
throws QueryException {
return StandardBasicTypes.STRING;
}
#SuppressWarnings("rawtypes")
#Override
public String render(Type firstArgumentType, List arguments,
SessionFactoryImplementor factory) throws QueryException {
if (arguments.size() != 1) {
throw new QueryException("group_concat should have only one argument");
}
return "group_concat(" + arguments.get(0) + ")";
}
}
2.) We will create a custom dialect which will have the code to register our group_concat function in dialect:
import org.hibernate.dialect.MySQL5Dialect;
public class CustomMySql5Dialect extends MySQL5Dialect {
public CustomMySql5Dialect() {
super();
registerFunction("group_concat", new GroupConcatFunction());
}
}
3.) Replace the dialect definition in persistence.xml with your custom dialect:
<property name="hibernate.dialect" value="<<pkg name>>.CustomMySql5Dialect" />
Now, you will be able to use this in your criteria query.
this is how a test looks like in my application:
#Test (expected = UniqueFieldValueConstraintViolationException.class)
public void testName() {
Branch b1 = new Branch("tetsname","Test 234","06:00-17:00","098144658");
Branch b2 = new Branch("tetsname","Test 234","06:00-17:00","098144658");
db.store(b1);
db.store(b2);
db.commit();
}
This test fails although the exception is thrown:
com.db4o.constraints.UniqueFieldValueConstraintViolationException: class: dataModel.Branch field: pNumber at
com.db4o.constraints.UniqueFieldValueConstraint$1.ensureSingleOccurence(UniqueFieldValueConstraint.java:66)
at
com.db4o.constraints.UniqueFieldValueConstraint$1.onEvent(UniqueFieldValueConstraint.java:97)
at com.db4o.internal.events.Event4Impl.trigger(Event4Impl.java:78)
at
com.db4o.internal.events.EventRegistryImpl$4.run(EventRegistryImpl.java:123)
at com.db4o.foundation.DynamicVariable.with(DynamicVariable.java:54)
at com.db4o.internal.InCallback.run(InCallback.java:24) at
com.db4o.internal.events.EventRegistryImpl.withExceptionHandlingInCallback(EventRegistryImpl.java:279)
at
com.db4o.internal.events.EventRegistryImpl.commitOnStarted(EventRegistryImpl.java:121)
at
com.db4o.internal.LocalTransaction.dispatchCommittingCallback(LocalTransaction.java:89)
at
com.db4o.internal.LocalTransaction.commit(LocalTransaction.java:66)
at
com.db4o.internal.LocalTransaction.commit(LocalTransaction.java:59)
at
com.db4o.internal.LocalObjectContainer.commitTransaction(LocalObjectContainer.java:689)
at
com.db4o.internal.LocalObjectContainer.close2(LocalObjectContainer.java:94)
at
com.db4o.internal.ObjectContainerBase.close1(ObjectContainerBase.java:361)
at
com.db4o.internal.ObjectContainerBase.close(ObjectContainerBase.java:344)
at tests.BranchTests.cleanUp(BranchTests.java:127) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at
org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:33)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at
org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at
org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at
org.junit.runners.ParentRunner.run(ParentRunner.java:309) at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
How can i avoid this behavior?
From the stack trace, you can see this exception isn't being thrown in the testName() method: it's being thrown by tests.BranchTests.cleanUp, which is presumably a separate method run before or after your real test.
JUnit's expected won't cover exceptions thrown during these phases. Either ensure these failures don't happen here, or catch and ignore them.