Adding MIME Messages to a LinkedBlockingQueue Error - java

Trying to add all MIME messages in a POP3 inbox to a LinkedBlockingQueue:
inbox = pollStore.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
for (int i = 0; i < inbox.getMessageCount(); i++) {
Message messageI = inbox.getMessage(i+1);
if (messageI != null ) {
MimeMessage mimeMessageI = (MimeMessage) messageI;
inboxQueue.add(mimeMessageI);
messageI.setFlag(Flags.Flag.DELETED, true);
}
}
However I get java.lang.NullPointerException error upon running a tester class, which otherwise works. What could be the problem?
at com.tutorgami.relay.email.EmailFetchClient.poll(EmailFetchClient.java:147)
at com.tutorgami.relay.RelayIntegrationTest1.testSendingAndReceiving(RelayIntegrationTest1.java:70)
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.InvokeMethod.evaluate(InvokeMethod.java:17)
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)

Related

Apache Commons FileUtils.copyURLToFile - Directory that already exists could not be created

I'm attempting to download a JSON file and save it to a local directory. The directory (/data/provisioning) already exists and has been given 776 (u=rwx,g=rwx,o=rw) as its permissions. The parent directory (/data) has also been given 776 permissions.
I'm using the Apache Commons FileUtils.copyURLToFile(..) method to download the file, like this:
String filePathToSave = "/data/provisioning/nexus_contents.json";
String url = "http://repository.obfuscated.com/nexus/url/to/json/file";
try {
FileUtils.copyURLToFile(
new URL(url)
, new File(filePathToSave),
5000,
5000);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
However, to my surprise, I'm getting this error:
java.io.IOException: Directory '/data/provisioning' could not be
created at
org.apache.commons.io.FileUtils.openOutputStream(FileUtils.java:356)
at
org.apache.commons.io.FileUtils.openOutputStream(FileUtils.java:319)
at org.apache.commons.io.FileUtils.copyToFile(FileUtils.java:1552)
at
org.apache.commons.io.FileUtils.copyInputStreamToFile(FileUtils.java:1528)
at org.apache.commons.io.FileUtils.copyURLToFile(FileUtils.java:1506)
at
deployment.download.Downloader.getAndSaveNexusJSON(Downloader.java:26)
at
deployment.test.DeploymentTest.downloader_get_Nexus_JSON(DeploymentTest.java:424)
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
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.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.junit.runner.JUnitCore.run(JUnitCore.java:160) at
com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at
com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at
com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at
com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
What am I missing here?

NullPointerException while running JUnit

Getting NullPointerException while running a JUnit test. I have already mocked the ClientHttpResponse class. Not sure what else I am missing.
Error:
java.lang.NullPointerException
at org.springframework.web.client.DefaultResponseErrorHandler.hasError(DefaultResponseErrorHandler.java:75)
at org.springframework.web.client.DefaultResponseErrorHandler.hasError(DefaultResponseErrorHandler.java:50)
at com.tss.payhub.template.rest.client.CustomResponseErrorHandler.hasError(CustomResponseErrorHandler.java:20)
at com.tss.payhub.template.rest.client.test.CustomResponseErrorHandlerTest.testHasError(CustomResponseErrorHandlerTest.java:21)
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 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.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.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
CustomResponseErrorHandlerTest.java
public class CustomResponseErrorHandlerTest {
#Mock
ClientHttpResponse response = Mockito.mock(ClientHttpResponse.class);
#Test
public void testHasError() throws IOException {
CustomResponseErrorHandler instance = new CustomResponseErrorHandler();
boolean blnVal = instance.hasError(response);
assertTrue(blnVal);
}
}
CustomResponseErrorHandler.java (Class Under Test)
#Component
public class CustomResponseErrorHandler implements ResponseErrorHandler {
private ResponseErrorHandler errorHandler = new DefaultResponseErrorHandler();
public boolean hasError(ClientHttpResponse response) throws IOException {
return errorHandler.hasError(response);
}
}
Try adding #RunWith(EasyMockRunner.class) to your test class:
#RunWith(EasyMockRunner.class)
public class CustomResponseErrorHandlerTest {

Spring Security Test fails with NullPointerException

Using Spring Security 3.2.5 and Spring Secuirty Test 4.0.0.M1 artifact, I am not able to run the following unit test successfully:
#Test
public void testRequestOAuthToken() throws Exception {
this.mockMvc.perform(post("/oauth/token/")
.param("grant_type", "password")
.param("client_id", "ios")
.param("username", "user")
.param("password", "123c86b3634342f")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.accept(MediaType.APPLICATION_JSON)
.with(user("ios").password("aabb03880fsddc665ffb9a0").roles("APP")))
.andDo(print())
.andExpect(status().isOk());
}
It results in throwing the NullPointerException:
java.lang.NullPointerException
at org.springframework.security.test.web.support.WebTestUtils.findFilter(WebTestUtils.java:115)
at org.springframework.security.test.web.support.WebTestUtils.getSecurityContextRepository(WebTestUtils.java:57)
at org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors$SecurityContextRequestPostProcessorSupport.save(SecurityMockMvcRequestPostProcessors.java:436)
at org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors$SecurityContextRequestPostProcessorSupport.save(SecurityMockMvcRequestPostProcessors.java:424)
at org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors$AuthenticationRequestPostProcessor.postProcessRequest(SecurityMockMvcRequestPostProcessors.java:560)
at org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors$UserDetailsRequestPostProcessor.postProcessRequest(SecurityMockMvcRequestPostProcessors.java:585)
at org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors$UserRequestPostProcessor.postProcessRequest(SecurityMockMvcRequestPostProcessors.java:699)
at org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder.postProcessRequest(MockHttpServletRequestBuilder.java:686)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:137)
at com.mycomp.OAuthUnitTests.testRequestOAuthToken(OAuthUnitTests.java:88)
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: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:73)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:217)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
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:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
at org.junit.runners.Suite.runChild(Suite.java:127)
at org.junit.runners.Suite.runChild(Suite.java:26)
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.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Any tips? This is my Spring Unit Test configuration:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration( locations = { "file:src/main/webapp/WEB-INF/applicationContext.xml", "file:src/main/webapp/WEB-INF/securityApplicationContext.xml" })
public class OAuthUnitTests {
#Autowired
private WebApplicationContext wac;
#Autowired
private Filter springSecurityFilterChain;
private MockMvc mockMvc;
#Before
public void setUp() {
this.mockMvc = webAppContextSetup(this.wac)
.addFilters(springSecurityFilterChain)
.build();
}

Creating a Serializable mock with Mockito error

I'm trying to create a mock object with Mockito that can be serialized. The object is an interface implementation. When this method is called, I receive an object that I want to pass to another object, hence using the doAnswer(...)-method.
This is my code.
InterfaceClass obj = mock(InterfaceClass.class, withSettings().serializable());
doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
//Here I do something with the arguments
}
}).when(obj).someMethod(
any(someObject.class));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(obj);
byte[] yourBytes = bos.toByteArray();
} finally {
out.close();
bos.close();
}
As far as I can tell this should be correct (I'm fairly new to Mockito).
But when Serializing my object I get this error:
java.io.NotSerializableException: com.trust1t.ocs.signcore.test.InvalidInputTestCase$1
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1165)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:329)
at java.util.concurrent.ConcurrentLinkedQueue.writeObject(ConcurrentLinkedQueue.java:644)
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 java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:950)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1482)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1535)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:329)
at java.util.LinkedList.writeObject(LinkedList.java:943)
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 java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:950)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1482)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1535)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1535)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1535)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1535)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:329)
at com.trust1t.ocs.signcore.test.InvalidInputTestCase.certificateValidationTest(InvalidInputTestCase.java:117)
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: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.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)
The invalidInputTestCase class is the class containing the test where I'm using this code. It looks as if the mock object references this TestCase somewhere (can't find it though).
Am I not correctly implementing this or better ideas to mock?
If you want to serialize a mock everything needs to be serializable, including the Answer.
And actually that's what the JDK is telling you :
java.io.NotSerializableException: com.trust1t.ocs.signcore.test.InvalidInputTestCase$1
where InvalidInputTestCase$1 is the name of the anonymous Answer.
To make it serializable you have to create a class implementing Answer and Serializable.
Also note that serialization across classloaders (JVM) is not yet released, at the moment you can only serialize and deserialize a mock in the same classloader.

