Exception in thread "Twitter4J Async Dispatcher[0]" java.lang.NoClassDefFoundError - java

I'm working on a project that analyzes real-time tweets and identify user's moods.
So I'm using twitter4j to receive real-time tweets and feeds those tweets to Stanford’s Core NLP. I'm receiving the real-time tweets correctly. But when I feed those tweets to Stanford's Core NLP i'm getting an run-time error.
PrintSampleStream Class that gets real-time tweets using twitter4j:
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import twitter4j.*;
import twitter4j.conf.*;
public class PrintSampleStream {
private String twitter_handle;
PrintSampleStream()
{
twitter_handle = null;
}
PrintSampleStream(String tw)
{
twitter_handle = tw;
}
public void twitterConnector() throws TwitterException {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true).setOAuthConsumerKey("bbbb")
.setOAuthConsumerSecret("bbbb")
.setOAuthAccessToken("bbbb")
.setOAuthAccessTokenSecret("bbbb");
TwitterStream twitterStream = new TwitterStreamFactory(cb.build())
.getInstance();
StatusListener listener = new StatusListener() {
#Override
public void onStatus(Status status) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
NLP.init();
System.out.println(status.getText() + " : " + NLP.findSentiment(status.getText()));
//storeTweets(status.getText());
//JOptionPane.showMessageDialog(null, status.getText());
}
#Override
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}
#Override
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
#Override
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
#Override
public void onStallWarning(StallWarning warning) {
System.out.println("Got stall warning:" + warning);
}
#Override
public void onException(Exception ex) {
ex.printStackTrace();
}
};
twitterStream.addListener(listener);
FilterQuery filtre = new FilterQuery();
String[] keywordsArray = {twitter_handle};
filtre.track(keywordsArray);
twitterStream.filter(filtre);
}
}
NLP Class that feeds real-time tweets received from twitter4j to Stanford's Core NLP:
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.sentiment.SentimentCoreAnnotations;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.util.CoreMap;
public class NLP {
static StanfordCoreNLP pipeline;
public static void init() {
pipeline = new StanfordCoreNLP("MyPropFile.properties");
}
public static int findSentiment(String tweet) {
int mainSentiment = 0;
if (tweet != null && tweet.length() > 0) {
int longest = 0;
Annotation annotation = pipeline.process(tweet);
for (CoreMap sentence : annotation
.get(CoreAnnotations.SentencesAnnotation.class)) {
Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class);
int sentiment = RNNCoreAnnotations.getPredictedClass(tree);
String partText = sentence.toString();
if (partText.length() > longest) {
mainSentiment = sentiment;
longest = partText.length();
}
}
}
return mainSentiment;
}
}
My run-time error is:
#laliyaD - Lalinda feels tired
Exception in thread "Twitter4J Async Dispatcher[0]" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at edu.stanford.nlp.pipeline.StanfordCoreNLP.<clinit>(StanfordCoreNLP.java:99)
at NLP.init(NLP.java:13)
at PrintSampleStream$1.onStatus(PrintSampleStream.java:38)
at twitter4j.StatusStreamImpl.onStatus(StatusStreamImpl.java:75)
at twitter4j.StatusStreamBase$1.run(StatusStreamBase.java:105)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 8 more
Actually I'm getting the real-time tweets from twitter4j. Any help?

You need to download SLF4J (Simple Logging Facade for Java) and include it in your classpath.
You'll need at least slf4j-api-1.7.21.jar and slf4j-simple-1.7.21.jar in order to be able to actually view log messages from the NLP library.
http://www.slf4j.org/download.html

java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory means that need the slf4j library in your classpath.
If you use maven, you can use this dependency:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.21</version>
</dependency>

Related

Twitter4j streaming api call throwing class not found exception

