Search in sources :

Example 1 with WeiboException

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

the class CallbackServlet method doGet.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpServletRouter r = new HttpServletRouter(request);
    r.setPattern("/:type");
    if (request.getParameter("denied") != null) {
        response.sendRedirect("/");
        return;
    }
    HttpSession session = request.getSession(false);
    String loginUser = (String) session.getAttribute(Keys.SESSION_LOGIN_USER);
    String oauthVerifier = request.getParameter("oauth_verifier");
    DBHelper helper = (DBHelper) request.getAttribute(Keys.REQUEST_DB_HELPER);
    if (r.is(":type", "weibo.jsp")) {
        String code = request.getParameter("code");
        if (code != null) {
            T2WUser tid = helper.findOneByUser(loginUser);
            if (tid.getToken() == null) {
                // send for the first time
                session.setAttribute(Keys.SESSION_PROMPT_TWEET, "You are ready to go! Do you want to tweet about this service and share it with your friends?");
            }
            Oauth oauth = new Oauth();
            try {
                AccessToken token = oauth.getAccessTokenByCode(code);
                tid.setToken(token.getAccessToken());
                Weibo weibo = new Weibo();
                weibo.setToken(tid.getToken());
                Account am = new Account();
                try {
                    JSONObject obj = am.getUid();
                    String uid = obj.getString("uid");
                    tid.setWeiboUserId(uid);
                } catch (WeiboException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                helper.saveUser(tid);
            } catch (WeiboException e) {
                log.error(e);
            }
        } else {
            log.error("Can't auth " + loginUser + " for Weibo. " + request.getQueryString());
        }
    } else if (r.is(":type", "twitter")) {
        try {
            TwitterFactory factory = new TwitterFactory();
            Twitter t = factory.getInstance();
            twitter4j.auth.RequestToken req = (RequestToken) session.getAttribute(Keys.SESSION_REQUEST_TOKEN);
            twitter4j.auth.AccessToken accessToken = t.getOAuthAccessToken(req, oauthVerifier);
            session.removeAttribute(Keys.SESSION_REQUEST_TOKEN);
            if (accessToken != null) {
                t.setOAuthAccessToken(accessToken);
                User user = t.verifyCredentials();
                loginUser = user.getScreenName();
                T2WUser tid = helper.findOneByUser(loginUser);
                if (tid.getTwitterToken() == null) {
                    // save latest id for the first time. sync from that tweet
                    ResponseList<Status> tl = t.getUserTimeline();
                    if (tl.size() > 0) {
                        Status s = tl.get(0);
                        tid.setLatestId(s.getId());
                    }
                }
                tid.setTwitterToken(accessToken.getToken());
                tid.setTwitterTokenSecret(accessToken.getTokenSecret());
                helper.saveUser(tid);
                session.setAttribute(Keys.SESSION_LOGIN_USER, loginUser);
            }
        } catch (TwitterException e) {
            log.error("Twitter Exception", e);
            throw new RuntimeException(e);
        }
    }
    String requestUrl = (String) session.getAttribute(Keys.SESSION_REQUEST_URL);
    if (requestUrl != null) {
        session.removeAttribute(Keys.SESSION_REQUEST_URL);
        response.sendRedirect(requestUrl);
    } else {
        response.sendRedirect("/u/" + loginUser);
    }
}
Also used : Account(weibo4j.Account) T2WUser(h2weibo.model.T2WUser) HttpSession(javax.servlet.http.HttpSession) DBHelper(h2weibo.model.DBHelper) JSONException(weibo4j.org.json.JSONException) twitter4j(twitter4j) Oauth(weibo4j.Oauth) Weibo(weibo4j.Weibo) WeiboException(weibo4j.model.WeiboException) T2WUser(h2weibo.model.T2WUser) JSONObject(weibo4j.org.json.JSONObject) AccessToken(weibo4j.http.AccessToken) RequestToken(twitter4j.auth.RequestToken) HttpServletRouter(h2weibo.HttpServletRouter)

