"The target server failed to respond" when using HttpSolrServer - java

http://localhost:8080/solr works well in my browser and there is no error in the console of tomcat when I start it.
my code is:
public static void index() throws SolrServerException, IOException {
String url = "http://localhost:8080/solr";
HttpSolrServer server = new HttpSolrServer(url);
SolrInputDocument doc = new SolrInputDocument();
doc.addField("id", "1");
doc.addField("name", "name");
doc.addField("content", "cold today");
server.add(doc);
server.commit();
}
when I run the code,there is nothing printed in the console of tomcat and I get
Caused by: org.apache.http.NoHttpResponseException: The target server failed to respond instead.
the full failure trace is:
org.apache.solr.client.solrj.SolrServerException: IOException occured when talking to server at: http://localhost:8080/solr
at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:507)
at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:199)
at org.apache.solr.client.solrj.request.AbstractUpdateRequest.process(AbstractUpdateRequest.java:118)
at org.apache.solr.client.solrj.SolrServer.add(SolrServer.java:116)
at org.apache.solr.client.solrj.SolrServer.add(SolrServer.java:102)
at com.cc.solr.SolrDemo.index(SolrDemo.java:21)
at com.cc.solr.TestSolrDemo.testIndex(TestSolrDemo.java:16)
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:483)
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)
Caused by: org.apache.http.NoHttpResponseException: The target server failed to respond
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:143)
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:57)
at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:260)
at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:283)
at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:251)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.receiveResponseHeader(ManagedClientConnectionImpl.java:197)
at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:271)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:123)
at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:682)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:486)
at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:863)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57)
at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:395)
... 29 more
I think here is something wrong in my computer but I can not figure out.
I have tried solr 4.6.0 and solr 4.7.2,both of them failed.
It fails when running this code:
final HttpResponse response = httpClient.execute(method);
in HttpSolrServer.java(line number 395 in 4.7.2)
But when I copied the project to my roommate's computer ,it worked fine.
It's very wierd.It seems that the request is successfully accepted by server and if I change my code like:
public static void index() throws SolrServerException, IOException {
String url = "http://localhost:8080/solr";
HttpSolrServer server = new HttpSolrServer(url);
server.setSoTimeout(10000);
SolrInputDocument doc = new SolrInputDocument();
doc.addField("id", "3");
doc.addField("name", "name3");
doc.addField("content", "cold today3");
try{
server.add(doc);
}catch(Exception e){
e.printStackTrace(); //time out
}
server.commit();
}
It still prints exception message but it works...

Related

java.lang.IllegalAccessError: tried to access method org.openqa.selenium.remote.http.ClientConfig

I'm getting this error when I try to run a testCase from eclipse:
I'm using eclipse, Appium-Server-GUI-windows-1.22.3-4, Android 4:
java-client-8.2.1.jar
I need your help:
Code:
#Test
public void test() throws MalformedURLException{
//fail("Not yet implemented");
URL link = new URL("http://127.0.0.1:4723/wd/hub");
//AndroidDriver driver;
DesiredCapabilities capacidades = new DesiredCapabilities();
capacidades.setCapability("platformName", "Android");
capacidades.setCapability("appium:platformVersion", "13");
capacidades.setCapability("appium:appActivity", "com.BancaxcxcxActivity");
capacidades.setCapability("appium:appPackage", "com.banxxxv40");
capacidades.setCapability("appium:deviceName", "sdk_gphone64_x86_64");
// Inicio driver
AndroidDriver driver = new AndroidDriver(link ,capacidades);
}
error:
java.lang.IllegalAccessError: tried to access method org.openqa.selenium.remote.http.ClientConfig.<init>
(Ljava/net/URI;
Ljava/time/Duration;
Ljava/time/Duration;
Lorg/openqa/selenium/remote/http/Filter;
Ljava/net/Proxy;Lorg/openqa/selenium/Credentials;)
V from class io.appium.java_client.AppiumClientConfig
at io.appium.java_client.AppiumClientConfig.<init>(AppiumClientConfig.java:62)
at io.appium.java_client.AppiumClientConfig.defaultConfig(AppiumClientConfig.java:79)
at io.appium.java_client.remote.AppiumCommandExecutor.<init>(AppiumCommandExecutor.java:109)
at io.appium.java_client.AppiumDriver.<init>(AppiumDriver.java:92)
at io.appium.java_client.android.AndroidDriver.<init>(AndroidDriver.java:117)
at consolePruebasTest.TestMovil.test(TestMovil.java:49)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
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: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)
I'm trying to do a initial conecction with emulated device.
java-client 8.2.1 has issues with resolving dependencies: https://github.com/appium/java-client/issues/1812
Upgrade to 8.3.0 and check.

