WireMock fails with NoSuchMethodError HttpServletResponse.getHeader - java

I'm trying to use WireMock in my JUnit tests to mock calls to an external API.
public class ExampleWiremockTest {
#Rule
public WireMockRule wireMockRule = new WireMockRule(9999);
#Before
public void setUp() {
stubFor(get(urlEqualTo("/bin/sillyServlet"))
.willReturn(aResponse()
.withStatus(200)
.withBody("Hello WireMock!")
)
);
}
#Test
public void testNothing() throws URISyntaxException, IOException {
URI uri = new URIBuilder().setScheme("http")
.setHost("localhost")
.setPort(9999)
.setPath("/bin/sillyServlet")
.build();
HttpGet httpGet = new HttpGet(uri);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity);
assertThat(body, is("Hello WireMock!"));
}
}
The code compiles but when I run my test, WireMock throws an HTTP 500 that seems to be caused by an inconsistency in the underlying Servlet API version.
Running com.example.core.ExampleWiremockTest
[main] INFO wiremock.org.eclipse.jetty.util.log - Logging initialized #1030ms
[main] INFO wiremock.org.eclipse.jetty.server.Server - jetty-9.2.z-SNAPSHOT
[main] INFO wiremock.org.eclipse.jetty.server.handler.ContextHandler - Started w.o.e.j.s.ServletContextHandler#ef9296d{/__admin,null,AVAILABLE}
[main] INFO wiremock.org.eclipse.jetty.server.handler.ContextHandler - Started w.o.e.j.s.ServletContextHandler#659a969b{/,null,AVAILABLE}
[main] INFO wiremock.org.eclipse.jetty.server.NetworkTrafficServerConnector - Started NetworkTrafficServerConnector#723d73e1{HTTP/1.1}{0.0.0.0:9999}
[main] INFO wiremock.org.eclipse.jetty.server.Server - Started #1168ms
[qtp436546048-16] INFO /__admin - RequestHandlerClass from context returned com.github.tomakehurst.wiremock.http.AdminRequestHandler. Normalized mapped under returned 'null'
[qtp436546048-20] INFO / - RequestHandlerClass from context returned com.github.tomakehurst.wiremock.http.StubRequestHandler. Normalized mapped under returned 'null'
[qtp436546048-20] WARN wiremock.org.eclipse.jetty.servlet.ServletHandler - Error for /bin/sillyServlet
java.lang.NoSuchMethodError: javax.servlet.http.HttpServletResponse.getHeader(Ljava/lang/String;)Ljava/lang/String;
at wiremock.org.eclipse.jetty.servlets.GzipFilter.doFilter(GzipFilter.java:322)
at wiremock.org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at wiremock.org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585)
at wiremock.org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
at wiremock.org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
at wiremock.org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
at wiremock.org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at wiremock.org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110)
at wiremock.org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at wiremock.org.eclipse.jetty.server.Server.handle(Server.java:499)
at wiremock.org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310)
at wiremock.org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
at wiremock.org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
at wiremock.org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
at wiremock.org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
at java.lang.Thread.run(Thread.java:745)
[qtp436546048-20] WARN wiremock.org.eclipse.jetty.server.HttpChannel - /bin/sillyServlet
java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.isAsyncStarted()Z
at wiremock.org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:684)
at wiremock.org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
at wiremock.org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
at wiremock.org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
at wiremock.org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at wiremock.org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110)
at wiremock.org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at wiremock.org.eclipse.jetty.server.Server.handle(Server.java:499)
at wiremock.org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310)
at wiremock.org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
at wiremock.org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
at wiremock.org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
at wiremock.org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
at java.lang.Thread.run(Thread.java:745)
[qtp436546048-20] WARN wiremock.org.eclipse.jetty.server.HttpChannel - Could not send response error 500: java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.isAsyncStarted()Z
[main] INFO wiremock.org.eclipse.jetty.server.NetworkTrafficServerConnector - Stopped NetworkTrafficServerConnector#723d73e1{HTTP/1.1}{0.0.0.0:9999}
[main] INFO wiremock.org.eclipse.jetty.server.handler.ContextHandler - Stopped w.o.e.j.s.ServletContextHandler#659a969b{/,null,UNAVAILABLE}
[main] INFO wiremock.org.eclipse.jetty.server.handler.ContextHandler - Stopped w.o.e.j.s.ServletContextHandler#ef9296d{/__admin,null,UNAVAILABLE}
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 1.577 sec <<< FAILURE! - in com.example.core.ExampleWiremockTest
I do have other libraries in my classpath that rely on different versions of Jetty, which I suppose is the cause of the problem.
WireMock uses Jetty 9.2.13, I also have a transitive dependency on Cobertura, which relies on 6.1.14
I was originally trying to use the following dependency:
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>2.6.0</version>
</dependency>
I switched to the standalone Jar version, hoping it would help me avoid the conflict but the result is exactly the same.
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-standalone</artifactId>
<version>2.6.0</version>
</dependency>

