android twitter 4j integration get tweet entities - java

I am working on twitter integration with android using Twiitter4j. I am trying to fetch Home timelines and its working fine. But when i am looking to get urls included in the tweets there is no functions. Is there a functon to get tweet entites like urls etc.
Here is the code
cb = new ConfigurationBuilder();
cb.setDebugEnabled(true).setOAuthConsumerKey(Constants.CONSUMER_KEY)
.setOAuthConsumerSecret(Constants.CONSUMER_SECRET)
.setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(
accessSecret);
try {
TwitterFactory factory = new TwitterFactory(cb.build());
// gets Twitter instance with default credentials
Twitter twitter = factory.getInstance();
User user = twitter.verifyCredentials();
List<Status> statuses = twitter.getHomeTimeline();
System.out.println("Showing #" + user.getScreenName() + "'s home timeline.");
for (Status status : statuses) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText() + "--"+status.getURLs()+ "--"+status.getURLEntities());
}
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to get timeline: " + te.getMessage());
System.exit(-1);
}
Works well with Sony's code and after that i have moved my code to async task and it shows some errors
Here is my edited code
protected String doInBackground(Void... args) {
String response = null;
try {
TwitterFactory factory = new TwitterFactory(cb.build());
// gets Twitter instance with default credentials
Twitter twitter = factory.getInstance();
User user = twitter.verifyCredentials();
ResponseList<Status> statuses = twitter.getHomeTimeline();
System.out.println("Showing #" + user.getScreenName() + "'s home timeline.");
for (Status status : statuses) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText() + "--"+status.getUser().getProfileImageURL());
URLEntity[] uent = status.getURLEntities();
if (uent != null) {
for (int k = 0; k < uent.length; k++) {
Log.i("URL Entity", "Dp Url " + uent[k].getDisplayURL()
+ " URL " + uent[k].getURL() + " start "
+ uent[k].getStart() + " end "
+ uent[k].getEnd());
}
}
}
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to get timeline: " + te.getMessage());
System.exit(-1);
}
return response;
}

You just need to add one more line while creating object of ConfigurationBuilder
cb.setIncludeEntitiesEnabled(true);
(Hint for the next code)And you will get the Entities then,
ResponseList<Status> list = twitter.getHomeTimeline();
URLEntity[] uent = list.get(0).getURLEntities();
if (uent != null) {
for (int k = 0; k < uent.length; k++) {
Log.i("URL Entity", "Dp Url " + uent[k].getDisplayURL()
+ " URL " + uent[k].getURL() + " start "
+ uent[k].getStart() + " end "
+ uent[k].getEnd());
}
}

Related

Fetching tweets for specific hash tag using twitter4j

I am using twitter4j stream api to get the tweets for specific hashtag ,but am getting only 10 tweets for my required hashtag and for other hashtags I am getting maximum of 5000 tweets.
Why I am getting only 10 tweets for some and 5000 for others?
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(" ")
.setOAuthConsumerSecret(" ")
.setOAuthAccessToken(" ")
.setOAuthAccessTokenSecret(" ");
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
Query query = new Query("hashtag");
int numberOfTweets = 7;
long lastID = Long.MAX_VALUE;
ArrayList<Status> tweets = new ArrayList<Status>();
while (tweets.size () < numberOfTweets) {
if (numberOfTweets - tweets.size() > 100)
query.setCount(100);
else
query.setCount(numberOfTweets - tweets.size());
try {
QueryResult result = twitter.search(query);
tweets.addAll(result.getTweets());
System.out.println("Gathered " + tweets.size() + " tweets"+"\n");
for (Status t: tweets)
if(t.getId() < lastID)
lastID = t.getId();
}
catch (TwitterException te) {
System.out.println("Couldn't connect: " + te);
};
query.setMaxId(lastID-1);
}
for (int i = 0; i < tweets.size(); i++) {
Status t = (Status) tweets.get(i);
// GeoLocation loc = t.getGeoLocation();
String user = t.getUser().getScreenName();
String msg = t.getText();
//String time = "";
//if (loc!=null) {
//Double lat = t.getGeoLocation().getLatitude();
//Double lon = t.getGeoLocation().getLongitude();*/
System.out. println(i + " USER: " + user + " wrote: " + msg + "\n");
}
//else
//System.out.println(i + " USER: " + user + " wrote: " + msg+"\n");

