Search in sources :

Example 16 with AccessToken

use of twitter4j.auth.AccessToken in project Talon-for-Twitter by klinker24.

the class TwitterMultipleImageHelper method uploadPics.

public boolean uploadPics(File[] pics, String text, Twitter twitter) {
    JSONObject jsonresponse = new JSONObject();
    final String ids_string = getMediaIds(pics, twitter);
    if (ids_string == null) {
        return false;
    }
    try {
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();
        // generate authorization header
        String get_or_post = "POST";
        String oauth_signature_method = "HMAC-SHA1";
        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        // any relatively random alphanumeric string will work here
        String oauth_nonce = uuid_string;
        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        // get current time in milliseconds
        long ts = tempcal.getTimeInMillis();
        // then divide by 1000 to get seconds
        String oauth_timestamp = (new Long(ts / 1000)).toString();
        // the parameter string must be in alphabetical order, "text" parameter added at end
        String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";
        System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string);
        String twitter_endpoint = "https://api.twitter.com/1.1/statuses/update.json";
        String twitter_endpoint_host = "api.twitter.com";
        String twitter_endpoint_path = "/1.1/statuses/update.json";
        String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string);
        String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));
        String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors
        new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors
        new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });
        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpContext context = new BasicHttpContext(null);
        HttpHost host = new HttpHost(twitter_endpoint_host, 443);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
        try {
            try {
                SSLContext sslcontext = SSLContext.getInstance("TLS");
                sslcontext.init(null, null, null);
                SSLSocketFactory ssf = sslcontext.getSocketFactory();
                Socket socket = ssf.createSocket();
                socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
                conn.bind(socket, params);
                BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST", twitter_endpoint_path);
                MultipartEntity reqEntity = new MultipartEntity();
                reqEntity.addPart("media_ids", new StringBody(ids_string));
                reqEntity.addPart("status", new StringBody(text));
                reqEntity.addPart("trim_user", new StringBody("1"));
                request2.setEntity(reqEntity);
                request2.setParams(params);
                request2.addHeader("Authorization", authorization_header_string);
                httpexecutor.preProcess(request2, httpproc, context);
                HttpResponse response2 = httpexecutor.execute(request2, conn, context);
                response2.setParams(params);
                httpexecutor.postProcess(response2, httpproc, context);
                String responseBody = EntityUtils.toString(response2.getEntity());
                System.out.println("response=" + responseBody);
                // error checking here. Otherwise, status should be updated.
                jsonresponse = new JSONObject(responseBody);
                conn.close();
            } catch (HttpException he) {
                System.out.println(he.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus HttpException message=" + he.getMessage());
            } catch (NoSuchAlgorithmException nsae) {
                System.out.println(nsae.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus NoSuchAlgorithmException message=" + nsae.getMessage());
            } catch (KeyManagementException kme) {
                System.out.println(kme.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus KeyManagementException message=" + kme.getMessage());
            } finally {
                conn.close();
            }
        } catch (JSONException jsone) {
            jsone.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    } catch (Exception e) {
    }
    return true;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) AccessToken(twitter4j.auth.AccessToken) BasicHttpParams(org.apache.http.params.BasicHttpParams) SyncBasicHttpParams(org.apache.http.params.SyncBasicHttpParams) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest) Calendar(java.util.Calendar) JSONException(org.json.JSONException) DefaultHttpClientConnection(org.apache.http.impl.DefaultHttpClientConnection) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) JSONException(org.json.JSONException) GeneralSecurityException(java.security.GeneralSecurityException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TwitterException(twitter4j.TwitterException) IOException(java.io.IOException) BasicHttpParams(org.apache.http.params.BasicHttpParams) SyncBasicHttpParams(org.apache.http.params.SyncBasicHttpParams) HttpParams(org.apache.http.params.HttpParams) JSONObject(org.json.JSONObject) StringBody(org.apache.http.entity.mime.content.StringBody) Socket(java.net.Socket)

Example 17 with AccessToken

use of twitter4j.auth.AccessToken in project openhab1-addons by openhab.

the class TwitterActionService method start.

private static void start() {
    if (!Twitter.isEnabled) {
        return;
    }
    Twitter.client = createClient();
    AccessToken accessToken = getAccessToken();
    if (accessToken != null) {
        Twitter.client.setOAuthAccessToken(accessToken);
        logger.info("TwitterAction has been successfully authenticated > awaiting your Tweets!");
    } else {
        logger.info("Twitter authentication failed. Please use OSGi " + "console to restart the org.openhab.io.net-Bundle and re-initiate the authorization process!");
    }
}
Also used : AccessToken(twitter4j.auth.AccessToken)

Example 18 with AccessToken

use of twitter4j.auth.AccessToken in project twitter-2-weibo by rjyo.

the class Twitter2Weibo method syncTwitter.

public void syncTwitter(String userId) {
    T2WUser user = helper.findOneByUser(userId);
    weibo.setToken(user.getToken());
    Twitter twitter = new TwitterFactory().getInstance();
    if (user.getTwitterToken() != null) {
        twitter.setOAuthAccessToken(new AccessToken(user.getTwitterToken(), user.getTwitterTokenSecret()));
        log.debug(String.format("Using OAuth for %s", user.getUserId()));
    }
    StatusFilters filters = new StatusFilters();
    // should be used first
    filters.use(new NoSyncFilter());
    filters.use(new TcoStatusFilter()).use(new URLStatusFilter()).use(new TagStatusFilter()).use(new FlickrImageFilter());
    NoMentionFilter mentionFilter = new NoMentionFilter();
    UserMappingFilter mappingFilter = new UserMappingFilter(helper);
    if (!user.ready()) {
        log.debug(String.format("Skipping @%s ...", user.getUserId()));
        return;
    }
    // gets Twitter instance with default credentials
    String screenName = user.getUserId();
    long latestId = user.getLatestId();
    log.debug(String.format("Checking @%s's timeline, latest ID = %d.", userId, latestId));
    try {
        if (latestId == 0) {
            List<Status> statuses = twitter.getUserTimeline(screenName);
            if (statuses.size() > 0) {
                // Record latestId, and sync next time
                user.setLatestId(statuses.get(0).getId());
            }
            log.info(String.format("First time use for @%s. Set latest ID to %d.", userId, latestId));
        } else {
            Timeline tl = new Timeline();
            Paging paging = new Paging(latestId);
            List<Status> statuses = twitter.getUserTimeline(screenName, paging);
            // sync from the oldest one
            for (int i = statuses.size() - 1; i >= 0; i--) {
                Status status = statuses.get(i);
                // safe keeper
                if (status.getId() < user.getLatestId())
                    continue;
                String name = status.getUser().getScreenName();
                String statusText = status.getText();
                log.info(String.format("@%s - %s", name, statusText));
                try {
                    if (status.isRetweet()) {
                        if (user.isDropRetweets()) {
                            user.setLatestId(status.getId());
                            log.debug("Skipped " + statusText + " because status is a retweet.");
                            continue;
                        } else {
                            filters.remove(mentionFilter);
                            filters.use(mappingFilter);
                        }
                    } else {
                        if (user.isDropMentions()) {
                            filters.remove(mappingFilter);
                            filters.use(mentionFilter);
                        } else {
                            filters.remove(mentionFilter);
                            filters.use(mappingFilter);
                        }
                    }
                    statusText = filters.filter(statusText);
                    if (statusText == null) {
                        user.setLatestId(status.getId());
                        log.info(String.format("Skipped %s because of the filter.", statusText));
                        continue;
                    }
                    if (!user.isNoImage()) {
                        // add twitter images to status text
                        MediaEntity[] mediaEntities = status.getMediaEntities();
                        if (mediaEntities != null) {
                            for (MediaEntity entity : mediaEntities) {
                                statusText += " " + entity.getMediaURL();
                            }
                            log.info("with media url: " + statusText);
                        }
                        StatusImageExtractor ex = new StatusImageExtractor();
                        StringBuffer buf = new StringBuffer(statusText);
                        byte[] image = ex.extract(buf);
                        if (image != null) {
                            user.setLatestId(status.getId());
                            try {
                                // with image urls removed
                                statusText = buf.toString();
                                tl.UploadStatus(statusText, new ImageItem(image));
                                log.info(String.format("@%s - %s sent with image.", name, statusText));
                            } catch (WeiboException e) {
                                log.error("Faile to update image.", e);
                            }
                            continue;
                        }
                    }
                    GeoLocation location = status.getGeoLocation();
                    if (user.isWithGeo() && location != null) {
                        tl.UpdateStatus(statusText, (float) location.getLatitude(), (float) location.getLongitude(), "");
                        log.info(String.format("@%s - %s sent with geo locations.", name, statusText));
                    } else {
                        tl.UpdateStatus(statusText);
                        log.info(String.format("@%s - %s sent.", name, statusText));
                    }
                } catch (WeiboException e) {
                    if (e.getStatusCode() != 400) {
                        // resending same tweet
                        log.warn("Failed to update Weibo");
                        break;
                    }
                }
                user.setLatestId(status.getId());
            }
        }
        helper.saveUser(user);
    } catch (Exception e) {
        if (!(e instanceof TwitterException)) {
            log.error("Failed to update.", e);
        }
    }
}
Also used : AccessToken(twitter4j.auth.AccessToken) StatusImageExtractor(h2weibo.utils.StatusImageExtractor) WeiboException(weibo4j.model.WeiboException) Timeline(weibo4j.Timeline) WeiboException(weibo4j.model.WeiboException) T2WUser(h2weibo.model.T2WUser) ImageItem(weibo4j.http.ImageItem)

Example 19 with AccessToken

use of twitter4j.auth.AccessToken in project twitter-2-weibo by rjyo.

the class TweetServlet method doGet.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession session = request.getSession(false);
    String loginUser = (String) session.getAttribute(Keys.SESSION_LOGIN_USER);
    DBHelper helper = (DBHelper) request.getAttribute(Keys.REQUEST_DB_HELPER);
    T2WUser t2wUser = helper.findOneByUser(loginUser);
    TwitterFactory factory = new TwitterFactory();
    Twitter t = factory.getInstance();
    t.setOAuthAccessToken(new AccessToken(t2wUser.getTwitterToken(), t2wUser.getTwitterTokenSecret()));
    try {
        t.updateStatus("Twitter, say hello to Weibo! Now syncing Twitter 2 Weibo using http://h2weibo.cloudfoundry.com #t2w_sync");
    } catch (TwitterException e) {
        log.error("Failed to send tweets", e);
    }
    response.setStatus(200);
}
Also used : T2WUser(h2weibo.model.T2WUser) HttpSession(javax.servlet.http.HttpSession) DBHelper(h2weibo.model.DBHelper) AccessToken(twitter4j.auth.AccessToken)