Check your servlet-api version, you likely are using an old version.
Both of those methods were added in Servlet 3.0
HttpServletResponse.getHeader(String name)
HttpServletRequest.isAsyncStarted()
You probably have the Servlet 2.5 (or Servlet 2.4) jar in your classpath.

As mentioned, in the question, one of the libraries I was using had a dependency on Cobertura, which in turn introducde a dependency on Servlet API 2.5 (both as a transitive dependency via an older verison of Jetty and a direct dependency).
Excluding the artifact from the original dependency (the one dependent on cobertura) allowed me to run my test successfully.
<dependency>
<groupId>com.cognifide.slice</groupId>
<artifactId>slice-core-api</artifactId>
<version>${slice.version}</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.mortbay.jetty</groupId>
<artifactId>servlet-api-2.5</artifactId>
</exclusion>
</exclusions>
</dependency>

Related

Null Pointer exception while running Jmeter test in Java

Following is my simple code to run jmeter test plan in Java8.
import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.protocol.http.sampler.HTTPSampler;
import org.apache.jmeter.testelement.TestPlan;
import org.apache.jmeter.threads.ThreadGroup;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;
public class JmxSuite {
public static void main(String[] args){
StandardJMeterEngine jmeter = new StandardJMeterEngine();
JMeterUtils.setJMeterHome("C:\\PLACES\\apache-jmeter-2.11");
HashTree testPlanTree = new HashTree();
HTTPSampler httpSampler = new HTTPSampler();
httpSampler.setDomain("exapmle.com");
httpSampler.setPort(80);
httpSampler.setPath("/");
httpSampler.setMethod("GET");
LoopController loopController = new LoopController();
loopController.setLoops(1);
loopController.addTestElement(httpSampler);
loopController.setFirst(true);
loopController.initialize();
ThreadGroup threadGroup = new ThreadGroup();
threadGroup.setNumThreads(1);
threadGroup.setRampUp(1);
threadGroup.setSamplerController(loopController);
TestPlan testPlan = new TestPlan("RKSV Jmeter Testing");
testPlanTree.add("testPlan", testPlan);
testPlanTree.add("loopController", loopController);
testPlanTree.add("threadGroup", threadGroup);
testPlanTree.add("httpSampler", httpSampler);
jmeter.configure(testPlanTree);
jmeter.run();
}
}
But I am keep getting the following error while running it.
INFO 2016-04-07 15:40:44.060 [jmeter.e] (): Listeners will be started after enabling running version
INFO 2016-04-07 15:40:44.079 [jmeter.e] (): To revert to the earlier behaviour, define jmeterengine.startlistenerslater=false
INFO 2016-04-07 15:40:44.108 [jmeter.p] (): No response parsers defined: text/html only will be scanned for embedded resources
INFO 2016-04-07 15:40:44.115 [jmeter.p] (): Maximum connection retries = 10
INFO 2016-04-07 15:40:44.121 [jmeter.e] (): Running the test!
INFO 2016-04-07 15:40:44.141 [jmeter.s] (): List of sample_variables: []
INFO 2016-04-07 15:40:44.141 [jmeter.s] (): List of sample_variables: []
Exception in thread "main" java.lang.NullPointerException
at org.apache.jmeter.util.JMeterUtils.setProperty(JMeterUtils.java:885)
at org.apache.jmeter.threads.JMeterContextService.startTest(JMeterContextService.java:92)
at org.apache.jmeter.engine.StandardJMeterEngine.run(StandardJMeterEngine.java:313)
at JmxSuite.main(JmxSuite.java:48)
And following is my pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Places</groupId>
<artifactId>Places</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.apache.jmeter</groupId>
<artifactId>ApacheJMeter_java</artifactId>
<version>2.11</version>
</dependency>
<dependency>
<groupId>org.apache.jmeter</groupId>
<artifactId>ApacheJMeter_http</artifactId>
<version>2.11</version>
</dependency>
</dependencies>
</project>
What could be the possible reason for it?
I have used code from 4th topic from this 5 ways to run jmeter
You're missing few lines from the article, double check your code, to wit:
JMeterUtils.loadJMeterProperties("C:\\PLACES\\apache-jmeter-2.11\\bin\\jmeter.properties");
JMeterUtils.initLogging();
JMeterUtils.initLocale();
Also there is an example project jmeter-from-code which can be used as a reference or skeleton.
Also consider using latest version of JMeter, for the moment it's Apache JMeter 2.13
The error occurs because the internal Properties-object of JMeterUtils is null at this point. Add the following line to your code to initalize this object:
JMeterUtils.loadJMeterProperties("/path/to/your/jmeter/bin/jmeter.properties");
EDIT: Instead of doing it all manually you should call
JMeterUtils.initializeProperties("/path/to/your/jmeter/bin/jmeter.properties");
which is the correct way and does all the initalizing of logging and locale internally.