Google Drive API: Error 500 sharing folder

Using Google Apps for Education, I create and share folders for pupils and staff.
This is done using server-side-flow, since we may need to increase storage.
When sharing some folders, it works, but when sharing others, I get Internal Error 500.
Sometimes this happens for the vast majority of folders, but rarely for all.
As an example, I created folders for approx. 1000 users, and sharing each one failed.
They are shared with type=user, role=writer.
Also, as happened today, there are days when sharing causes no errors at all, and I
could create and share folders for all users.
Does anyone have any ideas?
Thanks,
Michael.
I call shareFolder like this:
shareFolder(, , "user", "writer", true);
public boolean shareFolder(String fileId, String sharerEmail, String type, String role, boolean forcesharing) {
if (sharerEmail == null || sharerEmail.length() == 0) {
return true;
}
sharerEmail = sharerEmail.toLowerCase();
Permission perm = sharedAlready(fileId, sharerEmail, type, role);
if (forcesharing && perm == null) {
logger.info("File id " + fileId + " will be force shared with " + sharerEmail + ".");
Permission permission = new Permission();
permission.setValue(sharerEmail);
permission.setEmailAddress(sharerEmail);
permission.setType(type);
permission.setRole(role);
return insertSharingperm(fileId, permission);
} else if (forcesharing) {
// I do this in the hope that it my have an effect, but I'm beginning to doubt it.
// There seems to be a problem with sharing the class folders with the class email, as readers.
return updateSharingperm(fileId, perm);
} else {
if (perm != null) {
logger.info("File " + fileId + " already shared with " + sharerEmail + ".");
return true;
} else {
Permission permission = new Permission();
permission.setValue(sharerEmail);
permission.setEmailAddress(sharerEmail);
permission.setType(type);
permission.setRole(role);
return insertSharingperm(fileId, permission);
}
}
}
public boolean insertSharingperm(String fileId, Permission perm) {
try {
if (null != executeWithEB(service.permissions().insert(fileId, perm))) {
logger.info("File id " + fileId + " shared with " + perm.getEmailAddress() + ".");
return true;
} else {
logger.warning("File id " + fileId + " not shared with " + perm.getEmailAddress() + ".");
return false;
}
} catch (GoogleJsonResponseException e) {
logger.severe("Failed. Code: "
+ e.getDetails().getCode() + "\nMessage: "
+ e.getDetails().getMessage() + " FileID=" + fileId
+ " SharerEmail=" + perm.getEmailAddress() + " Type=" + perm.getType()
+ " Role=" + perm.getRole());
} catch (IOException e) {
logger.severe("Failed:" + e.getMessage());
} catch (InterruptedException e) {
logger.severe("Failed:" + e.getMessage());
}
return false;
}

Reading all new messages from my gmail using javamail

