i'm having trouble with java programming. This java is calling Google API which provide me with GData access
I'm having trouble when it's querying some query, resulting #5fa01e33. This is my code:
package com.thegroovie;
import java.net.URL;
import javax.swing.JOptionPane;
import com.google.gdata.client.DocumentQuery;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
public class GDataExample {
public static void main(String[] args) {
String username = JOptionPane.showInputDialog(null,"Input Username");
String password = JOptionPane.showInputDialog(null,"Input Password");
try{
DocsService service = new DocsService("Document List demo");
service.setProtocolVersion(DocsService.Versions.V3);
service.setUserCredentials(username, password);
URL documentListFeedUrl = new
URL("https://docs.google.com/feeds/default/private/full");
DocumentListFeed feed = service.getFeed(documentListFeedUrl, DocumentListFeed.class);
for(DocumentListEntry entry : feed.getEntries()){
System.out.println(entry.getTitle().getPlainText());
}
System.out.println("*******************************");
String input_query = JOptionPane.showInputDialog(null,"Search : ");
DocumentQuery query = new DocumentQuery(documentListFeedUrl);
query.setFullTextQuery(input_query);
DocumentListFeed feeds = service.getFeed(query, DocumentListFeed.class);
System.out.print(feeds);
}
catch (Exception ex){
System.err.println("Exception "+ ex.getMessage());
}
}
}
How to resolve this?
Thank you
This does not look like as an error code. Rather you print the DocumentListFeed object which type doesn't have an overridden toString method. You can access the feed's contents with the appropriate accessor methods described in the docs.
Related
In my application I have a method which I cant execute without main method. It only runs inside the main method. When I call that method inside my servlet class. It show an exception
My class with Main Method
package com.books.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.HashSet;
import java.util.Set;
import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;
public class ParserTest {
// download
public void download(String url, File destination) throws IOException, Exception {
URL website = new URL(url);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
public static Set<String> nounPhrases = new HashSet<>();
private static String line = "The Moon is a barren, rocky world ";
public void getNounPhrases(Parse p) {
if (p.getType().equals("NN") || p.getType().equals("NNS") || p.getType().equals("NNP")
|| p.getType().equals("NNPS")) {
nounPhrases.add(p.getCoveredText());
}
for (Parse child : p.getChildren()) {
getNounPhrases(child);
}
}
public void parserAction() throws Exception {
// InputStream is = new FileInputStream("en-parser-chunking.bin");
File modelFile = new File("en-parser-chunking.bin");
if (!modelFile.exists()) {
System.out.println("Downloading model.");
download("https://drive.google.com/uc?export=download&id=0B4uQtYVPbChrY2ZIWmpRQ1FSVVk", modelFile);
}
ParserModel model = new ParserModel(modelFile);
Parser parser = ParserFactory.create(model);
Parse topParses[] = ParserTool.parseLine(line, parser, 1);
for (Parse p : topParses) {
// p.show();
getNounPhrases(p);
}
}
public static void main(String[] args) throws Exception {
new ParserTest().parserAction();
System.out.println("List of Noun Parse : " + nounPhrases);
}
}
It gives me below output
List of Noun Parse : [barren,, world, Moon]
Then I commented the main method and. Called the ParserAction() method in my servlet class
if (name.equals("bkDescription")) {
bookDes = value;
try {
new ParserTest().parserAction();
System.out.println("Nouns Are"+ParserTest.nounPhrases);
} catch (Exception e) {
}
It gives me the below exceptions
And below error in my Browser
Why is this happening ? I can run this with main method. But when I remove main method and called in my servlet. it gives an exception. Is there any way to fix this issue ?
NOTE - I have read below instructions in OpenNLP documentation , but I have no clear idea about it. Please help me to fix his issue.
Unlike the other components to instantiate the Parser a factory method
should be used instead of creating the Parser via the new operator.
The parser model is either trained for the chunking parser or the tree
insert parser the parser implementation must be chosen correctly. The
factory method will read a type parameter from the model and create an
instance of the corresponding parser implementation.
Either create an object of ParserTest class or remove new keyword in this line new ParserTest().parserAction();
I'm trying to generate a list of all my saved reddit items using JRAW.
I've gone through the Quickstart , and successfully managed to login and retrieve information, and I can get a list of items on the Frontpage from the Cookbook, but I can't work out how I would get a list of my saved items (comments and posts) or a list of my own posts (also comments and posts).
The saved items are at https://www.reddit.com/user/<username>/saved/, but I don't know how to get jraw to retrieve and parse that, or if the api uses a different URL.
Edit: I think I probably need to use a UserContributionPaginator, but I haven't quite worked out exactly how to get it to work yet.
Worked it out.
package com.jraw;
import net.dean.jraw.RedditClient;
import net.dean.jraw.http.UserAgent;
import net.dean.jraw.http.oauth.Credentials;
import net.dean.jraw.http.oauth.OAuthData;
import net.dean.jraw.http.oauth.OAuthException;
import net.dean.jraw.models.Contribution;
import net.dean.jraw.models.Listing;
import net.dean.jraw.paginators.UserContributionPaginator;
public class printSaved {
public static void main(String [] args) {
UserAgent myUserAgent = UserAgent.of("desktop", "com.jraw.printSaved", "v0.01", "user");
RedditClient redditClient = new RedditClient(myUserAgent);
String username = "username";
Credentials credentials = Credentials.script(username, "<password>", "<clientId>", "<clientSecret>");
OAuthData authData = null;
try {
authData = redditClient.getOAuthHelper().easyAuth(credentials);
} catch (OAuthException e) {
e.printStackTrace();
}
redditClient.authenticate(authData);
UserContributionPaginator saved = new UserContributionPaginator(redditClient,"saved",username);
Listing<Contribution> savedList = saved.next();
for (Contribution item : savedList) {
System.out.println(item);
}
}
}
I am writing a local java application which is to access my google datastore. I followed the tutorial here http://googlecloudplatform.github.io/gcloud-java/0.2.0/index.html
This is my basic code
package myproject;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import com.google.cloud.AuthCredentials;
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Key;
import com.google.cloud.datastore.KeyFactory;
public class Main {
private String projID = "myID";
public static void main(String[] args) throws IOException {
System.out.println("correct");
Main test = new Main();
Datastore dstore = test.getDatastore();
KeyFactory keyFactory = dstore.newKeyFactory().kind("keyKind");
Key key = keyFactory.newKey("keyName");
Entity entity = Entity.builder(key)
.set("name", "John Doe")
.set("age", 30)
.build();
dstore.put(entity);
}
private Datastore getDatastore() throws IOException {
File file = new File("./resource/mycredential.json");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
System.out.println("Total file size to read (in bytes) : "
+ fis.available());
} catch (IOException e) {
e.printStackTrace();
}
DatastoreOptions options = DatastoreOptions.builder()
.projectId(projID)
.authCredentials(AuthCredentials.createForJson(fis)).build();
Datastore datastore = options.service();
return datastore;
}
}
I created the json credential key from cloud console. After I run the program, it shows com.google.datastore.v1beta3.client.DatastoreFactory makeClient
??: Not using any credentials
I am really trapped here. How to create the right credential and use it correctly?
Thanks in advance.
This is "INFO" message which means nothing. I agree that it's confusing, but this message shows up every time I start my local program, which works fine - connects to the Datastore, retrieves and saves data, etc.
i have a java class ::
package MyPackage;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.google.gson.Gson;
public class PopulateTextbox {
Gson gson = new Gson();
JSONObject obj = new JSONObject();
JSONArray arr = new JSONArray();
String temp1;
String temp;
List <String>rowValues = new ArrayList<String>();
List <Integer>rowValues1 = new ArrayList<Integer>();
String[] contactListNames;
Connection con=null;
Statement st=null;
ResultSet rs=null;
public String method(){
try{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:Practice_Database";
con = DriverManager.getConnection(db,"","");
st = con.createStatement();
String sql = "SELECT Emp_Name,ID,Email_Add FROM EmployeeSearch";
rs = st.executeQuery(sql);
while(rs.next()){
obj.put("ID", rs.getInt("ID"));
obj.put("Names",rs.getString("Emp_Name"));
obj.put("Email", rs.getString("Email_Add"));
arr.add(obj);
}
//obj.accumulate("ID",rowValues1);
//obj.accumulate("Names",rowValues);
temp1 = arr.toString();
System.out.println(temp1);
}catch(Exception e){System.out.println(e);}
/*finally{
try {
if(con!=null)con.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(rs!=null)rs.close();
} catch (SQLException e) {
e.printStackTrace();
}try {
if(st!=null)st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}*/
return temp1;
}
public static void main(String args[])
{
PopulateTextbox obj = new PopulateTextbox();
String temp1= obj.method();
}
}
This is returning me a Json array. Now i want to call method() of this class in JavaScript again and again to get new values as i update my database. I have a data grid which is working fine as the page loads for the first time with a set of values in this json array. But how to refresh data using Ajax. Or how to call the method() using Ajax so that data gets refreshed when i click on a button on the page. The code where i am calling this method in java-script is ::
<%
String temp1;
PopulateTextbox obj = new PopulateTextbox();
temp1 = obj.method();
%>
i am getting problem in retrieving new set of values in temp1 through a Ajax call to the server . please help ? Thanks.
Create a blank JSP (for example, textBoxAjaxResp.jsp) and out put your JSON string from that JSP:
<%
String temp1;
PopulateTextbox obj = new PopulateTextbox();
temp1 = obj.method();
%>
<%=temp1 %>
and hit that JSP using jQuery AJAX call.
$.get("mypath/textBoxAjaxResp.jsp", function (response) {
//do operation using the response
}, "json");
you can use Direct Web Remoting library to call java functions using javascript
But I would suggest to write servlet (tutorial is pretty old but good, you should use servlet 3.0 if possible) yourself (instead of using DWR which will have their servlet to write to the response stream also this is very simple requirement so you should write servlet yourself instead of using third party library) and write JSON response directly.
You might want to look at my answer here Updating contents of a jsp page without refreshing this uses a SpringMVC class which returns a text value from server side to client side using jquery ajax.
this is what is the code and i get the problem in marked lines(BOLD), i think it is because of the jar version but i am not sure about this. if this is because of jar version please do let me know the right one.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
public class NamexTweet {
private final static String CONSUMER_KEY = "xxxxxxxxxxxxx";
private final static String CONSUMER_KEY_SECRET = "yyyyyyyyyyyyyyy";
public void start() throws TwitterException, IOException {
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
**RequestToken requestToken = twitter.getOAuthRequestToken();**
System.out.println("Authorization URL: \n"
+ requestToken.getAuthorizationURL());
AccessToken accessToken = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (null == accessToken) {
try {
System.out.print("Input PIN here: ");
String pin = br.readLine();
**accessToken = twitter.getOAuthAccessToken(requestToken, pin);**
} catch (TwitterException te) {
System.out.println("Failed to get access token, caused by: "
+ te.getMessage());
System.out.println("Retry input PIN");
}
}
System.out.println("Access Token: " + accessToken.getToken());
System.out.println("Access Token Secret: "
+ accessToken.getTokenSecret());
twitter.updateStatus("hi.. im updating this using Namex Tweet for Demo");
}
public static void main(String[] args) throws Exception {
new NamexTweet().start();// run the Twitter client
}
}
Make sure the jar is actually in the build path (if I knew your IDE I might have given more concrete instructions).
If this doesn't solve the problem, search these classes and methods in that jar. If they're there - try to perform step 1 above better... If it's not there - then you have the wrong jar.
twitter4j 2.2.4 is the reliable version, which can be used.
You have to attach following libraries:
twitter4j-core-4.0.4.jar
twitter4j-stream-4.0.4.jar