Get the lastest tweet of multiple users in a single request - java

Is there any way I can get the latest tweet/status update of multiple Twitter-friends in a single request
An API call for the same would look as below
latestStatus = getLatestStatus(new long[]{userId1, userId2, userId3});
So as I pass in the input array of user id's (or screennames), I get the latest status update (or the status id) as an output.
I can do this one request per user, but then it exceeds the Rate Limit.
Language no barrier, even an HTTP Get request algorithm is good enough.

Check out Twitter4j.
You can use the lookupUsers(long[]) method. This will return information (including latest status) from up to 100 users at once. Check out: http://twitter4j.org/en/javadoc/twitter4j/api/UserMethods.html#lookupUsers(long[]) for more details.
example:
Twitter twitter = new TwitterFactory().getInstance();
ResponseList<User> userInfo = twitter.lookupUsers(new long[]{userId1, userId2, userId3});
for(User u: userInfo){
System.out.println(u.getScreenName() + ": " + u.getStatus().getText());
}

Related

IBM Domino 10 - Open calendar of certain user in Java (for createEntry)

I'm writing an integration API in Java for IBM Domino 10, I want to perform resource (room) reservations, fetch and update them from an external source.
So far, I successfully created an entry in current user's calendar (current session) and the reservation is also successfull, however I want to create reservations as certain users (personification), since only one user is configured to use my API database. So the main user is used to do everything, but I'd like to pass him the credentials of other users and he should create the events & reservations in their calendars. I can verify if an user exists & if his password is correct, but I don't know how could I open his calendar because it's session based.
My current code:
Database mdb = session.getDbDirectory(session.getServerName()).openMailDatabase();
NotesCalendar cal = session.getCalendar(mdb);
java.text.SimpleDateFormat datefmt = new java.text.SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
String dStart = datefmt.format(dtStart);
String dEnd = datefmt.format(dtEnd);
Name nnOrganizer = session.createName(session.getEffectiveUserName());
String iCalEntry = "BEGIN:VCALENDAR\n" +
"PRODID:-//Test//Reservation API//EN\n" +
"VERSION:2.0\n" +
"BEGIN:VEVENT\n" +
"DTSTART:" + dStart + "\n" +
"DTEND:" + dEnd + "\n" +
"SUMMARY:Sample Meeting\n" +
"DESCRIPTION:TEST\n" +
"ORGANIZER;CN=admin/O=Corp:mailto:test#test.test\n" +
"ATTENDEE;ROLE=CHAIR;PARTSTAT=ACCEPTED;" + nnOrganizer.getCanonical() + ";RSVP=false:mailto:test#test.test\n" +
"ATTENDEE;CUTYPE=ROOM;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;" + nnResource.getCanonical() + ";RSVP=true:mailto:room#test.test\n" +
"END:VEVENT\n" +
"END:VCALENDAR\n";
NotesCalendarEntry entry = cal.createEntry(iCalEntry);
System.out.println("calendar uid " + entry.getUID());
How could I make this work with any user I want? So it's not using session.getCalendar() but something else, so I could create an entry in another user's calendar.
Also, how can I programatically get the organizer's & room's email addresses? As for now, they are hardcoded. I know I could do a directory lookup, but sometimes the email (internet address) isn't configured, and lookupNames returns nothing. Notes client somehow bypasses that and creates an email like Name_Surname/server#Corp, is it enough?
Edit
I achieved what I wanted by using the REST Service (CustomServiceBean) and NotesCalendar for creating/updating/deleting reservations, paired with direct document access to check for conflicts and read detailed room & reservation data. Everything works fine so far, reservations are visible in both user's calendar and the dtabase. However when I re-installed the server from scratch and added the database with rest service, I couldn't access the api with my default admin user (403 forbidden, You are forbidden to perform this operation ) server logs:
HTTP JVM: CLFAD0229E: Security exception occurred servicing request for: /db.nsf/services.xsp/api - HTTP Code: 403. For more detailed information, please consult error-log-0.xml
When I added the admin user to Configuration->Current Server Document->Security->Sign or run unrestricted methods and operations, it starts working correctly, even when accessing the API with newly registered users (that weren't assigned any groups, permissions, nothing at all just an internet password & address and they were created by the admin account)
Will this work correctly? I need to access the API from accounts of normal users, because I need to create entries in user's calendars.

twitter API identify users with direct messaging enabled

I'm trying to use twitter4j (in Java) to grab the list of users following a particular user who happen to have direct messaging enabled. Something like this...
IDs followerIDs = twitter.getFollowersIDs(someTwitterScreenName, -1);
long[] ids = followerIDs.getIDs();
for (long id : ids) {
twitter4j.User user = twitter.showUser(id);
String userScreenName = user.getScreenName();
String realName = user.getName();
//I'm hoping for something like...
///Boolean directMessagingEnabled = user.messagingEnabled();
}
The only problem is that I can't find any attributes associated with the twitter4j.User object that sound suitable (and also can't find any reference to it in the API documentation). Does anyone know if there's some way to programmatically find these types of users? Or perhaps twitter have deliberately excluded it? Thanks for any thoughts at all.
------EDIT-----
The documentation link from Yuri led me to this response from a twitter employee: "Determining if a user accepts DMs from all is not available via the public API. If you are a trusted partner please reach out via your direct Twitter contacts for details."
(https://twittercommunity.com/t/how-can-i-tell-which-users-the-current-user-can-send-messages-to/36127/4)
Also noticed that it IS possible to get the DM status for an already authenticated user using "AccountSettings.getAccountSettings().allow_dms_from"
This is discussed here
https://dev.twitter.com/rest/reference/post/direct_messages/new
There is apparently a whitelist for access you can apply for.
However it seems you mostly have all you need. The users following your account can usually receive DMs from you already. This doesn't cover the cases where the user either DMed you first, or accepts DMs from anyone.
But it is probably simplest to try sending and inspect the failures.

Java + RestFB API: Getting fresh Page Access Token without messing with AppID, appSecret

What I want to do:
I am trying to make a simple program that posts 5-10 statuses, at a time, on a page's wall. The post to the page will have to be done under the name of the page.
I've read tons of badly written Facebook Developers documentation and I'm reaching the point of confusion where I don't even know what questions to ask. So her I am.
My code so far:
I manually got the Page Access token manually, by this method:
Go to https://developers.facebook.com/tools/explorer
At the GET request form, down there, fill in me/accounts
You'll get a Javascript representation of your basic user data. Find the page you want.
Note the access_token and id fields, we're going to use them in the code below.
Thus, after getting the page Access token manually (And the ID of the page, of course)
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Parameter;
import com.restfb.exception.FacebookException;
import com.restfb.types.FacebookType;
import com.restfb.types.Page;
import com.restfb.types.User;
/**
*
* #author dsfounis
*/
public class FacebookConnector {
/* Variables */
private final String pageAccessToken = "GOT_THIS_FROM_THE_METHOD_ABOVE";
private final String pageID = "THIS_TOO";
private FacebookClient fbClient;
private User myuser = null; //Store references to myr user and page
private Page mypage = null; //for later use. In this question's context, these
//references are useless.
private int counter = 0;
public FacebookConnector() {
try {
fbClient = new DefaultFacebookClient(pageAccessToken);
myuser = fbClient.fetchObject("me", User.class);
mypage = fbClient.fetchObject(pageID, Page.class);
counter = 0;
} catch (FacebookException ex) { //So that you can see what went wrong
ex.printStackTrace(System.err); //in case you did anything incorrectly
}
}
public void makeTestPost() {
fbClient.publish(pageID + "/feed", FacebookType.class, Parameter.with("message", Integer.toString(counter) + ": Hello, facebook World!"));
counter++;
}
}
The problem:
The code above works. The thing is, it works temporarily. The page access token that I get has an expiration time of one hour, and I need to manually go through the process of obtaining it, every time that I run the program. What is the point of automating a process if I keep some aspects of it manual?
So I have to ask you: Can I do the process above programmatically, and obtain a fresh page access token at program launch?
Can I, maybe, use a better API to do something as simple as just post a couple of things on a Page's wall, every day?
My application is a console one, and I would like to stay away from implementing needless Logins, even though if you tell me that it is needed, it's going to be a bother I'll have to go through.
As a note: I've got the application registered in Facebook Developers, albeit only as a basic app. To get more permissions, I need to show proof of Facebook Login implementation, and as I say in the title, it's something I'll have to avoid.
There is no automatic process to obtain an access token. If there was, it will defeat the whole purpose of the OAuth flow. For pet projects and tests it's okay to use the Graph API Explorer but for public applications involving users it is mandatory that the user manually selects the login dialog.
Under your current scenario you can extend the user token using the method mentioned here https://developers.facebook.com/docs/roadmap/completed-changes/offline-access-removal/
Scenario 5: Page Access Tokens
When a user grants an app the manage_pages permission, the app is able
to obtain page access tokens for pages that the user administers by
querying the [User ID]/accounts Graph API endpoint. With the migration
enabled, when using a short-lived user access token to query this
endpoint, the page access tokens obtained are short-lived as well.
Exchange the short-lived user access token for a long-lived access
token using the endpoint and steps explained earlier.
https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN
By using a
long-lived user access token, querying the [User ID]/accounts endpoint
will now provide page access tokens that do not expire for pages that
a user manages. This will also apply when querying with a non-expiring
user access token obtained through the deprecated offline_access
permission.
A simple program used only by the owner of the application does not need approval from Facebook.
e.g. https://www.facebook.com/phwdbot

Exchange Web Services get Message Message-ID

I'm using the Java EWS library to try to sync messages from an Exchange mailbox. I'm able to get a list off all new messages created since the last sync date, however, I would really like to find out the Message-ID property of the message before loading it from exchange.
Background: I'm trying to integrate EWS sync into an existing mail storage system. The Message-ID identification is solely for performance reasons, as our system already has millions of messaged processed outside of EWS. Having to download them again would cause major performance overhead.
//Sample code to fetch the message from sync
ChangeCollection<ItemChange> icc = service.syncFolderItems( folder.getId()
, PropertySet.FirstClassProperties // propertySet
, null // ignoredItemIds
, 25 // maxChangesReturned
, SyncFolderItemsScope.NormalItems
, currSyncState );
for ( ItemChange ic : icc )
{
if (ic.getChangeType() == ChangeType.Create)
{
Item item = ic.getItem();
//how to get the Message-ID
}
Right now, the best way I see to retrieve the Message-ID is by calling ic.getItem().getInternetMessageHeaders() after calling ic.load(). But that requires loading the entire message from exchange, and I would to avoid this step.
Edit: Another way to grab the Message-ID is
EmailMessage em = EmailMessage.bind( service, item.getId() );
em.getInternetMessageId()
However, that still loads the entire message.
The other solution is to start associating messages by the ItemId, but even that's not perfect: http://daniellang.net/exchange-web-services-itemid-is-not-permanent/
More about Message-ID: http://en.wikipedia.org/wiki/Message-ID
I believe the solution is this:
EmailMessage em = EmailMessage.bind( service, item.getId(),
new PropertySet( EmailMessageSchema.InternetMessageId) );
Explanation :
We have to bind the item to an email message, but instead of grabbing all the info, we only ask for the ID and any additional properties we want through the PropertySet parameter.
Inspired by this answer: https://stackoverflow.com/a/22482779/138228

How to uniquely identify the same user across multiple websites?

I'm doing an advertising network as a project for BS degree.
I;m trying to identify the same user across multiple websites. I have a USER table in my database with ID as an auto_increment number.
In the websites i'm tracking i included the following Javascript :
function OnLoad()
{
var requestURI = window.location;
var resolution = screen.width + 'x' + screen.height;
var colorDepth = screen.colorDepth;
var query = '?requestURI=' + encodeURIComponent(requestURI)
+ '&resolution=' + encodeURIComponent(resolution)
+ '&websiteid=' + encodeURIComponent(id);
document.getElementById("body").innerHTML = "<img src ='http://dan-vaio:8080/licenta/bannerimg.gif'" + query + " width = 500 height = 200 />"; // this is the place where i want to display my banner
}
On the server side A banner choosing algorithm is called and i get a queue of 5 banners that i want to display to this user. (only if the user acceseses the first time this website, otherwise i'd have to display the remaining banners in the queue. Haven't figured out how to do this either, could i keep the queue in a session ? ).
The question is : If i add a cookie to the response in the servlet, will it be avaiable when the same user acceses another website ?
i have this :
Cookie cookie = new Cookie("DisplayedBanners",visitedBanners); //
response.addCookie(cookie);
How can i uniquely identify an user? How to generate a unique ID to keep in the cookie and in the database, so when the same user accesses another website and calls my servlet i will know who he is.
Thanks a lot.
Banner queue will not work either if you use session for this. Session is maintained on the server. If you go to other site the same old session will not work here.
I would suggest that you keep this information in database.
So keep the last_shown_banner_tag with a user_id in a single table.
This table should be common among the websites.
Here it is explained how to do multidomain cookies, but in PHP (requires tweaking the Apache)
http://www.tutorialized.com/tutorial/Implementing-Cross-Domain-Cookies/372

Categories

Resources