I have an application which contains a GUI, it is using Javamail. When i open this Jframe I have to see messages that are sent to my mail on a jTextArea.
The problem is when i wrote my code it only shows just the last message sent.
How do I display all new messages in my inbox?
This is my code :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Properties props = new Properties();
props.put("mail.pop3.host", "pop.gmail.com");
props.put("mail.pop3.user", "mymail#gmail.com");
props.put("mail.pop3.socketFactory", 995);
props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.pop3.port", 995);
Session session = Session.getDefaultInstance(props, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("mymail#gmail.com", "mypassword");
}
});
try {
Store store = session.getStore("pop3");
store.connect("pop.gmail.com", "mymail#gmail.com", "mypaswword");
Folder fldr = store.getFolder("INBOX");
fldr.open(Folder.READ_ONLY);
Message[] msg = fldr.getMessages();
Address[] address;
for (int i = 0; i < msg.length; i++) {
jTextArea1.setText("SentDate : " + msg[i].getSentDate() + "\n" + "From : " + msg[i].getFrom()[0] + "\n" + "Subject : " + msg[i].getSubject() + "\n" + "Message : " + "\n" + msg[i].getContent().toString());
}
fldr.close(true);
store.close();
} catch (Exception e) {
System.out.println(e);
}
You repeatedly set the text of the jTextArea1 to the same contents in your loop over messages here:
for (int i = 0; i < msg.length; i++) {
jTextArea1.setText("SentDate : " + msg[i].getSentDate() + "\n" + "From : " + msg[i].getFrom()[0] + "\n" + "Subject : " + msg[i].getSubject() + "\n" + "Message : " + "\n" + msg[i].getContent().toString());
}
You should build a StringBuilder with all the messages and then set the contents of the jTextArea1
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < msg.length; i++) {
sb.append("SentDate : " + msg[i].getSentDate() + "\n" + "From : " + msg[i].getFrom()[0] + "\n" + "Subject : " + msg[i].getSubject() + "\n" + "Message : " + "\n" + msg[i].getContent().toString());
}
jTextArea1.setText(sb.toString());
You can then make this a lot more legible by using an enhanced for loop and using the append method of the StringBuilder.
final StringBuilder sb = new StringBuilder();
for (Message message : msg) {
sb.append("SentDate : ").
append(message.getSentDate()).
append("\n").
append("From : ").
append(message.getFrom()[0]).
append("\n").append("Subject : ").
append(message.getSubject()).
append("\n").
append("Message : ").
append("\n").
append(message.getContent().toString());
}
jTextArea1.setText(sb.toString());
final StringBuilder sb = new StringBuilder();
for (Message message : msg) {
sb.append("SentDate : ").
append(message.getSentDate()).
append("\n").
append("From : ").
append(message.getFrom()[0]).
append("\n").append("Subject : ").
append(message.getSubject()).
append("\n").
append("Message : ").
append("\n").
append(message.getContent().toString());
}
jTextArea1.setText(sb.toString());

how to parse this output file in Java [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have the following out put from a text file:
===============================================
guideMenuSuite.mts:
[monkeytalk:run] MonkeyTalk v1.0.11.beta5c_473 - 2012-07-18 11:38:51 MDT - Copyright 2012 Gorilla Logic, Inc. - www.gorillalogic.com
[monkeytalk:run] running suite guideMenuSuite.mts...
[monkeytalk:run] BCOKAS127271: -start suite (1 test)
[monkeytalk:run] BCOKAS127271: 1 : guide_menu.mt
[monkeytalk:run] BCOKAS127271: -> OK
[monkeytalk:run] BCOKAS127271: -end suite
[monkeytalk:run] result: OK
[monkeytalk:run] ...done
================================================
In Java, I need to:
1) Parse the out put for the device serial number (BCOKAS127271 in this case.... it changes depending on what device is being tested).
2) Get the status results of the test which is after the -> (-> OK in this case).
I tried using split but the data keeps coming out null...
Any suggestions would be greatly appreciated.
here is my code:
CODE
while ((strLine = br.readLine()) != null)
{
maintextarea.append(strLine + "\n");
System.out.println(strLine);
System.out.flush();
maintextarea.append(selectedSerial);
delims = "[ \\->]+";
//String[] tokens = strLine.split(delims);
//String[] tokens = strLine.substring(prefix.length()).split(delims);
String noprefixStr = strLine.substring(strLine.indexOf(prefix) + prefix.length());
String[] tokens = noprefixStr.split(delims);
//for (String t: tokens)
{
//System.out.println(t);
if (tokens.toString().contains("ERROR"))
{
testStatus = "ERROR";
maintextarea.append("\n" + selectedValue + " " + selectedSerial + " = " + testStatus + "\n");
System.out.println(selectedValue + " " + selectedSerial + " = " + testStatus);
System.out.flush();
}
else if (tokens.toString().contains("FAILURE"))
{
testStatus = "FAILED";
maintextarea.append("\n" + selectedValue + " " + selectedSerial + " = " + testStatus + "\n");
System.out.println(selectedValue + " " + selectedSerial + " = " + testStatus);
System.out.flush();
}
else if (tokens.toString().contains("OK"))
{
testStatus = "PASSED";
maintextarea.append("\n" + selectedValue + " " + selectedSerial + " = " + testStatus + "\n");
System.out.println(selectedValue + " " + selectedSerial + " = " + testStatus);
System.out.flush();
}
else
{
testStatus = "N/A";
maintextarea.append("\n" + selectedValue + " " + selectedSerial + " = " + testStatus + "\n");
System.out.println(selectedValue + " " + selectedSerial + " = " + testStatus);
System.out.flush();
}
}
}
br.close();
============================================================
UPDATE:
I found my solution based on all the input that I received from this group!
I ended up making it really simple and parsing the out put file for an expression and then based on that setting a variable to pass or fail or error.
Here is the base code I used:
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream("/home/ironmantis7x/Documents/TWC_test/MT_test_runner_output.txt"))));
String strLine;
while ((strLine = br.readLine()) != null)
{
if (strLine.contains("-> OK"))
{
testStatus = "Pass";
System.out.println("Test Result = " + testStatus);
}
}
}
catch (FileNotFoundException ex)
{
Logger.getLogger(parseFile.class.getName()).log(Level.SEVERE, null, ex);
}
Sorry it took me so long to get back to you guys and say thanks!
ironmantis7x
You can use regular expressions:
import java.util.Pattern
import java.util.Matcher
Pattern status = Pattern.compile("\\[.*] \\w+:\\s+-> (\w+).*");
...
You can learn how to do it here

