I need some guidance on my current obstacle with this application. If you can point me in the right direction will help. Basically I have twitter like application with a sql database storing the "tweets" and the users data.The user's nickname always start with a "#". Now everything is working but i need to add the functionality that if I send a twit and "mentioned" a user, meaning I add #nickname , then that person I mentioned should see it on his messages. I think I can figure it out, but i'm just confused on how to get started, specifically when I'm getting the "tweet" how can I find a "#" and return the word that contains the "#" ? The next step should probably be to see if that nickname exists and find the userID by the nickname and update their messages? Please help me out.
This is what I'm trying.. not working..
HttpSession session = request.getSession();
String tweet = request.getParameter("tweet");
ArrayList<User> x= new ArrayList<User>();
for(int i = 0; i < x.size(); i++){
String alias = x.get(i).getAlias();
if(tweet.contains(alias)){
try {
int uid= getUseridByNickName(alias);
Twit t = new Twit();
t.setMentionedUserID(uid);
} catch (SQLException ex) {
Logger.getLogger(TwitServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
To get the username of the mentioned users you could simply use the indexOf method:
String s = "#user1 #user2 some text";
ArrayList<String> users = new ArrayList<>();
int index = s.indexOf("#");
while(index != -1) {
users.add(s.substring(index + 1, s.indexOf(" ", index)));
index = s.indexOf("#", index + 1);
}
users.stream().forEach(System.out::println);
Note that this method will work only if the username is followed by a space, otherwise the username will also contain the text between the "#" and the first space it founds (e.g. the tweet "#user1, some text" will return "user1,")
Related
I am trying to get the vertical index from a JList. My program saves website, username, and passwords in a list to a text file like this:
website
username
password
When I use a for loop to create a new instance of my usernamesAndPasswords class it reads it like this:
website website website
username username username
password password password.
The code I think causing the problem is this:
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String outFileName;
String website, username, password;
ArrayList<UsernamesAndPasswords> upInfo = new
ArrayList<UsernamesAndPasswords>();
try{
for (int i = 0; i < list1.getSize(); i++){
website = list1.getElementAt(i);
username = list1.getElementAt(i);
password = list1.getElementAt(i);
upInfo.add(new UsernamesAndPasswords(website, username, password));
}
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name of the file to write to: ");
outFileName = sc.nextLine();
upc.saveToTextFile(upInfo, outFileName);
} catch (Exception ex){
JOptionPane.showMessageDialog(null, "There was" +
"an error saving the file");
}
}});
If this just doesn't make sense let me know how I can fix it. Thanks.
Look at your loop:
for (int i = 0; i < list1.getSize(); i++){
website = list1.getElementAt(i);
username = list1.getElementAt(i);
password = list1.getElementAt(i);
upInfo.add(new UsernamesAndPasswords(website, username, password));
}
When you run into an indexing issue like this, try to use your brain as a debugger by substituting values:
// Loop iteration 1 (index = 0)
website = list1.getElementAt(0);
username = list1.getElementAt(0);
password = list1.getElementAt(0);
The first element in your list is a website name, but you don't increment the index before trying to set the corresponding username or password. You want:
website = list1.getElementAt(0);
username = list1.getElementAt(1);
password = list1.getElementAt(2);
Based on the structure of your file, you obviously need to increment that index within your loop.
website = list1.getElementAt(i);
i++;
username = list1.getElementAt(i);
i++;
password = list1.getElementAt(i);
The i++ of your for loop will take care of incrementing the index to element 4, and you have to change getSize() as the loop's exit condition to getSize() - 2 to avoid index out of bounds.
You could also switch to saving your list with each website and corresponding data on its own line and splitting based on some separator (tab, comma, etc.), which may make things more conceptually simple for you or someone else looking at your code, but that change is not only somewhat trivial to implement, but also somewhat trivial in value.
I have been wondering if there is a way to access all the twitter followers list.
We have tried using call to the REST API via twitter4j:
public List<User> getFriendList() {
List<User> friendList = null;
try {
friendList = mTwitter.getFollowersList(mTwitter.getId(), -1);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (TwitterException e) {
e.printStackTrace();
}
return friendList;
}
But it returns only a list of 20 followers.
I tried using the same call in loop, but it cause a rate limit exception - says we are not allowed to make too many requests in a small interval of time.
Do we have a way around this?
You should definitely use getFollowersIDs. As the documentation says, this returns an array (list) of IDs objects. Note that it causes the list to be broken into pages of around 5000 IDs at a time. To begin paging provide a value of -1 as the cursor. The response from the API will include a previous_cursor and next_cursor to allow paging back and forth.
The tricky part is to handle the cursor. If you can do this, then you will not have the problem of getting only 20 followers.
The first call to getFollowersIDs will need to be given a cursor of -1. For subsequent calls, you need to update the cursor value, by getting the next cursor, as done in the while part of the loop.
long cursor =-1L;
IDs ids;
do {
ids = twitter.getFollowersIDs(cursor);
for(long userID : ids.getIDs()){
friendList.add(userID);
}
} while((cursor = ids.getNextCursor())!=0 );
Here is a very good reference:
https://github.com/yusuke/twitter4j/blob/master/twitter4j-examples/src/main/java/twitter4j/examples/friendsandfollowers/GetFriendsIDs.java
Now, if the user has more than around 75000 followers, you will have to do some waiting (see Vishal's answer).
The first 15 calls will yield you around 75000 IDs. Then you will have to sleep for 15 minutes. Then make another 15 calls, and so on till you get all the followers. This can be done using a simple Thread.sleep(time_in_milliseconds) outside the for loop.
Just Change like this and try, this is working for me
try {
Log.i("act twitter...........", "ModifiedCustomTabBarActivity.class");
// final JSONArray twitterFriendsIDsJsonArray = new JSONArray();
IDs ids = mTwitter.mTwitter.getFriendsIDs(-1);// ids
// for (long id : ids.getIDs()) {
do {
for (long id : ids.getIDs()) {
String ID = "followers ID #" + id;
String[] firstname = ID.split("#");
String first_Name = firstname[0];
String Id = firstname[1];
Log.i("split...........", first_Name + Id);
String Name = mTwitter.mTwitter.showUser(id).getName();
String screenname = mTwitter.mTwitter.showUser(id).getScreenName();
// Log.i("id.......", "followers ID #" + id);
// Log.i("Name..", mTwitter.mTwitter.showUser(id).getName());
// Log.i("Screen_Name...", mTwitter.mTwitter.showUser(id).getScreenName());
// Log.i("image...", mTwitter.mTwitter.showUser(id).getProfileImageURL());
}
} while (ids.hasNext());
} catch (Exception e) {
e.printStackTrace();
}
Try This...
ConfigurationBuilder confbuilder = new ConfigurationBuilder();
confbuilder.setOAuthAccessToken(accessToken)
.setOAuthAccessTokenSecret(secretToken)
.setOAuthConsumerKey(TwitterOAuthActivity.CONSUMER_KEY)
.setOAuthConsumerSecret(TwitterOAuthActivity.CONSUMER_SECRET);
Twitter twitter = new TwitterFactory(confbuilder.build()).getInstance();
PagableResponseList<User> followersList;
ArrayList<String> list = new ArrayList<String>();
try
{
followersList = twitter.getFollowersList(screenName, cursor);
for (int i = 0; i < followersList.size(); i++)
{
User user = followersList.get(i);
String name = user.getName();
list.add(name);
System.out.println("Name" + i + ":" + name);
}
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1 , list));
listView.setVisibility(View.VISIBLE);
friend_list.setVisibility(View.INVISIBLE);
post_feeds.setVisibility(View.INVISIBLE);
twit.setVisibility(View.INVISIBLE);
}
This is a tricky one.
You should specify whether you're using application or per user tokens and the number of users you're fetching followers_ids for.
You get just 15 calls per 15 minutes in case of an application token. You can fetch a maximum of 5000 followers_ids per call. That gives you a maximum of 75K followers_ids per 15 minutes.
If any of the users you're fetching followers_ids for has over 75K followers, you'll get the rate_limit error immediately. If you're fetching for more than 1 user, you'll need to build strong rate_limit handling in your code with sleeps and be very patient.
The same applies for friends_ids.
I've not had to deal with fetching more than 75K followers/friends for a given user but come to think of it, I don't know if it's even possible anymore.
Problem
I want to see if user "john" is in group "Calltaker". I can't seem to get the syntax right on my search filter to check for a specific user in a specific group. I can list all users in a group to verify the desired user is there.
Questions
What is the right syntax for a ldap search filter to determine if a specific user is in a specific group(in Tivoli Access Manager)?
What should I check on the returned LDAPEntry object given by that search string to see that the user is, or isn't, in the group?
Info
john is defined in "cn=users,dc=ldap,dc=net"
Calltaker is defined in "cn=groups,dc=ldap,dc=net"
I'm querying against TAM's ldap, from java
Using the searchfilter to be "cn=Calltaker" I can print out the search results such that calling nextEntry.toString contains the list of users. See Example 1 below
Here's a few searchfilters I've tried that don't work (aka searchResults.next() throws an error):
(&(objectclass=groupOfUniqueName)(uniquemember=uid="+ username + ",cn=groups,dc=ldap,dc=net))
(&(objectclass=groupOfUniqueName)(uniquemember=uid="+ username + ",cn=users,dc=ldap,dc=net))
(uniquemember=uid="+ username + ",cn=users,dc=ldap,dc=net)
Example 1) only search group, using searchFilter="cn=Calltaker", verify it contains users:
System.out.println(nextEntry.toString()); //added newlines for readability
nextEntry:
LDAPEntry:
cn=Calltaker,cn=groups,dc=ldap,dc=net;
LDAPAttributeSet:
LDAPAttribute: {type='objectclass', values='groupOfUniqueNames','top'}
LDAPAttribute: {type='uniquemember',
values=
'uid=placeholder,cn=users,dc=ldap,dc=net',
'secAuthority=default',
'uid=john,cn=users,dc=ldap,dc=net',
'uid=sally,cn=users,dc=ldap,dc=net', ....etc
Code:
public boolean isUserInGroup(username){
boolean userInGroup = false;
String loginDN = "uid=" + admin_username + "," + "cn=users,dc=ldap,dc=net";
String searchBase = "cn=groups,dc=ldap,dc=net";
int searchScope = LDAPConnection.SCOPE_SUB;
searchFilter = "(&(objectclass=ePerson)(uniquemember=uid="+ username + ",cn=users,dc=ldap,dc=net))";
//Connect
LDAPConnection lc = connect(hosts);
lc.bind(LDAPConnection.LDAP_V3, loginDN, admin_password.getBytes("UTF8"));
lc.getAuthenticationDN();
LDAPSearchResults searchResults = lc.search(searchBase,
searchScope,
searchFilter,
null, // return all attributes
false); // return attrs and values
while (searchResults.hasMore()) {
LDAPEntry nextEntry = null;
try {
nextEntry = searchResults.next();
} catch (LDAPException e) {
// Exception is thrown, go for next entry
if (e.getResultCode() == LDAPException.LDAP_TIMEOUT || e.getResultCode() == LDAPException.CONNECT_ERROR)
break;
else
continue;
}
//TODO some check to verify nextEntry shows the user in the group
userInGroup = true;
LDAPAttributeSet attributeSet = nextEntry.getAttributeSet();
Iterator<LDAPAttribute> allAttributes = attributeSet.iterator();
while (allAttributes.hasNext()) {
LDAPAttribute attribute = (LDAPAttribute) allAttributes.next();
String attributeName = attribute.getName();
System.out.println("found attribute '" + attributeName + "' with value '" + attribute.getStringValue() + "'");
}
}
lc.disconnect();
return userInGroup;
}
** EDIT **
Implemented answer from EJP, changed searchBase to include group
Code that works:
private static final String admin_username = "foo";
private static final String[] hosts = new String[]{"foohost.net"};
public boolean isUserInGroup(String username, String group){
boolean userInGroup = false;
String loginDN = "uid=" + admin_username + "," + "cn=users,dc=ldap,dc=net";
String searchBase = "cn=" + group + "," + "cn=groups,dc=ldap,dc=net";
int searchScope = LDAPConnection.SCOPE_SUB;
searchFilter = "(&(objectclass=groupOfUniqueNames)(uniquemember=uid="+ username + ",cn=users,dc=ldap,dc=net))";
//Connect
LDAPConnection lc = connect(hosts);
lc.bind(LDAPConnection.LDAP_V3, loginDN, admin_password.getBytes("UTF8"));
lc.getAuthenticationDN();
LDAPSearchResults searchResults = lc.search(searchBase,
searchScope,
searchFilter,
null, // return all attributes
false); // return attrs and values
while (searchResults.hasMore()) {
LDAPEntry nextEntry = null;
try {
nextEntry = searchResults.next();
} catch (LDAPException e) {
// Exception is thrown, go for next entry
if (e.getResultCode() == LDAPException.LDAP_TIMEOUT || e.getResultCode() == LDAPException.CONNECT_ERROR)
break;
else
continue;
}
//A result was found, therefore the user is in the group
userInGroup = true;
}
lc.disconnect();
return userInGroup;
}
What is the right syntax for a ldap search filter to determine if a specific user is in a specific group(in Tivoli Access Manager)?
Either of the filters you used, but the objectClass to search on is groupofUniqueNames (plural).
What should I check on the returned LDAPEntry object given by that search string to see that the user is, or isn't, in the group?
Nothing. He will be, otherwise the group won't be returned in the search. All you need to do is check that the search result is non-empty.
Here's a few searchfilters I've tried that don't work (aka searchResults.next() throws an error):
Throws what error?
(&(objectclass=groupOfUniqueName)(uniquemember=uid="+ username + ",cn=groups,dc=ldap,dc=net))
Nothing wrong with this except for groupOfUniqueName. You should use search filter arguments like {0} rather than building them into the search string.
(&(objectclass=groupOfUniqueName)(uniquemember=uid="+ username + ",cn=users,dc=ldap,dc=net))
This one will search the cn=users subtree for a group. It won't work unless you have groups under cn=users, which doesn't seem likely.
(uniquemember=uid="+ username + ",cn=users,dc=ldap,dc=net)
This will select non-groups. You don't want that: you need the objectClass part.
I want to extract user information(age,location etc) from a particular page.
For example: My search string is "obama". So I want the information of all users who have liked or commented in this particular page of obama.
I am able to achieve this to some extent by:
public static String getFacebookPostes(Facebook facebook, String searchPost)
throws FacebookException {
String searchResult = "Item : " + searchPost + "\n";
StringBuilder searchMessage = new StringBuilder();
ResponseList<Post> results = facebook.getPosts(searchPost);
//facebook.getFriends(new Reading().fields("gender"));
/*System.out.println("success");
System.out.println(facebook.getMe().getFirstName());*/
String userId="";
for (Post post : results) {
System.out.println(post.getMessage());
searchMessage.append(post.getMessage() + "\n");
for (int j = 0; j < post.getComments().size(); j++) {
searchMessage.append(post.getComments().get(j).getFrom()
.getName()
+ ", ");
searchMessage.append(post.getComments().get(j).getMessage()
+ ", ");
searchMessage.append(post.getComments().get(j).getCreatedTime()
+ ", ");
searchMessage.append(post.getComments().get(j).getLikeCount()
+ "\n");
userId=post.getComments().get(j).getFrom().getId();
User user = facebook.getUser(userId);
System.out.println(user);
}
}
searchResult = searchResult + searchMessage.toString();
System.out.println(searchMessage.toString());
return searchResult;
}
Reference URL: http://www.devx.com/Java/how-to-integrate-facebook-and-twitter-with-java-applications.html
But this gives me only Name, Username, Gender, Locale, Profile link.. It gives me null values for location,birthday,email..
Through googling, some people suggested that "It all depends on what information the user has made public". So i created a test account and made all the information public and commented on the obama page. It displays the information i made public, except for the email and birthday.. How can i extract these 2 parameters?
Any help,suggestion,guidance is appreciated.
PS:I am using eclipse kepler and facebook4j-core-2.0.2
Make sure you have set the right OAuthPermissions like email,user_birthday,read_stream etc..
configurationBuilder.setOAuthPermissions("email, publish_stream, id, name, first_name, last_name, read_stream , generic");
Try this....
Use FacebookClient object....Get access token from Facebook developer tools and in the fetchobject() pass username.....you can extract username from url's using some sort of regular expressions or other methods....
N.B :- Result depends on the fact that which all fields are made public...
public static FacebookClient facebookClient;
public static void main(String[] args) throws FacebookException
{
facebookClient = new DefaultFacebookClient("ur access token");
String result= facebookClient.fetchObject("username", String.class);
System.out.println(result);
}
}
I have this code. And basically this returns the correct data without the town qualities. When I add the town qualities the method returns nothing, not even the orginal data that it has been and I dont know why. Can anyone see a problem?
protected void listRecords() {
mListForm.deleteAll(); // clear the form
try {
RecordStore rs = RecordStore.openRecordStore("Details", true);
RecordEnumeration re = rs.enumerateRecords(null, new RecordSorter(), false);
while (re.hasNextElement()) {
byte [] recordBuffer = re.nextRecord();
String record = new String(recordBuffer);
// extract the name and the age from the record
int endOfName = record.indexOf(";");
int endOfDesc = record.indexOf(";" , endOfName + 1);
int endOfTown = record.indexOf (";", endOfDesc + 1);
String name = record.substring(0, endOfName);
String desc = record.substring(endOfName + 1, endOfDesc);
String town = record.substring(endOfDesc +1, endOfTown);
mListForm.append(name + " aged: "+ desc + " " + town);
}
rs.closeRecordStore();
}
catch(Exception e){
mAlertConfirmDetailsSaved.setString("Couldn't read details");
System.err.println("Error accessing database");
}
mDisplay.setCurrent(mListForm);
}
Have you tried running it in the debugger? Is the exception happening? Are the three semicolons present in the record? Is there a limit on mDisplay's string size? When setCurrent is called, is the mListForm correct?
In other words, what have you done so far and where is it definitely right, and where does it become wrong?