HTTPClient Example - Exception in thread "main" java.lang.NoSuchFieldError: INSTANCE - java

I am using HttpClient components from Apache for the following simple program and I see the below exception:
Exception in thread "main" java.lang.NoSuchFieldError: INSTANCE
at org.apache.http.impl.io.DefaultHttpRequestWriterFactory.(DefaultHttpRequestWriterFactory.java:52)
at org.apache.http.impl.io.DefaultHttpRequestWriterFactory.(DefaultHttpRequestWriterFactory.java:56)
at org.apache.http.impl.io.DefaultHttpRequestWriterFactory.(DefaultHttpRequestWriterFactory.java:46)
at org.apache.http.impl.conn.ManagedHttpClientConnectionFactory.(ManagedHttpClientConnectionFactory.java:72)
at org.apache.http.impl.conn.ManagedHttpClientConnectionFactory.(ManagedHttpClientConnectionFactory.java:84)
at org.apache.http.impl.conn.ManagedHttpClientConnectionFactory.(ManagedHttpClientConnectionFactory.java:59)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager$InternalConnectionFactory.(PoolingHttpClientConnectionManager.java:487)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.(PoolingHttpClientConnectionManager.java:147)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.(PoolingHttpClientConnectionManager.java:136)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.(PoolingHttpClientConnectionManager.java:112)
at org.apache.http.impl.client.HttpClientBuilder.build(HttpClientBuilder.java:726)
at com.starwood.rms.controller.property.HttpExample.main(HttpExample.java:14)
public class HttpExample {
public static void main(String[] args) {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("https://www.google.com/?q=java");
try {
HttpResponse response = client.execute(request);
System.out.println(response.getStatusLine());
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am using
Httpclient-4.3.3.jar
Httpcore-4.3.2.jar
Any ideas?

I had this problem with Hadoop. It used an old version of httpclient-4.2.5.jar and httpcore-4.2.5.jar in their shared lib.
I solved this by shading parts via the maven-shade-plugin
<relocations>
<relocation>
<pattern>org.apache.http</pattern>
<shadedPattern>shaded.org.apache.http</shadedPattern>
</relocation>
</relocations>

Looking at the source code of DefaultHttpRequestWriterFactory
package org.apache.http.impl.io;
import org.apache.http.HttpRequest;
import org.apache.http.annotation.Immutable;
import org.apache.http.io.HttpMessageWriter;
import org.apache.http.io.HttpMessageWriterFactory;
import org.apache.http.io.SessionOutputBuffer;
import org.apache.http.message.BasicLineFormatter;
import org.apache.http.message.LineFormatter;
#Immutable
public class [More ...] DefaultHttpRequestWriterFactory implements HttpMessageWriterFactory<HttpRequest> {
public static final DefaultHttpRequestWriterFactory INSTANCE = new DefaultHttpRequestWriterFactory();
private final LineFormatter lineFormatter;
public [More ...] DefaultHttpRequestWriterFactory(final LineFormatter lineFormatter) {
super();
this.lineFormatter = lineFormatter != null ? lineFormatter : BasicLineFormatter.INSTANCE;
}
public [More ...] DefaultHttpRequestWriterFactory() {
this(null);
}
public HttpMessageWriter<HttpRequest> [More ...] create(final SessionOutputBuffer buffer) {
return new DefaultHttpRequestWriter(buffer, lineFormatter);
}
}
Are you sure you are using HttpCore 4.3.2? DefaultHttpRequestWriterFactory try to resolve
BasicLineFormatter.INSTANCE
field but can not find it.
Check your classpath for libraries which could contains another BasicLineFormatter class, maybe you have a HttpCore from an old version in conflict with the 4.3.2 version.

Caused by: java.lang.NoSuchFieldError: INSTANCE
one of the solution of java.lang.NoSuchFieldError: INSTANCE : This happens if we have two diff version of same class in our classpath…. […], So we first find that class(one version of class) , click that class, select "build path", then we click "remove from build path" . by 333ccc333

I had this problem. It looks like there is a problem while initializing HttpClient with HttpClientBuilder.create().build(). If you want more immediate solution just use new DefaultHttpClient() to initialize HttpClient.
HttpClient client = new DefaultHttpClient();

This code works...without any error.. check the packages if you are using similar import .
package com.jai.http;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
public class HttpExample {
/**
* #param args
*/
public static void main(String[] args) {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("https://www.google.com/?q=java");
try {
HttpResponse response = client.execute(request);
System.out.println(response.getStatusLine());
} catch (Exception e) {
e.printStackTrace();
}
}
}

For those using Webpshere, make sure your class loading policy is set to "Parent Last", otherwise it will not work since WAS is using its own version of commons http which can be conflicting.

I had this problem too, i realized it was when we upgraded to java 1.8, i just downgraded to 1.7 and works as expected.
Not sure why the version became an issue.

I also was frustrated by this and Eclipse until I realized that similar to Pat B's Webpshere tip, it does cause issues for Eclipse if you have the dependencies in the wrong order.
Properties -> Java Build Path -> Order and Export
Play a bit around here with the order of core and client.

I have this error too, in my class path
I have httpclient-4.4.1.jar, and httpcore-4.4.1.jar
However, for some reason,the classloader loaded the class org.apache.http.message.BasicLineFormatter
from httpcore-4.0.jar in a unexpected location and caused this error
you can use below code to check which jar it is using
try{
Class cls=Class.forName('org.apache.http.message.BasicLineFormatter');
println cls.getProtectionDomain().getCodeSource().getLocation();
}catch (Error ex){
println ex
}
Hope this help~

Related

Gradle external class required by plugin on runtime

I'm creating custom Gradle plugin for internal company use. It will add few tasks to project and behaviour of one task can be customized by plugin users. Idea is to have plugin property that will contain external class name. This class must implement appropriate interface to be correctly used. Plugin's task will instantiate objects for this class and use it during execution.
Reasons for that - there are several reasonably different patterns used by different teams in company. So set of these "external classes" will be created and published. Each team can choose which one to use for their build configuration. Or even can create a new one if there are reasons for that. So I want this thing to be configurable on a build level.
I'm failing to setup this kind of dependency in build.gradle script. Let me show you code on which I'm trying to reproduce and solve issue:
buildscript{
repositories {
mavenCentral()
maven{
url "http://our-internal-nexus/repository/maven-releases/"
}
dependencies{
classpath 'my.company:myplugin:0.1'
classpath 'my.other.company:extClass:0.1'
}
}
}
apply plugin: 'my.company.myplugin'
MyInput{
managerClass = "ExtClass"
}
myplugin - artifact of my plugin, and extclass - external class that should be instantiated by plugin's task.
When I try to execute plugins task: gradle hellotask I receive error: java.lang.ClassNotFoundException: ExtClass
I put a code to hellotask class definition to show me the classpath. The only thing it shows is C:/work/Projects/development/gradle-4.0.1/lib/gradle-launcher-4.0.1.jar. So for me it looks like no path to extClass jar provided by gradle to plugin in runtime so it can't find it.
Below you can find source code of plugin and extClass if this may help.
MyPlugin
MyPlugin.java
package my.company;
import org.gradle.api.*;
//Plugin definition
public class MyPlugin implements Plugin<Project>{
#Override
public void apply(Project project){
project.getExtensions().create("MyInput", MyPluginExtension.class);
HelloTask helloTask = project.getTasks().create("helloTask", HelloTask.class);
}
}
HelloTask.java
package my.company;
import java.net.URL;
import java.net.URLClassLoader;
import org.gradle.api.*;
import org.gradle.api.tasks.*;
//Plugin task
public class HelloTask extends DefaultTask {
#TaskAction
public void action() {
//Print classpath
ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader)sysClassLoader).getURLs();
for(int i=0; i< urls.length; i++) {
System.out.println(urls[i].getFile());
}
//Try to instantiate class
try {
MyPluginExtension extension = getProject().getExtensions().findByType(MyPluginExtension.class);
Object instance = Class.forName(extension.getManagerClass()).newInstance();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
throw new GradleException("Class not found");
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new GradleException("IllegalAccessException");
} catch (InstantiationException e) {
e.printStackTrace();
throw new GradleException("InstantiationException");
}
}
}
MyPluginExtension.java
package my.company;
public class MyPluginExtension {
private String managerClass = null;
public String getManagerClass(){return this.managerClass;}
public void setManagerClass(String managerClass){ this.managerClass = managerClass;}
}
extClass
extClass.java
package my.other.company;
public class ExtClass {
public void ExtClass(){
System.out.println("Show me how it works!");
}
}
Even if you already answered your own question (you can also accept it), I would like to add a small remark:
If you want to provide an option to set a class in your plugin exception, why don't you let the user set the class directly by specifying a Class<?> instead of a String? Each class added in one of the classpath dependencies is available in the build.gradle file. You would also need to specify the package, but you could also import just like in Java. Also, Groovy does not expect you to use the .class suffix, you could simply set the class to the extension property:
import my.other.company.ExtClass
[...]
MyInput {
managerClass = ExtClass
}
ok, as always answer comes as soon as you post the question.
Needed to change managerClass = "ExtClass" to managerClass = "my.other.company.ExtClass" and everything works as expected

Mule upgrade 3.6 compiler error

I was working on mule 3.5.1, when I upgrade to mule 3.6 version, getting compile time error for following class:
import org.mule.module.jersey.MuleResponseWriter;
import com.sun.jersey.spi.container.ContainerResponse;
public class GLExportTransformer extends AbstractMessageTransformer {
public List<GLExport> methodType(#Payload MuleResponseWriter content){
List<GLExport> glExportList = (List<GLExport>) content;
System.out.println("Java payload is -->"+glExportList.getClass());
return glExportList ;
}
#Override
public Object transformMessage(MuleMessage message, String outputEncoding)throws TransformerException {
ContainerResponse cr = (ContainerResponse) message.getInvocationProperty("jersey_response");
List<GLExport> res = (List<GLExport>)cr.getResponse().getEntity();
System.out.println("Response from QB is -->"+res);
return res;
}
}
<custom-transformer name="StringToNameString" class="com.trinet.qb.utils.GLExportTransformer" doc:name="GL Export Transformer"/>
Compile time error:
The type org.mule.module.jersey.MuleResponseWriter is not visible
The import com.sun.jersey cannot be resolved
How do I resolve this?
In my Anypoint Studio shows Mule3.6 uses all jersey related jar uses 2.11 version of jar files. Using Java 1.7 version.
EDIT:
Here is my rest component(GLExportService):
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public List<GLExport> postOperation(#Payload String content) throws ParseException {
System.out.println("Content from Reporting page-->\n\n"+content+"\n\n");
JSONParser jsonParser = new JSONParser();
Object jsonObjectInstance =null;
try {
jsonObjectInstance = jsonParser.parse(new StringReader(content));
} catch (ParseException e) {
System.out.println(e.getLocalizedMessage());
}
// parse json and assign to dto as glExportList
return glExportList;
Here is my mule flows:
<http:inbound-endpoint exchange-pattern="request-response" host="${hostname}" port="${glport}" path="QBJournalExport/QBGLRest" doc:name="HTTP"/>
<jersey:resources doc:name="REST">
<component class="com.qb.rest.GLExportService"/>
</jersey:resources>
<set-session-variable variableName="accessToken" value="#[payload.get(0).get('ACCESS_TOKEN')]" doc:name="Access token"/>
<set-session-variable variableName="accessTokenSecret" value="#[payload.get(0).get('ACCESS_TOKEN_SECRET')]" doc:name="Access Secret"/>
<set-session-variable variableName="realmId" value="#[payload.get(0).get('ACCT_SYSTEM_COMPANY_ID')]" doc:name="Company ID"/>
<set-session-variable variableName="quickbooksClient" value="#[com.qb.utils.QuickbooksUtils.getQuickbooksClient(sessionVars['accessToken'],sessionVars['accessTokenSecret'],'${consumerKey}','${consumerSecret}','${appToken}',sessionVars['realmId'])]" doc:name="QB Client"/>
<custom-transformer name="StringToNameString" class="com.qb.utils.GLExportTransformer" doc:name="GL Export Transformer"/>
<set-payload value="#[com.qb.utils.CreateJournalEntry.createJournalEntry(payload,sessionVars['accessToken'],sessionVars['accessTokenSecret'],'${consumerKey}','${consumerSecret}','${appToken}', sessionVars['realmId'])]" doc:name="Create Journal Entry"/>
import org.glassfish.jersey.server.ContainerResponse;
public class GLExportTransformer extends AbstractMessageTransformer {
#Override
public Object transformMessage(MuleMessage message, String outputEncoding)throws TransformerException {
ContainerResponse cr = (ContainerResponse) message.getInvocationProperty("jersey_response");
List<GLExport> res = (List<GLExport>)cr.getEntity();
return res;
}
}
method called methodType was a dummy code.
Try making the parameter type java.util.Object, and removing the import. You are immediately casting it to List<GLExport> anyway, so you don't appear to need that type.
We indeed made MuleResponseWriter package only, but that's not the root of your problem. In Mule 3.6 we upgraded from Jersey 1.6 to 2.11. Jersey 2 is quite different, it even includes a package rename from com.sun.jersey to org.glassfish.jersey. You can find more information about the upgrade in this post, including a link to Jersey's migration guide: http://blogs.mulesoft.org/mule-3-6-api/
What I don't understand anyway, is why you need to access the ContainerResponse in your transformer instead of having your jersey resource set the message payload to the List directly.
Regards
It seems they made the class org.mule.module.jersey.MuleResponseWriter package only.
This could be because the class was never part of the public Mule API or just minor typo.
Anyways, as it is right now there is no much you can do.
The only hack is to place the transformer and any class that references org.mule.module.jersey.MuleResponseWriter inside a package named:
org.mule.module.jersey
BUT THIS IS A HACK, and I wouldn't advise it.
I'll try to find out if was made on purpose and let you know ;)

Crawling GitHub with JGit

I'm trying to crawl a GitHub Wiki with JGit.
When I try it with one URL, it worked perfectly fine. Then I tried it with another random URL and got an error.
Please see the extract of my code:
import java.io.File;
import java.io.IOException;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
public class Main {
// with this URL I get an error
String url = "https://github.com/radiant/radiant.wiki.git";
// this URL works
// String url = "https://github.com/WardCunningham/Smallest-Federated-Wiki.wiki.git";
public static void main(String[] args) {
Main m = new Main();
m.jgitTest();
System.out.println("Done!");
}
public void jgitTest() {
try {
File localPath = File.createTempFile("TestGitRepository", "");
localPath.delete();
Git.cloneRepository().setURI(url).setDirectory(localPath).call();
} catch (IOException | GitAPIException e) {
System.err.println("excepton: " + e.getMessage());
e.printStackTrace();
}
}
}
This is the stack trace:
Exception in thread "main" org.eclipse.jgit.dircache.InvalidPathException: Invalid path (contains separator ':'): How-To:-Create-an-Extension.textile
at org.eclipse.jgit.dircache.DirCacheCheckout.checkValidPathSegment(DirCacheCheckout.java:1243)
at org.eclipse.jgit.dircache.DirCacheCheckout.checkValidPathSegment(DirCacheCheckout.java:1225)
at org.eclipse.jgit.dircache.DirCacheCheckout.checkValidPath(DirCacheCheckout.java:1185)
at org.eclipse.jgit.dircache.DirCacheCheckout.processEntry(DirCacheCheckout.java:311)
at org.eclipse.jgit.dircache.DirCacheCheckout.prescanOneTree(DirCacheCheckout.java:290)
at org.eclipse.jgit.dircache.DirCacheCheckout.doCheckout(DirCacheCheckout.java:408)
at org.eclipse.jgit.dircache.DirCacheCheckout.checkout(DirCacheCheckout.java:393)
at org.eclipse.jgit.api.CloneCommand.checkout(CloneCommand.java:236)
at org.eclipse.jgit.api.CloneCommand.call(CloneCommand.java:127)
at Main.jgitTest(Main.java:21)
at Main.main(Main.java:13)
If you visit the wiki page of the URL that doesn't work (https://github.com/radiant/radiant/wiki), you will find this page: How To: Create an Extension.
The title of this page is the cause of the error: Invalid path (contains separator ':'): How-To:-Create-an-Extension.textile.
I assume I need to escape all output.
I suppose you are on windows. You can't create a file on windows having the ":" in the name. JGit should handle it somehow, so I suppose this is a bug in JGit.
I had the same problem with pure git, and this answer helped me:
git config core.protectNTFS false

Proper usage of Apache Commons Configuration

My code is the following:
package org.minuteware.jgun;
import org.apache.commons.configuration.*;
class ConfigReader {
public void getconfig() {
Configuration config;
try {
config = new PropertiesConfiguration("gun.conf");
} catch (ConfigurationException e) {
e.printStackTrace();
}
String day = config.getString("sync_overlays");
System.out.println(day);
}
}
Eclipse has two problems with this code:
For the package org.minuteware.jgun; line it says The type org.apache.commons.lang.exception.NestableException cannot be resolved. It is indirectly referenced from required .class files
For the line } catch (ConfigurationException e) { it says No exception of type ConfigurationException can be thrown; an exception type must be a subclass of Throwable
I've found ConfigurationException in Java?, but the solution provided there does not help.
The core of Apache Commons Configuration has the following runtime dependencies:
Apache Commons Lang (version 2.2, 2.3, 2.4, 2.5 or 2.6)
Apache Commons Collections (version 3.1, 3.2 or 3.2.1)
Apache Commons Logging (version 1.0.4, 1.1 or 1.1.1)
Put them in your classpath as well. Your particular problem is caused by a missing Lang dependency.
This library issue plagued me for a few days until I figure out why Apache was wanting me to use old libraries.
If you are being requested to use older Lang libraries by the compiler, ensure you are making your Apache properties file the NEW way, not the old way (which utilizes the older lang libraries).
https://commons.apache.org/proper/commons-configuration/userguide/howto_filebased.html
is the Apache site I derived my following code from, which does a basic SET operation against a file on my Windows machine.
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.FileBasedConfiguration;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
public final class Settings implements Serializable {
private Configuration config;
private String propertiesFilePath;
private FileBasedConfigurationBuilder<FileBasedConfiguration> builder;
public Settings(String propertiesFilePath) {
Parameters params = new Parameters();
File propFile = new File(propertiesFilePath);
builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
.configure(params.fileBased()
.setFile(propFile));
try {
config = builder.getConfiguration();
} catch (Exception e) {
System.out.println("Exception - Settings constructor: " + e.toString());
}
}//end constructor
public void setValue(String key, String value) throws Exception {
config.setProperty(key, value);
builder.save();
}// end setter method
}//end class

How to call a web service (described by a wsdl) from java

Knowing nothing of web services, I'm just trying to call some "isAlive" service that is described by a wsdl.
This seems to me like something that should take no more than 2-5 lines of code but I can't seem to find anything but huge long examples involving 3rd party packages etc.
Anyone has any ideas? If it is always suppose to be long maybe a good explanation as to why it has to be so complicated will also be appreciated.
I'm using Eclipse and the wsdl is SOAP.
JDK 6 comes with jax-ws, everything you need to develop a client for a web service.
I'm unable to find some simple enough examples to post , but start at https://jax-ws.dev.java.net/
Edit: here's a simple example - a client for this web service: http://xmethods.com/ve2/ViewListing.po?key=427565
C:\temp> md generated
C:\temp>"c:\Program Files\Java\jdk1.6.0_17"\bin\wsimport -keep -d generated http://www50.brinkster.com/vbfacileinpt/np.asmx?wsdl
Create PrimeClient.java which look like:
import javax.xml.ws.WebServiceRef;
import com.microsoft.webservices.*;
//the above namespace is from the generated code from the wsdl.
public class PrimeClient {
//Cant get this to work.. #WebServiceRef(wsdlLocation="http://www50.brinkster.com/vbfacileinpt/np.asmx?wsdl")
static PrimeNumbers service;
public static void main(String[] args) {
try {
service = new PrimeNumbers();
PrimeClient client = new PrimeClient();
client.doTest(args);
} catch(Exception e) {
e.printStackTrace();
}
}
public void doTest(String[] args) {
try {
System.out.println("Retrieving the port from the following service: " + service);
PrimeNumbersSoap pm = service.getPrimeNumbersSoap();
System.out.println("Invoking the getPrimeNumbersSoap operation ");
System.out.println(pm.getPrimeNumbers(100));
} catch(Exception e) {
e.printStackTrace();
}
}
}
Compile and run:
C:\temp>"c:\Program Files\Java\jdk1.6.0_17"\bin\javac -cp generated PrimeClient.java
C:\temp>"c:\Program Files\Java\jdk1.6.0_17"\bin\java -cp .;generated PrimeClient
Retrieving the port from the following service: com.microsoft.webservices.PrimeN
umbers#19b5393
Invoking the getPrimeNumbersSoap operation
1,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97
There are plugins for IDE's which generate the needed code to consume a web service for you.
After the plugin generates you the base methods you simply call a web service like that:
TransportServiceSoap service = new TransportServiceLocator().getTransportServiceSoap();
service.getCities();
Have a look at http://urbas.tk/index.php/2009/02/20/eclipse-plug-in-as-a-web-service-client/
There are three ways to write a web service client
Dynamic proxy
Dynamic invocation interface (DII)
Application client
Example for Dynamic Proxy Client
import java.net.URL;
import javax.xml.rpc.Service;
import javax.xml.rpc.JAXRPCException;
import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceFactory;
import dynamicproxy.HelloIF;
public class HelloClient {
public static void main(String[] args) {
try {
String UrlString = "Your WSDL URL"; //
String nameSpaceUri = "urn:Foo";
String serviceName = "MyHelloService";
String portName = "HelloIFPort";
System.out.println("UrlString = " + UrlString);
URL helloWsdlUrl = new URL(UrlString);
ServiceFactory serviceFactory =
ServiceFactory.newInstance();
Service helloService =
serviceFactory.createService(helloWsdlUrl,
new QName(nameSpaceUri, serviceName));
dynamicproxy.HelloIF myProxy =
(dynamicproxy.HelloIF)
helloService.getPort(
new QName(nameSpaceUri, portName),
dynamicproxy.HelloIF.class);
System.out.println(myProxy.sayHello("Buzz"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I hope , this would solve your question.
The easiest I've found so far to use is the Idea IntelliJ wizard which - using Metro libraries - generate a very small code snippet which works fine with Java 6.

Categories

Resources