Example 20 with AccessToken

use of twitter4j.auth.AccessToken in project ORCID-Source by ORCID.

the class OrcidSocialManagerImpl method tweet.

/**
     * Tweet a message to the specified profile
     * 
     * @param entity
     *            An entity containing the user information and the twitter
     *            credentials
     * @return true if it was able to tweet the updates
     * */
@SuppressWarnings("unchecked")
private boolean tweet(OrcidSocialEntity entity) {
    String jsonCredentials = decrypt(entity.getEncryptedCredentials());
    Map<String, String> credentials = (HashMap<String, String>) JSON.parse(jsonCredentials);
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(twitterKey, twitterSecret);
    AccessToken accessToken = new AccessToken(credentials.get(TWITTER_USER_KEY), credentials.get(TWITTER_USER_SECRET));
    twitter.setOAuthAccessToken(accessToken);
    try {
        twitter.updateStatus(buildUpdateMessage(entity.getId().getOrcid()));
    } catch (Exception e) {
        LOGGER.error("Unable to tweet on profile {}", entity.getId().getOrcid());
        return false;
    }
    return true;
}
Also used : HashMap(java.util.HashMap) AccessToken(twitter4j.auth.AccessToken) Twitter(twitter4j.Twitter) TwitterFactory(twitter4j.TwitterFactory)

Aggregations

AccessToken (twitter4j.auth.AccessToken)22 IOException (java.io.IOException)8 TwitterException (twitter4j.TwitterException)7 Twitter (twitter4j.Twitter)5 TwitterFactory (twitter4j.TwitterFactory)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 InetSocketAddress (java.net.InetSocketAddress)4 Socket (java.net.Socket)4 GeneralSecurityException (java.security.GeneralSecurityException)4 Calendar (java.util.Calendar)4 SSLContext (javax.net.ssl.SSLContext)4 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)4 DefaultHttpClientConnection (org.apache.http.impl.DefaultHttpClientConnection)4 BasicHttpEntityEnclosingRequest (org.apache.http.message.BasicHttpEntityEnclosingRequest)4 BasicHttpParams (org.apache.http.params.BasicHttpParams)4 HttpParams (org.apache.http.params.HttpParams)4 RequestToken (twitter4j.auth.RequestToken)4 T2WUser (h2weibo.model.T2WUser)3 File (java.io.File)3 KeyManagementException (java.security.KeyManagementException)3