java database function removed - still executing

I have a java web application that I removed a function from the code and yet the database entries that this function writes are still being written to the database.
Inside the IssueWarrant function there is a call to insertWarrantFee that has been commented out.
private void issueWarrant(String CasePrefix, String CaseNumber, String HearingType, String Suspend)
{
int i = 0, intDivision = 0, pos = 0;
String SummSeq = getSummSeq(CasePrefix, CaseNumber);
String Charges = getCharges(CasePrefix, CaseNumber, HearingType);
boolean isVacated = false, isHearingFound = false;
NextBWNumber warrNbr = new NextBWNumber();
String WarrantNumber = warrNbr.getNextBWNumber();
String warrStatus = warrNbr.getNextBWNStatus();
String HearingDesc = "", Division = "";
isVacated = getVacatedStatus(CasePrefix, CaseNumber, HearingType);
isHearingFound = getHearingStatus (CasePrefix, CaseNumber, HearingType);
HearingDesc = getFormatToday() + " " + getHearingDesc(HearingType);
if (HearingDesc.length() > 30)
{
HearingDesc = HearingDesc.substring(0,30);
}
Division = getHearingJudge(CasePrefix,CaseNumber,HearingType);
intDivision = Integer.parseInt(Division);
if (intDivision < 10)
{ Division = "0" + Division; }
Statement localstmt = null;
String localqueryString;
localqueryString = "INSERT INTO " + library7 + "CMPBWPND" +
" (CASPRE, CASNUM, DEFSEQ, CHGSEQ, SUMSEQ, STSCOD, STSDAT," +
" STATUT, CHGABV, BWNBR, JUDCOD, PRVFLG, CT2FLG, DIVISN, BNDAMT," +
" BTYPE, CMNT, CUSER, TUSER, LUPDAT, SCRDAT, STATSDAT, SUMCRDAT, LUPDATE )" +
" VALUES ('" + CasePrefix + "', " + CaseNumber + ", 1, " + Charges.substring(i, i + 1) +
", " + SummSeq + ", 9, " + getShortDate() + ", 'RCP 12-A TA', 'WARRANT', '" +
WarrantNumber + "', " + intDivision + ", 'N', 1, '" + Division + "', " +
BondAmt + ", '" + BondType + "', '" + HearingDesc + "', 'TAAD', 'TAAD', " +
getShortDate() + ", " + getShortDate() + ", " + getLongDate() + ", " + getLongDate() +
", " + getLongDate() + ")";
try
{
if (!isVacated && isHearingFound)
{
localstmt = conn.createStatement();
localstmt.executeUpdate(localqueryString);
localstmt.close();
StatusMsg = "Client No Show-WI";
}
if (isVacated)
{
StatusMsg = "Client Vacated Case";
}
if (!isHearingFound)
{
StatusMsg = "Client Hearing Missing";
}
} catch (SQLException e)
{
System.out.println("IssueWarr - Error in IssueWarrant");
e.printStackTrace();
ReturnInfo = "Issuing Warrants Failed.";
success = false;
}finally
{
try
{
if (!localstmt.isClosed())
{
localstmt.close();
}
} catch (SQLException sql2)
{
System.out.println("Error trying to close connections. Exception: " + sql2.getMessage());
}
}
**//insertWarrantFee(CasePrefix, CaseNumber, SummSeq, WarrantNumber);**
updateHearingRecord(CasePrefix, CaseNumber, HearingType, Charges.substring(i, i + 1), Suspend);
for ( i = 1; i < Charges.length(); i++ )
{
insertBWPTFRecord(CasePrefix, CaseNumber, SummSeq, Charges.substring(i, i + 1));
}
if (!success)
{
StatusMsg = "Client Iss. Warrant Failure";
}
}
Here is the code that the insertWarrantFee called before it was commented out:
private void insertWarrantFee(String CasePrefix, String CaseNumber, String SummSeq, String WarrantNumber)
{
Statement localstmt = null;
String localqueryString;
ResultSet localrSet = null;
String feeAmt = null;
localqueryString = "SELECT AUTO$$ FROM " + library3 + "CMPDKTTP WHERE DKTTYP = 'W'";
try
{
localstmt = conn.createStatement();
localrSet = localstmt.executeQuery(localqueryString);
while (localrSet.next())
{
feeAmt = localrSet.getString("AUTO$$");
}
localstmt.close();
localrSet.close();
} catch (SQLException e)
{
System.out.println("IssueWarr - Error in Insert Warrant Fee SQL1");
e.printStackTrace();
ReturnInfo = "Issuing Warrants Failed.";
success = false;
}finally
{
try
{
if (!localstmt.isClosed())
{
localstmt.close();
}
} catch (SQLException sql2)
{
System.out.println("Error trying to close connections. Exception: " + sql2.getMessage());
}
}
localqueryString = "INSERT INTO " + library7 + "CMPBWTRN"
+ " (CASPRE, CASNUM, DEFSEQ, SUMSEQ, BWNBR, FEEAMT, DKTTYP, TUSER, LUPDAT)"
+ " VALUES ('" + CasePrefix + "', " + CaseNumber + ", 1, " + SummSeq + ", '" + WarrantNumber
+ "', " + feeAmt + ", 'W', 'TAAD', " + getShortDate() + ")";
try
{
localstmt = conn.createStatement();
localstmt.executeUpdate(localqueryString);
localstmt.close();
} catch (SQLException e)
{
System.out.println("IssueWarr - Insert Warrant Fee SQL2");
e.printStackTrace();
ReturnInfo = "Issuing Warrants Failed.";
success = false;
}finally
{
try
{
if (!localstmt.isClosed())
{
localstmt.close();
}
} catch (SQLException sql2)
{
System.out.println("Error trying to close connections. Exception: " + sql2.getMessage());
}
}
}
So even though the line that called insertWarrantFee is commented out a record is still being inserted into CMPBWTRN.
Any ideas how this could happen? The developer is indicating it could be a tomcat connection cache issue? Any other suggestion beside magical code?
Thanks!
Leslie
A couple of things to try:
Make sure you've redeployed the application and have restarted Tomcat. Check the timestamp of the deployed class in question.
Clean Tomcat's tmp and work directories
Open the deployed Java class using a decompiler to see whether the removed code is still in there.
Add a logging (or System.out.println) statement to the method that's commented out, and to the method calling it. See whether one or both are printed after redeploying the changes.

Categories

Resources