I am writing a utility class using twitter4j for multiple purpose. I am able to search tweets based on Hashtags, location etc but Streaming API is not working for me.
I have written a class with main method after following a blog as follows but I am getting class not found error.I am new to java.
package mytweetapp;
import twitter4j.FilterQuery;
import twitter4j.StallWarning;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.TwitterException;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.conf.ConfigurationBuilder;
public class Stream {
public static void main(String[] args) throws TwitterException {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("*****")
.setOAuthConsumerSecret(
"*******")
.setOAuthAccessToken(
"*****")
.setOAuthAccessTokenSecret(
"*****");
TwitterStreamFactory tf = new TwitterStreamFactory(cb.build());
TwitterStream twitter = tf.getInstance();
StatusListener listener = new StatusListener() {
public void onStatus(Status status) {
System.out
.println("#" + status.getUser().getScreenName() + " - " + status
.getText());
}
public void onDeletionNotice(
StatusDeletionNotice statusDeletionNotice) {
System.out
.println("Got a status deletion notice id:" + statusDeletionNotice
.getStatusId());
}
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out
.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
public void onScrubGeo(long userId, long upToStatusId) {
System.out
.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
public void onException(Exception ex) {
ex.printStackTrace();
}
#Override
public void onStallWarning(StallWarning arg0) {
// TODO Auto-generated method stub
}
};
FilterQuery fq = new FilterQuery();
String keywords[] = { "Mango", "Banana" };
fq.track(keywords);
twitter.addListener(listener);
twitter.filter(fq);
}
Error
Exception in thread "main" java.lang.NoClassDefFoundError: twitter4j/internal/http/HttpClientWrapperConfiguration
at twitter4j.TwitterStreamFactory.<clinit>(TwitterStreamFactory.java:40)
at mytweetapp.Stream.main(Stream.java:23)
Caused by: java.lang.ClassNotFoundException: twitter4j.internal.http.HttpClientWrapperConfiguration
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 2 more
My current hypothesis is that the problem is because of mixing core and stream jars of different versions (so e.g. TwitterStreamFactory from stream-3.0.3 expects HttpClientWrapperConfiguration to be available on your classpath but in 4.0.4 it is no longer included. Please try having those of the same version included (and only one version of lib, so stream-3 and stream-4 being included together is no-no). If that won't work - share the whole project somewhere for more context.
As for what classpath is you can google, or read up e.g. here What is a classpath?

Why is there '0' in sun.net.www.protocol.http.HttpURLConnection.getInputStream0?

I'm executing a Babelfy program:
Here's the code:
import it.uniroma1.lcl.babelfy.Babelfy;
import it.uniroma1.lcl.babelfy.Babelfy.Matching;
import it.uniroma1.lcl.babelfy.Babelfy.AccessType;
import it.uniroma1.lcl.babelfy.data.Annotation;
import it.uniroma1.lcl.babelfy.data.BabelSynsetAnchor;
import it.uniroma1.lcl.babelnet.BabelNet;
import it.uniroma1.lcl.babelnet.BabelSense;
import it.uniroma1.lcl.babelnet.BabelSynset;
import it.uniroma1.lcl.jlt.util.Language;
public class Example
{
public static void main(String[] args) throws Exception
{
Babelfy bfy = Babelfy.getInstance(AccessType.ONLINE);
BabelNet bn = BabelNet.getInstance();
String word=" ";
String inputText = "He has a passion for music";
Annotation annotations = bfy.babelfy("3697a512-bfd4-427e-846d-9eb60f98c3bb",inputText,Matching.EXACT,Language.EN);
System.out.println("inputText: "+inputText+"\nannotations:");
for(BabelSynsetAnchor annotation : annotations.getAnnotations())
{
word=annotation.getBabelSynset().getId();
System.out.println(annotation.getAnchorText()+"\t"+word+"\t"+annotation.getBabelSynset());
//BabelSynset by = bn.getSynsetFromId(("bn:03083790n"));
for (BabelSense sense : bn.getSynsetFromId((word)))
{
if(sense.getSource().toString().equals("WN"))
System.out.println("Sense: " + sense.getLemma()+ "\tSource: " + sense.getSource().toString());
}
}
}
}
And here's the error thrown:
Exception in thread "main" java.io.FileNotFoundException: http://babelfy.org/rest?text=He%20has%20a%20passion%20for%20music&key=3697a512-bfd4-427e-846d-9eb60f98c3bb&partMatching=false&lang=EN&format=json
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at it.uniroma1.lcl.babelfy.Babelfy.babelfy(Babelfy.java:95)
at Example.main(Example.java:19)
Apart from the FileNotFoundException, why is there a '0' in the error at:
sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
Does it imply anything else?

getting error when compiling for modbus rs232

i am new in java... i am trying to read on modbus. PLC is slave device and it is configured well. my java file is unable to read modbus values.here is the code..given below. error is coming at master.init(); method. please help me in this case.
package com.mod4j;
import java.io.File;
import gnu.io.SerialPort;
import com.serotonin.io.serial.SerialParameters;
import com.serotonin.*;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.code.DataType;
import com.serotonin.modbus4j.code.RegisterRange;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.locator.BaseLocator;
import com.serotonin.modbus4j.locator.NumericLocator;
import com.serotonin.modbus4j.msg.ReadCoilsRequest;
import com.serotonin.modbus4j.msg.ReadCoilsResponse;
import com.serotonin.modbus4j.msg.ReadDiscreteInputsRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;
import com.serotonin.modbus4j.msg.ReadInputRegistersRequest;
import com.serotonin.modbus4j.msg.ReadInputRegistersResponse;
import com.serotonin.modbus4j.msg.WriteCoilRequest;
import com.serotonin.modbus4j.msg.WriteCoilResponse;
import com.serotonin.modbus4j.msg.WriteRegistersRequest;
import com.serotonin.modbus4j.msg.WriteRegistersResponse;
import gnu.io.*;
public class Modbus4JTest
{
public static void main(String[] args) throws Exception
{
try
{
SerialParameters params = new SerialParameters();
params.setCommPortId("COM1");
params.setBaudRate(9600);
params.setDataBits(8);
params.setStopBits(1);
params.setParity(0);
ModbusFactory modbusFactory = new ModbusFactory();
ModbusMaster master = modbusFactory.createRtuMaster(params);
master.setTimeout(100);
master.setRetries(3);
byte [] RIR,RHR,RDI,RCR;
int slaveId=1;
int startOffset=0;
int numberOfRegisters=10;
int numberOfBits=10;
try
{
master.init();
while (true)
{
ReadInputRegistersRequest reqRIR = new ReadInputRegistersRequest(slaveId, startOffset, numberOfRegisters);
System.out.println("ReadInputRegistersRequest reqRIR =" +reqRIR);
ReadInputRegistersResponse resRIR = (ReadInputRegistersResponse) master.send(reqRIR);
RIR = resRIR.getData();
System.out.println("InputRegisters :" + RIR);
ReadHoldingRegistersRequest reqRHR = new ReadHoldingRegistersRequest(slaveId, startOffset, numberOfRegisters);
ReadHoldingRegistersResponse resRHR = (ReadHoldingRegistersResponse) master.send(reqRHR);
RHR=resRHR.getData();
System.out.println("HoldingRegister :" + RHR);
ReadDiscreteInputsRequest reqRDI= new ReadDiscreteInputsRequest(slaveId, startOffset, numberOfBits);
ReadCoilsResponse resRDI = (ReadCoilsResponse) master.send(reqRDI);
RDI=resRDI.getData();
System.out.println("DiscreteInput :" + RDI);
ReadCoilsRequest reqRCR = new ReadCoilsRequest(slaveId, startOffset, numberOfBits);
ReadCoilsResponse resRCR = (ReadCoilsResponse) master.send(reqRCR);
RCR=resRCR.getData();
System.out.println("CoilResponce :" + RCR);
short[] sdata = null;
WriteRegistersRequest reqWR = new WriteRegistersRequest(slaveId, startOffset, sdata);
WriteRegistersResponse resWR = (WriteRegistersResponse) master.send(reqWR);
int writeOffset = 0;
boolean writeValue = true;
WriteCoilRequest reqWC = new WriteCoilRequest(slaveId, writeOffset, writeValue);
WriteCoilResponse resWC = (WriteCoilResponse) master.send(reqWC);
Thread.sleep(1000);
}//end while
}//end try
catch (Exception e)
{
e.printStackTrace();
}//end catch
finally
{
master.destroy();
}//end finally
}//end try
catch (Exception e)
{
e.printStackTrace();
}//end catch
}// end main
}//end class Modbus4JTest
this is java file i am running.
and here are the error i have got after compiling..
please suggest what went wrong and please correct me at ...
is there any step by step tutorial or any demo video please give me link at
ayyaz.nadaf#gmail.com
Exception in thread "main" java.lang.NoClassDefFoundError:
jssc/SerialPortException
at com.serotonin.io.serial.SerialUtils.openSerialPort(SerialUtils.java:94)
at com.serotonin.modbus4j.serial.SerialMaster.init(SerialMaster.java:58)
at com.serotonin.modbus4j.serial.rtu.RtuMaster.init(RtuMaster.java:45)
at com.mod4j.Modbus4JTest.main(Modbus4JTest.java:58)
Caused by: java.lang.ClassNotFoundException: jssc.SerialPortException
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 4 more
It appears you're using Modbus4J. It is based on jSSC (Java Simple Serial Connector) for serial communication, so make sure that jSSC is found while compiling (you may need to download it separately, since you're getting a ClassNotFoundException related to a jSSC class).
I don't know about any tutorial but I may suggest you to take a look at the Modbus4J forum archive. Here's a simple Modbus RTU example.

Google Analytics API- Exception in thread "main" java.lang.NoClassDefFoundError: com/google/api/client/http/HttpParser

The source code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAuthorizationRequestUrl;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.analytics.Analytics;
import com.google.api.services.analytics.Analytics.Data.Ga.Get;
import com.google.api.services.analytics.model.GaData;
import com.google.api.services.analytics.model.GaData.ColumnHeaders;
import com.google.api.services.analytics.model.Profile;
import com.google.api.services.analytics.model.Profiles;
import com.google.api.services.analytics.model.Segment;
import com.google.api.services.analytics.model.Segments;
/**
* This class displays an example of a client application using the Google API
* to access the Google Analytics data
*
*
*
*/
#SuppressWarnings("deprecation")
public class GoogleAnalyticsExample {
private static final String SCOPE = "https://www.googleapis.com/auth/analytics.readonly";
private static final String REDIRECT_URL = "urn:ietf:wg:oauth:2.0:oob";
private static final HttpTransport netHttpTransport = new NetHttpTransport();
private static final JacksonFactory jacksonFactory = new JacksonFactory();
private static final String APPLICATION_NAME = "familys";
// FILL THESE IN WITH YOUR VALUES FROM THE API CONSOLE
private static final String CLIENT_ID = "XXXXXX";
private static final String CLIENT_SECRET = "XXXXXX";
public static void main(String args[]) throws HttpResponseException,
IOException {
// Generate the URL to send the user to grant access.
GoogleCredential credential = null;
String authorizationUrl = new GoogleAuthorizationRequestUrl(CLIENT_ID,
REDIRECT_URL, SCOPE).build();
System.out.println("Go to the following link in your browser:");
System.out.println(authorizationUrl);
// Get authorization code from user.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is the authorization code?");
String authorizationCode = null;
try {
authorizationCode = in.readLine();
} catch (IOException ioe) {
ioe.printStackTrace();
}
// Use the authorisation code to get an access token
AccessTokenResponse response = null;
try {
response = new GoogleAccessTokenRequest.GoogleAuthorizationCodeGrant(
netHttpTransport, jacksonFactory, CLIENT_ID, CLIENT_SECRET,
authorizationCode, REDIRECT_URL).execute();
} catch (IOException ioe) {
ioe.printStackTrace();
}
// Use the access token to get a new GoogleAccessProtectedResource.
GoogleAccessProtectedResource googleAccessProtectedResource = new GoogleAccessProtectedResource(
response.accessToken, netHttpTransport, jacksonFactory,
CLIENT_ID, CLIENT_SECRET, response.refreshToken);
// Instantiating a Service Object
// Analytics analytics = Analytics
// .Builder(netHttpTransport, jacksonFactory)
// .setHttpRequestInitializer(googleAccessProtectedResource)
// .setApplicationName(APPLICATION_NAME).build();
Analytics analytics = new Analytics.Builder(netHttpTransport, jacksonFactory, credential)
.setHttpRequestInitializer(googleAccessProtectedResource).setApplicationName(APPLICATION_NAME).build();
analytics.getApplicationName();
System.out.println("Application Name: "
+ analytics.getApplicationName());
// Get profile details
Profiles profiles = analytics.management().profiles()
.list("~all", "~all").execute();
displayProfiles(profiles, analytics);
// Get the segment details
Segments segments = analytics.management().segments().list().execute();
displaySegments(segments);
}
/**
* displayProfiles gives all the profile info for this property
* #param profiles
* #param analytics
*/
public static void displayProfiles(Profiles profiles, Analytics analytics) {
for (Profile profile : profiles.getItems()) {
System.out.println("Account ID: " + profile.getAccountId());
System.out
.println("Web Property ID: " + profile.getWebPropertyId());
System.out.println("Web Property Internal ID: "
+ profile.getInternalWebPropertyId());
System.out.println("Profile ID: " + profile.getId());
System.out.println("Profile Name: " + profile.getName());
System.out.println("Profile defaultPage: "
+ profile.getDefaultPage());
System.out.println("Profile Exclude Query Parameters: "
+ profile.getExcludeQueryParameters());
System.out.println("Profile Site Search Query Parameters: "
+ profile.getSiteSearchQueryParameters());
System.out.println("Profile Site Search Category Parameters: "
+ profile.getSiteSearchCategoryParameters());
System.out.println("Profile Currency: " + profile.getCurrency());
System.out.println("Profile Timezone: " + profile.getTimezone());
System.out.println("Profile Updated: " + profile.getUpdated());
System.out.println("Profile Created: " + profile.getCreated());
try {
/**
* The get method follows the builder pattern, where all
* required parameters are passed to the get method and all
* optional parameters can be set through specific setter
* methods.
*/
// Possible to Build API Query with various criteria as below
Get apiQuery = analytics.data().ga()
.get("ga:" + profile.getId(), // Table ID =
// "ga"+ProfileID
"2013-03-21", // Start date
"2013-05-04", // End date
"ga:visits"); // Metrics
apiQuery.setDimensions("ga:source,ga:medium");
apiQuery.setFilters("ga:medium==referral");
apiQuery.setSort("-ga:visits");
apiQuery.setSegment("gaid::-11");
apiQuery.setMaxResults(100);
// Make Data Request
GaData gaData = apiQuery.execute();
if (profile.getId() != null) {
retrieveData(gaData);
}
} catch (IOException e) {
System.out.println("Inside displayProfile method");
e.printStackTrace();
}
}
}
/**
* retrieveData() gets the Google Analytics user data
* #param gaData
*/
public static void retrieveData(GaData gaData) {
// Get Row Data
if (gaData.getTotalResults() > 0) {
// Get the column headers
for (ColumnHeaders header : gaData.getColumnHeaders()) {
System.out.format("%-20s",
header.getName() + '(' + header.getDataType() + ')');
}
System.out.println();
// Print the rows of data.
for (List<String> rowValues : gaData.getRows()) {
for (String value : rowValues) {
System.out.format("%-20s", value);
}
System.out.println();
}
} else {
System.out.println("No data");
}
}
/**
* displaySegments provides Segment details of the account
* #param segments
*/
public static void displaySegments(Segments segments) {
for (Segment segment : segments.getItems()) {
System.out.println("Advanced Segment ID: " + segment.getId());
System.out.println("Advanced Segment Name: " + segment.getName());
System.out.println("Advanced Segment Definition: "
+ segment.getDefinition());
}
}
}
When i run this code it works correctly it gives a link for authorization and i get the authorization code but when the enter the authorization code in the console, it gives this error:
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/api/client/http/HttpParser
at GoogleAnalyticsExample.main(GoogleAnalyticsExample.java:64)
Caused by: java.lang.ClassNotFoundException: com.google.api.client.http.HttpParser
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more
Include following jar in your class path ... google-http-client-1.5.0-beta.jar . Also please make sure exact number of jars are included while running and compiling your code.
I have used following jars in my class path . Around 2-3 jars can be excluded from them
jdk1.6.0_21/lib/tools.jar
google-api-client-1.15.0-rc.jar
mysql-connector-java-3.1.7-bin.jar
google-api-services-analytics-v3-rev50-1.15.0-rc.jar
google-api-services-analytics-v3-rev50-1.15.0-rc-javadoc.jar
google-api-services-analytics-v3-rev50-1.15.0-rc-sources.jar
google-http-client-1.15.0-rc.jar
google-http-client-jackson2-1.15.0-rc.jar
jackson-core-2.0.5.jar
google-oauth-client-1.15.0-rc.jar

Runtime Exception while executing Contacts Demo in Google Data API

I have downloaded the google data API plugin for eclipse. While dealing with the Contacts template (Demo.java)
/* INSTRUCTION: This is a command line application. So please execute this template with the following arguments:
arg[0] = username
arg[1] = password
*/
/**
* #author (Your Name Here)
*
*/
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
/**
* This is a test template
*/
public class Contacts {
public static void main(String[] args) {
try {
// Create a new Contacts service
ContactsService myService = new ContactsService("My Application");
myService.setUserCredentials(args[0],args[1]);
// Get a list of all entries
URL metafeedUrl = new URL("http://www.google.com/m8/feeds/contacts/"+args[0]+"#gmail.com/base");
System.out.println("Getting Contacts entries...\n");
ContactFeed resultFeed = myService.getFeed(metafeedUrl, ContactFeed.class);
List<ContactEntry> entries = resultFeed.getEntries();
for(int i=0; i<entries.size(); i++) {
ContactEntry entry = entries.get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
}
System.out.println("\nTotal Entries: "+entries.size());
}
catch(AuthenticationException e) {
e.printStackTrace();
}
catch(MalformedURLException e) {
e.printStackTrace();
}
catch(ServiceException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
it is getting compiled successfully, but throwing this runtime exception (i am providing correct required credentials as arguments).
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/collect/Maps
at com.google.gdata.wireformats.AltRegistry.<init>(AltRegistry.java:118)
at com.google.gdata.wireformats.AltRegistry.<init>(AltRegistry.java:100)
at com.google.gdata.client.Service.<clinit>(Service.java:532)
at Contacts.main(Contacts.java:36)
Caused by: java.lang.ClassNotFoundException: com.google.common.collect.Maps
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
... 4 more
I am sure, i am missing something, but enable to resolve it.
You seem to be missing a dependency. Download this google-collections and add the jar to your build-path.

Categories

Resources