Example 2 with WeiboException

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

the class UserServlet method handleRequest.

@Override
protected Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context ctx) {
    HttpServletRouter r = new HttpServletRouter(request);
    r.setPattern("/:id");
    HttpSession session = request.getSession(false);
    DBHelper helper = (DBHelper) request.getAttribute(Keys.REQUEST_DB_HELPER);
    // Service limit
    String uId = r.get(":id");
    if (!helper.isUser(uId) && helper.getUserCount() > 50) {
        return getTemplate("full.vm");
    }
    T2WUser user = helper.findOneByUser(uId);
    if (r.has(":id")) {
        log.info("Displaying user info for @" + uId);
        ctx.put("user_id", uId);
        ctx.put("user", helper.findOneByUser(uId));
        try {
            User weiboUser = (User) session.getAttribute(Keys.SESSION_WEIBO_USER);
            if (weiboUser == null) {
                Users um = new Users();
                weiboUser = um.showUserById(user.getWeiboUserId());
                session.setAttribute(Keys.SESSION_WEIBO_USER, weiboUser);
            }
            ctx.put("weibo_user", weiboUser.getScreenName());
            ctx.put("weibo_user_image", weiboUser.getProfileImageURL().toString());
            ctx.put("weibo_login", 1);
            // save weiboUser ID mapping
            helper.setWeiboId(user.getUserId(), weiboUser.getScreenName());
        } catch (Exception e) {
            // 401 = not logged in
            if (e instanceof WeiboException && ((WeiboException) e).getStatusCode() != 401) {
                e.printStackTrace();
            }
        }
        try {
            twitter4j.User twitterUser = (twitter4j.User) session.getAttribute(Keys.SESSION_TWITTER_USER);
            if (twitterUser == null) {
                TwitterFactory factory = new TwitterFactory();
                Twitter t = factory.getInstance();
                t.setOAuthAccessToken(new AccessToken(user.getTwitterToken(), user.getTwitterTokenSecret()));
                twitterUser = t.verifyCredentials();
                session.setAttribute(Keys.SESSION_TWITTER_USER, twitterUser);
            }
            ctx.put("twitter_user", twitterUser.getScreenName());
            ctx.put("twitter_user_image", twitterUser.getProfileImageURL().toString());
            ctx.put("twitter_login", 1);
        } catch (Exception e) {
            // 401 = not logged in
            if (e instanceof TwitterException && ((TwitterException) e).getStatusCode() != 401) {
                e.printStackTrace();
            }
        }
    }
    Object message = session.getAttribute(Keys.SESSION_MESSAGE);
    if (message != null) {
        ctx.put("message", message);
        session.removeAttribute(Keys.SESSION_MESSAGE);
    }
    Object prompt = session.getAttribute(Keys.SESSION_PROMPT_TWEET);
    if (prompt != null) {
        ctx.put("prompt", prompt);
        session.removeAttribute(Keys.SESSION_PROMPT_TWEET);
    }
    return getTemplate("user.vm");
}
Also used : T2WUser(h2weibo.model.T2WUser) User(weibo4j.model.User) HttpSession(javax.servlet.http.HttpSession) DBHelper(h2weibo.model.DBHelper) Twitter(twitter4j.Twitter) Users(weibo4j.Users) TwitterFactory(twitter4j.TwitterFactory) WeiboException(weibo4j.model.WeiboException) TwitterException(twitter4j.TwitterException) WeiboException(weibo4j.model.WeiboException) T2WUser(h2weibo.model.T2WUser) AccessToken(twitter4j.auth.AccessToken) HttpServletRouter(h2weibo.HttpServletRouter) TwitterException(twitter4j.TwitterException)

Example 3 with WeiboException

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

the class HttpClient method multPartURL.

/**
	 * 支持multipart方式上传图片
	 * 
	 */
