Search in sources :

Example 6 with WeiboException

use of weibo4j.model.WeiboException in project twitter-2-weibo by rjyo.

the class Response method asString.

/**
     * Returns the response body as string.<br>
     * Disconnects the internal HttpURLConnection silently.
     * @return response body
     * @throws WeiboException
     */
public String asString() throws WeiboException {
    if (null == responseAsString) {
        BufferedReader br;
        try {
            InputStream stream = asStream();
            if (null == stream) {
                return null;
            }
            br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
            StringBuffer buf = new StringBuffer();
            String line;
            while (null != (line = br.readLine())) {
                buf.append(line).append("\n");
            }
            this.responseAsString = buf.toString();
            if (Configuration.isDalvik()) {
                this.responseAsString = unescape(responseAsString);
            }
            log(responseAsString);
            stream.close();
            con.disconnect();
            streamConsumed = true;
        } catch (NullPointerException npe) {
            // don't remember in which case npe can be thrown
            throw new WeiboException(npe.getMessage(), npe);
        } catch (IOException ioe) {
            throw new WeiboException(ioe.getMessage(), ioe);
        }
    }
    return responseAsString;
}
Also used : WeiboException(weibo4j.model.WeiboException) InputStreamReader(java.io.InputStreamReader) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException)

Example 7 with WeiboException

use of weibo4j.model.WeiboException in project twitter-2-weibo by rjyo.

the class AuthServlet method doGet.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpServletRouter r = new HttpServletRouter(request);
    r.setPattern("/:type");
    response.setContentType("text/plain");
    PrintWriter writer = response.getWriter();
    String serverPath = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    HttpSession session = request.getSession();
    if (r.is(":type", "weibo")) {
        try {
            Oauth oauth = new Oauth();
            String redirectUrl = oauth.authorize("code");
            response.setStatus(302);
            response.setHeader("Location", redirectUrl);
            log.info("Redirecting Weibo...");
        } catch (WeiboException e) {
            log.error(e);
        }
    } else if (r.is(":type", "twitter")) {
        log.info("hello world~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        try {
            TwitterFactory factory = new TwitterFactory();
            Twitter t = factory.getInstance();
            twitter4j.auth.RequestToken requestToken = t.getOAuthRequestToken(serverPath + "/callback/twitter");
            response.setStatus(302);
            log.info(requestToken.getAuthenticationURL());
            response.setHeader("Location", requestToken.getAuthenticationURL());
            session.setAttribute(Keys.SESSION_REQUEST_TOKEN, requestToken);
            log.info("Redirecting Twitter...");
        } catch (TwitterException e) {
            log.error(e);
        }
        writer.close();
    } else {
        response.setStatus(200);
        writer.println("Wrong parameter, not working!");
        writer.close();
    }
}
Also used : Oauth(weibo4j.Oauth) WeiboException(weibo4j.model.WeiboException) HttpSession(javax.servlet.http.HttpSession) HttpServletRouter(h2weibo.HttpServletRouter) Twitter(twitter4j.Twitter) TwitterFactory(twitter4j.TwitterFactory) TwitterException(twitter4j.TwitterException) PrintWriter(java.io.PrintWriter)

Example 8 with WeiboException

use of weibo4j.model.WeiboException 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)

Aggregations

WeiboException (weibo4j.model.WeiboException)8 IOException (java.io.IOException)4 JSONException (weibo4j.org.json.JSONException)4 HttpServletRouter (h2weibo.HttpServletRouter)3 T2WUser (h2weibo.model.T2WUser)3 HttpSession (javax.servlet.http.HttpSession)3 DBHelper (h2weibo.model.DBHelper)2 PostMethod (org.apache.commons.httpclient.methods.PostMethod)2 FilePart (org.apache.commons.httpclient.methods.multipart.FilePart)2 MultipartRequestEntity (org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)2 Part (org.apache.commons.httpclient.methods.multipart.Part)2 StringPart (org.apache.commons.httpclient.methods.multipart.StringPart)2 Twitter (twitter4j.Twitter)2 TwitterException (twitter4j.TwitterException)2 TwitterFactory (twitter4j.TwitterFactory)2 AccessToken (twitter4j.auth.AccessToken)2 Oauth (weibo4j.Oauth)2 PostParameter (weibo4j.model.PostParameter)2 StatusImageExtractor (h2weibo.utils.StatusImageExtractor)1 BufferedReader (java.io.BufferedReader)1