ClientRequest, how to serialize POJO's to json data correctly? could not find writer for content-type application/json type:

For a REST serives (RESTeasy) I have created JUnit test cases like:
#Test
public void a100_insertAddressTest() throws Exception {
Address addr = new Address(1, "testStreet", "1", (short) 1234,
"testCity");
ClientRequest request = new ClientRequest(BASE_URL + "customerID/{id}",
sslExecutor_schusb);
request.body(MediaType.APPLICATION_XML, addr).pathParameter(
"id", 1);
ClientResponse<String> response = request.post(String.class);
Assert.assertEquals(201, response.getStatus());
response.releaseConnection();
request.clear();
}
If I change the media type of the request body to "application/json", the test case fails with the error:
java.lang.RuntimeException: could not find writer for content-type application/json type: at.fhj.ase.dao.data.Address
at org.jboss.resteasy.client.ClientRequest.writeRequestBody(ClientRequest.java:469)
at org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor.loadHttpMethod(ApacheHttpClient4Executor.java:221)
at org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor.execute(ApacheHttpClient4Executor.java:107)
at org.jboss.resteasy.core.interception.ClientExecutionContextImpl.proceed(ClientExecutionContextImpl.java:39)
at org.jboss.resteasy.plugins.interceptors.encoding.AcceptEncodingGZIPInterceptor.execute(AcceptEncodingGZIPInterceptor.java:40)
at org.jboss.resteasy.core.interception.ClientExecutionContextImpl.proceed(ClientExecutionContextImpl.java:45)
at org.jboss.resteasy.client.ClientRequest.execute(ClientRequest.java:443)
at org.jboss.resteasy.client.ClientRequest.httpMethod(ClientRequest.java:674)
at org.jboss.resteasy.client.ClientRequest.post(ClientRequest.java:565)
at org.jboss.resteasy.client.ClientRequest.post(ClientRequest.java:570)
at at.fhj.ase.business.ServiceAddressImplTest.a100_insertAddressTest(ServiceAddressImplTest.java:59)
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.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:168)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
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)
Hence I created a MessageBodyWriter which works fine if I do a POST request by using the firefox plugin RESTClient:
#Provider
#Produces(MediaType.APPLICATION_JSON)
public class JsonMsbWriter implements MessageBodyWriter<Address> {
#Override
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
if(type == Address.class){
return true;
}
return false;
}
#Override
public long getSize(Address t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return -1;
}
#Override
public void writeTo(Address t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException,
WebApplicationException {
ObjectMapper m = new ObjectMapper();
m.writeValue(entityStream, t);
}
}
and updated the JUnit test case to:
#Test
public void a100_insertAddressTest() throws Exception {
Address addr = new Address(1, "testStreet", "1", (short) 1234,
"testCity");
ResteasyProviderFactory fact = ResteasyProviderFactory.getInstance();
fact.addMessageBodyWriter(JsonMsbWriter.class);
ClientRequest request = new ClientRequest(BASE_URL + "customerID/{id}",
sslExecutor_schusb);
request.body(MediaType.APPLICATION_JSON, addr).pathParameter("id", 1);
ClientResponse<String> response = request.post(String.class);
Assert.assertEquals(201, response.getStatus());
response.releaseConnection();
request.clear();
}
But now I get the error:
java.lang.VerifyError: (class: org/codehaus/jackson/map/ObjectMapper, method: writeValueAsBytes signature: (Ljava/lang/Object;)[B) Incompatible argument to function
at at.fhj.ase.xmlvalidation.msbreader.JsonMsbWriter.writeTo(JsonMsbWriter.java:46)
at at.fhj.ase.xmlvalidation.msbreader.JsonMsbWriter.writeTo(JsonMsbWriter.java:1)
at org.jboss.resteasy.core.interception.MessageBodyWriterContextImpl.proceed(MessageBodyWriterContextImpl.java:117)
at org.jboss.resteasy.plugins.interceptors.encoding.GZIPEncodingInterceptor.write(GZIPEncodingInterceptor.java:100)
at org.jboss.resteasy.core.interception.MessageBodyWriterContextImpl.proceed(MessageBodyWriterContextImpl.java:123)
at org.jboss.resteasy.client.ClientRequest.writeRequestBody(ClientRequest.java:472)
at org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor.loadHttpMethod(ApacheHttpClient4Executor.java:221)
at org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor.execute(ApacheHttpClient4Executor.java:107)
at org.jboss.resteasy.core.interception.ClientExecutionContextImpl.proceed(ClientExecutionContextImpl.java:39)
at org.jboss.resteasy.plugins.interceptors.encoding.AcceptEncodingGZIPInterceptor.execute(AcceptEncodingGZIPInterceptor.java:40)
at org.jboss.resteasy.core.interception.ClientExecutionContextImpl.proceed(ClientExecutionContextImpl.java:45)
at org.jboss.resteasy.client.ClientRequest.execute(ClientRequest.java:443)
at org.jboss.resteasy.client.ClientRequest.httpMethod(ClientRequest.java:674)
at org.jboss.resteasy.client.ClientRequest.post(ClientRequest.java:565)
at org.jboss.resteasy.client.ClientRequest.post(ClientRequest.java:570)
at at.fhj.ase.business.ServiceAddressImplTest.a100_insertAddressTest(ServiceAddressImplTest.java:65)
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.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:168)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
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 attach such a writer for json?
And why does it work for content type application/xml out of the
box?
For GET requests and application/json there is the same problem, however with the reader instead of the writer.
Problem solved, unfortunately I haven't included all necessary 3rd party libraries to the projects build path. Finally I added the following jars:
jackson-core-asl-1.6.3.jar
jackson-jaxrs-1.6.3.jar
jackson-mapper-asl-1.6.3.jar
jackson-xc-1.6.3.jar
resteasy-jackson-provider-2.2.1.GA.jar
This example brings the strength of Maven to the front. With Maven there is only one entry necessary to fulfill these dependencies.
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>2.2.1.GA</version>
</dependency>

Categories