public Response multPartURL(String url, PostParameter[] params, ImageItem item) throws WeiboException {
    PostMethod postMethod = new PostMethod(url);
    try {
        Part[] parts = null;
        if (params == null) {
            parts = new Part[1];
        } else {
            parts = new Part[params.length + 1];
        }
        if (params != null) {
            int i = 0;
            for (PostParameter entry : params) {
                parts[i++] = new StringPart(entry.getName(), (String) entry.getValue());
            }
            parts[parts.length - 1] = new ByteArrayPart(item.getContent(), item.getName(), item.getContentType());
        }
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
        return httpRequest(postMethod);
    } catch (Exception ex) {
        throw new WeiboException(ex.getMessage(), ex, -1);
    }
}
Also used : WeiboException(weibo4j.model.WeiboException) PostParameter(weibo4j.model.PostParameter) PostMethod(org.apache.commons.httpclient.methods.PostMethod) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) JSONException(weibo4j.org.json.JSONException) IOException(java.io.IOException) WeiboException(weibo4j.model.WeiboException)

Example 4 with WeiboException

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

the class HttpClient method multPartURL.

public Response multPartURL(String fileParamName, String url, PostParameter[] params, File file, boolean authenticated) throws WeiboException {
    PostMethod postMethod = new PostMethod(url);
    try {
        Part[] parts = null;
        if (params == null) {
            parts = new Part[1];
        } else {
            parts = new Part[params.length + 1];
        }
        if (params != null) {
            int i = 0;
            for (PostParameter entry : params) {
                parts[i++] = new StringPart(entry.getName(), (String) entry.getValue());
            }
        }
        FilePart filePart = new FilePart(fileParamName, file.getName(), file, new MimetypesFileTypeMap().getContentType(file), "UTF-8");
        filePart.setTransferEncoding("binary");
        parts[parts.length - 1] = filePart;
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
        return httpRequest(postMethod);
    } catch (Exception ex) {
        throw new WeiboException(ex.getMessage(), ex, -1);
    }
}
Also used : MimetypesFileTypeMap(javax.activation.MimetypesFileTypeMap) WeiboException(weibo4j.model.WeiboException) PostParameter(weibo4j.model.PostParameter) PostMethod(org.apache.commons.httpclient.methods.PostMethod) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) JSONException(weibo4j.org.json.JSONException) IOException(java.io.IOException) WeiboException(weibo4j.model.WeiboException)

Example 5 with WeiboException

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

the class HttpClient method httpRequest.

public Response httpRequest(HttpMethod method, Boolean WithTokenHeader) throws WeiboException {
    InetAddress ipaddr;
    int responseCode = -1;
    try {
        ipaddr = InetAddress.getLocalHost();
        List<Header> headers = new ArrayList<Header>();
        if (WithTokenHeader) {
            if (token == null) {
                throw new IllegalStateException("Oauth2 token is not set!");
            }
            headers.add(new Header("Authorization", "OAuth2 " + token));
            headers.add(new Header("API-RemoteIP", ipaddr.getHostAddress()));
            client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
            for (Header hd : headers) {
                log(hd.getName() + ": " + hd.getValue());
            }
        }
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        client.executeMethod(method);
        Header[] resHeader = method.getResponseHeaders();
        responseCode = method.getStatusCode();
        log("Response:");
        log("https StatusCode:" + String.valueOf(responseCode));
        for (Header header : resHeader) {
            log(header.getName() + ":" + header.getValue());
        }
        Response response = new Response();
        response.setResponseAsString(method.getResponseBodyAsString());
        log(response.toString() + "\n");
        if (responseCode != OK) {
            try {
                throw new WeiboException(getCause(responseCode), response.asJSONObject(), method.getStatusCode());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return response;
    } catch (IOException ioe) {
        throw new WeiboException(ioe.getMessage(), ioe, responseCode);
    } finally {
        method.releaseConnection();
    }
}
Also used : WeiboException(weibo4j.model.WeiboException) Header(org.apache.commons.httpclient.Header) ArrayList(java.util.ArrayList) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) JSONException(weibo4j.org.json.JSONException) IOException(java.io.IOException) InetAddress(java.net.InetAddress)

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