Openstack4j: Error 400 authenticate() got an unexpected keyword argument 'username'

using openstack4j, the OpenStack SDK for Java, I have an error when I try to authenticate.
OSClient os = OSFactory.builder().endpoint("http://enpoint:5000/v2.0/")
.credentials("***", "***").tenantName("****").authenticate();
The error is:
400 authenticate() got an unexpected keyword argument 'username'
The library is included using maven as decumented here, using this dependency;
<dependency>
<groupId>org.pacesys</groupId>
<artifactId>openstack4j</artifactId>
<version>2.0.0</version>
<classifier>withdeps</classifier>
</dependency>

java.lang.LinkageError on Websphere while trying to load HttpUriRequest

I'm using CUPS4J for my project, which depends on http-client, http-core, and slf4j.
To resolve dependencies we use Maven, and I have defined dependencies as follows:
<dependency>
<groupId>cups4j</groupId>
<artifactId>cups4j</artifactId>
<version>0.6.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.0.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
The cups4j dependency is on our ArtiFactory server (I couldn't find it online).
Everything works like a charm if I create a sample main method to print some document and launch it as a java application.
When I publish my classes to the Websphere server and call that method from a webpage, it generates a java.lang.LinkageError.
This is the relevant part of the stacktrace:
Caused by: java.lang.LinkageError: loader constraint violation: loader "org/eclipse/osgi/internal/baseadaptor/DefaultClassLoader#208c132" previously initiated loading for a different type with name "org/apache/http/client/methods/HttpUriRequest" defined by loader "com/ibm/ws/classloader/CompoundClassLoader#1e0f797"
at java.lang.ClassLoader.defineClassImpl(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:260)
at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.defineClass(DefaultClassLoader.java:188)
at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.defineClass(ClasspathManager.java:580)
at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findClassImpl(ClasspathManager.java:550)
at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClassImpl(ClasspathManager.java:481)
at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass_LockClassName(ClasspathManager.java:460)
at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass(ClasspathManager.java:447)
at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.findLocalClass(DefaultClassLoader.java:216)
at org.eclipse.osgi.internal.loader.BundleLoader.findLocalClass(BundleLoader.java:393)
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:469)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:422)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:410)
at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
at java.lang.ClassLoader.loadClass(ClassLoader.java:612)
at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:584)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:708)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:700)
at org.cups4j.operations.IppOperation.sendRequest(IppOperation.java:207)
at org.cups4j.operations.IppOperation.request(IppOperation.java:76)
at org.cups4j.CupsPrinter.print(CupsPrinter.java:113)
at it.dropcomp.tasks.print.PrinterService.printPDF(PrinterService.java:160)
This is the method that prints the PDF (Inside it.dropcomp.tasks.print.PrinterService):
public void printPDF() throws RemoteServiceException {
/*
* generatedPDF is defined as File, and it's properly initialized
* before calling this method.
*/
if(generatedPDF == null) {
throw new RemoteServiceException("You must generate a file first!");
}
try {
CupsPrinter selectedPrinter = new CupsPrinter(
new URL(Constants.PRINTER_FULL_URL),
Constants.PRINTER_NAME, true
);
InputStream is = new FileInputStream(generatedPDF);
PrintJob pj = new PrintJob.Builder(is).build();
selectedPrinter.print(pj); //this is line 160
} catch (Exception e) {
LOG.error("Exception", e);
throw new RemoteServiceException(e);
}
}
It seems that HttpUriRequest already exists and makes conflict with the one provided by the httpclient library from Apache, but if I try removing that dependency from pom.xml, I get a NoClassDefFoundException for that class.
If it matters, my IDE is Eclipse Luna.
How can I solve this exception?
WebSphere uses also httpclient library which may conflict with one you are providing.
Try to create isolated shared library in admin console via Environment > Shared Libraries. Put http-*, slf4j and cups4j jars there and associate that shared library with your application.