Dropwizard FileNotFoundException whilst the file is present and seen by debugger

I am testing my endpoint built with dropwizard, but something goes wrong:
#Test
public void testPostWithFileSuccess() throws Exception
{
FileDataBodyPart filePart = new FileDataBodyPart("file", new File(fixture("resources/testImage.jpg")));
filePart.setContentDisposition(FormDataContentDisposition.name("file").fileName("testImage.jpg").build());
FormDataMultiPart request = new FormDataMultiPart();
request.field("data", fixture("resources/postWithFileSuccess.json"), MediaType.APPLICATION_JSON_TYPE);
request.bodyPart(filePart);
WebTarget target = mClient.target("http://localhost:8080/crackers").register(MultiPartFeature.class);
Response response = target
.request()
.post(Entity.entity(request, MediaType.MULTIPART_FORM_DATA));
assertThat(response.getStatus()).isEqualTo(200);
}
What actually happens is the test fails on .post(Entity.entity(request, MediaType.MULTIPART_FORM_DATA)); with the following expection:
javax.ws.rs.ProcessingException: java.io.FileNotFoundException: Invalid file path
at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:287)
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:252)
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:684)
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:681)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:681)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:437)
at org.glassfish.jersey.client.JerseyInvocation$Builder.post(JerseyInvocation.java:343)
at org.example.project.resources.CrackersTest.testPostWithFileSuccess(CrackersTest.java:201)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:48)
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.runners.ParentRunner.run(ParentRunner.java:309)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.io.FileNotFoundException: Invalid file path
at java.io.FileInputStream.(FileInputStream.java:133)
at org.glassfish.jersey.message.internal.FileProvider.writeTo(FileProvider.java:115)
at org.glassfish.jersey.message.internal.FileProvider.writeTo(FileProvider.java:67)
at org.glassfish.jersey.media.multipart.internal.MultiPartWriter.writeTo(MultiPartWriter.java:232)
at org.glassfish.jersey.media.multipart.internal.MultiPartWriter.writeTo(MultiPartWriter.java:79)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130)
at org.glassfish.jersey.client.ClientRequest.doWriteEntity(ClientRequest.java:517)
at org.glassfish.jersey.client.ClientRequest.writeEntity(ClientRequest.java:499)
at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:388)
at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:285)
... 42 more
I'm not completely sure, as if the file was not present or the path would have been wrong, an Exception would have been thrown on new File(...) declaration.
There is obviously something wrong with filePart, but what? If I comment request.bodyPart(filePart); out, the test just fails with a comparison error (that's expected).
The issue is that fixture(...) method returns Resources.toString(Resources.getResource(filename), charset).trim(), hence debugger sees the file, but post(...) can't process it.
To fix the issue, instead of
new File(fixture("resources/testImage.jpg"))
I should have used
new File(Resources.getResource("resources/testImage.jpg").toURI())
Complete fixed method listing:
#Test
public void testPostWithFileSuccess() throws Exception
{
FileDataBodyPart filePart = new FileDataBodyPart("file", new File(Resources.getResource("resources/testImage.jpg").toURI()));
filePart.setContentDisposition(FormDataContentDisposition.name("file").fileName("testImage.jpg").build());
FormDataMultiPart request = new FormDataMultiPart();
request.field("data", fixture("resources/postWithFileSuccess.json"), MediaType.APPLICATION_JSON_TYPE);
request.bodyPart(filePart);
WebTarget target = mClient.target("http://localhost:8080/crackers").register(MultiPartFeature.class);
Response response = target
.request()
.post(Entity.entity(request, MediaType.MULTIPART_FORM_DATA));
assertThat(response.getStatus()).isEqualTo(200);
}

REST Java client API: Release connection before allocating another

I'm calling a REST service using this test code:
public class TestRESTServices {
private static final String BASE_URL = "http://localhost/ma.ge.persistence-1.0/rest/reference";
private static URI uri = UriBuilder.fromUri(BASE_URL).port(8080).build();
private static Client client = ClientBuilder.newClient();
#Test
public void createAndDeleteAReference() {
Reference r = ReferenceFactory.createReference("Maz",
"dummy", 1.7);
Response response = client.target(uri).request().post(Entity.entity(r, MediaType.APPLICATION_JSON));
assertEquals(Response.Status.CREATED, response.getStatusInfo());
URI referenceURI = response.getLocation();
// Get the posted reference
response = client.target(referenceURI).request().get();
Reference retreivedRef = response.readEntity(Reference.class);
assertEquals(Response.Status.OK, response.getStatusInfo());
assertEquals(retreivedRef.getName(), r.getName());
}
But I get the following error:
javax.ws.rs.ProcessingException: Unable to invoke request
at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:287)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:407)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilder.get(ClientInvocationBuilder.java:159)
at ma.gesto.persistence.TestRESTServices.createAndDeleteAReference(TestRESTServices.java:34)
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.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: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)
Caused by: java.lang.IllegalStateException: Invalid use of BasicClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.
at org.apache.http.impl.conn.BasicClientConnectionManager.getConnection(BasicClientConnectionManager.java:162)
at org.apache.http.impl.conn.BasicClientConnectionManager$1.getConnection(BasicClientConnectionManager.java:139)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:456)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:283)
... 26 more
The Client interface represents external resources. As such, it is a critical mistake to create and store one in a static variable. This is wrong:
private static Client client = ClientBuilder.newClient();
This is ok for unit testing:
private Client client;
#Before
public void setUp() {
this.client = ClientBuilder.newClient();
}
#After
public void tearDown() {
this.client.close();
}
In normal code you would want to wrap Client usage in a try-with-resources or try..finally:
Client client = ClientBuilder.newClient();
try {
// use the client to make requests
} finally {
client.close();
}
Ideally there would be a way to manage a pool of Client instances for reuse.
You also need to close your Response to free up the connection.
See explanations here:
Resteasy Client keeping connection allocated after a method throws an Exception

MockMVC and Mockito returns Status expected <200> but was <415>

I'm testing an api endpoint which works from a http poster (namely PAW) but I cant get a test in the code to pass.
I'm new to both Mockito and MockMVC so any help would be appreciated.
Test below:
#Test
public void createPaymentTest() throws Exception {
User user = new User("ben", "password", "a#a.com");
SuccessResponseDTO successDTO = new SuccessResponseDTO();
successDTO.setSuccess(true);
when(userService.getLoggedInUser()).thenReturn(user);
when(paymentService.makePayment(Mockito.any(PaymentRequestDTO.class), Mockito.any(User.class))).thenReturn(successDTO.getSuccess());
this.mockMvc.perform(post("/payment")).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultHandlers.print())
.andExpect(jsonPath("$.success").value(successDTO.getSuccess()));
}
SuccessResponseDTO just contains one attribute, a boolean 'success'.
The method it's testing is below:
#RequestMapping(value = "/payment", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public SuccessResponseDTO createPayment(#RequestBody PaymentRequestDTO payment) {
User loggedInUser = userService.getLoggedInUser();
LOGGER.info("Logged in user found...creating payment...");
Assert.notNull(payment.getAccountId(), "Missing user account id");
Assert.notNull(payment.getPayeeAccountNumber(), "Missing payee acount number");
Assert.notNull(payment.getPayeeName(), "Missing payee name");
Assert.notNull(payment.getPayeeSortCode(), "Missing payee sort code");
Assert.notNull(payment.getPaymentAmount(), "Missing payee amount");
Assert.notNull(payment.getPaymentDescription(), "Missing payment description");
Boolean paymentResult = paymentService.makePayment(payment, loggedInUser);
SuccessResponseDTO successResponse = new SuccessResponseDTO();
successResponse.setSuccess(paymentResult);
return successResponse;
}
Can anyone shed light on the stack trace:
java.lang.AssertionError: Status expected:<200> but was:<415>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
at org.springframework.test.web.servlet.result.StatusResultMatchers$5.match(StatusResultMatchers.java:546)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:141)
at com.capco.living.controller.PaymentControllerTest.createPaymentTest(PaymentControllerTest.java:69)
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.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)
HTTP Error 415 Unsupported media type - means that you send the data which is not supported by the service. In this case it means that you don't set the Content-Type header and actual content in the request. I suppose the JSON is expected content, so your call should look like this:
this.mockMvc.perform(post("/payment").contentType(MediaType.APPLICATION_JSON)
.content("{\"json\":\"request to be send\"}"))
.andExpect(status().isOk())
.and_the_rest_of_validation_part
You might also be missing some annotations on your controller class. Make sure you use #EnableWebMvc and #Controller
Check out this answer for details
Also you might add accept
mockMvc.perform(post("/api/sender/sms/")
.accept(MediaType.APPLICATION_JSON_UTF8)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content("{ \"serviceName\":\"serviceName\", \"apiId\":\"apiId\", \"to\":\"to\", \"msg\":\"msg\" }")
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();

Creation of Abdera Client fails

Creating the apache Abdera client is failing
Part of my code is
Abdera abdera = new Abdera();
AbderaClient abderaClient = new AbderaClient(abdera);
This is throwing me...
java.lang.RuntimeException: java.lang.NoSuchMethodException: org.apache.abdera.protocol.client.cache.LRUCacheFactory.<init>(org.apache.abdera.Abdera)
at org.apache.abdera.util.Discover.locate(Discover.java:37)
at org.apache.abdera.util.Discover.locate(Discover.java:21)
at org.apache.abdera.util.ServiceUtil.newInstance(ServiceUtil.java:142)
at org.apache.abdera.protocol.client.AbderaClient.initCacheFactory(AbderaClient.java:132)
at org.apache.abdera.protocol.client.AbderaClient.<init>(AbderaClient.java:108)
at org.apache.abdera.protocol.client.AbderaClient.<init>(AbderaClient.java:9
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
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.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.runners.ParentRunner.run(ParentRunner.java:309)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:65)
Caused by: java.lang.NoSuchMethodException: org.apache.abdera.protocol.client.cache.LRUCacheFactory.<init>(org.apache.abdera.Abdera)
at java.lang.Class.getConstructor0(Class.java:2706)
at java.lang.Class.getConstructor(Class.java:1657)
at org.apache.abdera.util.Discover.load(Discover.java:149)
at org.apache.abdera.util.Discover.locate(Discover.java:33)
... 30 more
Any help !!
Apparently looks like a bug in the following method of AbderaClient; which is using reflection to locate a constructor for LRUCacheFactory:
private CacheFactory initCacheFactory() {
CacheFactory cacheFactory =
(CacheFactory)Discover.locate(
CacheFactory.class.getName(),
LRUCacheFactory.class.getName(),
abdera);
return cacheFactory;
}
Check if there is any such constructor in your version of LRUCacheFactory.
Suggesting to switch to latest Abdera release (1.1.3). However, I found a workaround as well in a forum. Try if it is working.
AbderaClient client;
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
try {
ClassLoader cl = this.getClass().getClassLoader();
Thread.currentThread().setContextClassLoader(cl);
Abdera abdera = new Abdera();
client = new AbderaClient(abdera);
// Do something with client
} finally {
// Restore original classloader
Thread.currentThread().setContextClassLoader(originalClassLoader);
}
Refer to this link for more details regarding this workaround.

Categories

Resources