Error creating JClouds SwiftApi: Provider org.jclouds.openstack.keystone.v2_0.KeystoneApiMetadata could not be instantiated

I have some code for connecting to a JClouds swift storage container which works fine in its own test area, but once I integrate into my project, I get an error:
Exception in thread "main" java.util.ServiceConfigurationError:
org.jclouds.apis.ApiMetadata: Provider
org.jclouds.openstack.keystone.v2_0.KeystoneApiMetadata could not be
instantiated: java.lang.IllegalStateException:
java.lang.reflect.InvocationTargetException
This is the code which fails on the ContextBuilder line:
private SwiftApi swiftApi;
public JCloudsConnector(String username, String password, String endpoint) {
String provider = "openstack-swift";
Properties overrides = new Properties();
overrides.setProperty("jclouds.mpu.parallel.degree", "" + Runtime.getRuntime().availableProcessors());
swiftApi = ContextBuilder.newBuilder(provider)
.endpoint(endpoint)
.credentials(username, password)
.overrides(overrides)
.buildApi(SwiftApi.class);
}
I am using the same dependencies (JClouds version 1.7.3) so I can't understand what the problem might be since both are run in the same environment.
Thanks to Ignasi Barrera, I was able to sort this by adding an entry for Guava 15.0 in my maven POM file:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>15.0</version>
</dependency>

ElasticSearch: xerial.snappy error FAILED_TO_LOAD_NATIVE_LIBRARY

I'm trying running ElasticSearch client and getting xerial.snappy error FAILED_TO_LOAD_NATIVE_LIBRARY.
I'm using elastic search v. 0.20.5:
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>0.20.5</version>
</dependency>
and also added snappy v.1.0.4.1 into my dependency(but it did not help either):
<dependency>
<groupId>org.xerial.snappy</groupId>
<artifactId>snappy-java</artifactId>
<version>1.0.4.1</version>
</dependency>
here is the error I'm getting (my app continues to run, but I suspect compression lib is not in use)
INFO Log4jESLogger.internalInfo - [Human Top II] loaded [], sites []
DEBUG Log4jESLogger.internalDebug - using [UnsafeChunkDecoder] decoder
DEBUG Log4jESLogger.internalDebug - failed to load xerial snappy-java
org.xerial.snappy.SnappyError: [FAILED_TO_LOAD_NATIVE_LIBRARY] null
at org.xerial.snappy.SnappyLoader.load(SnappyLoader.java:229)
at org.xerial.snappy.Snappy.<clinit>(Snappy.java:44)
at org.elasticsearch.common.compress.snappy.xerial.XerialSnappy.<clinit>(XerialSnappy.java:42)
at org.elasticsearch.common.compress.CompressorFactory.<clinit>(CompressorFactory.java:58)
at org.elasticsearch.client.transport.TransportClient.<init>(TransportClient.java:161)
at org.elasticsearch.client.transport.TransportClient.<init>(TransportClient.java:109)
My code that generates this issue:
public static void main(String[] args)
{
// Error happens during client creation...
Client client = new TransportClient().addTransportAddress(new InetSocketTransportAddress("localhost", 9300));
try
{
SearchResponse res = client.prepareSearch().execute().actionGet();
SearchHits hits = res.getHits();
}
finally
{
client.close();
}
}
Can anyone shed some light into this issue? How to make snappy to load native lib? I'm currently on Win7-64, but want to be running on AWS(centOS,RH,etc)

Categories

Resources