Search in sources :

Example 1 with HttpServletRouter

use of h2weibo.HttpServletRouter 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 HttpServletRouter

use of h2weibo.HttpServletRouter in project twitter-2-weibo by rjyo.

the class ErrorServlet method handleRequest.

@Override
protected Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context ctx) {
    HttpServletRouter r = new HttpServletRouter(request);
    r.setPattern("/:errid");
    String errorId = r.get(":errid");
    if (r.is(":errid", "404")) {
        Object url = request.getAttribute("javax.servlet.forward.request_uri");
        ctx.put("url", url);
        log.error("404 Error: " + url);
    } else {
        Exception ex = (Exception) request.getAttribute("javax.servlet.error.exception");
        log.error(errorId + " Error", ex);
        errorId = "500";
    }
    log.info("Redirect to " + errorId);
    return getTemplate(errorId + ".vm");
}
Also used : HttpServletRouter(h2weibo.HttpServletRouter)

Example 3 with HttpServletRouter

use of h2weibo.HttpServletRouter 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 4 with HttpServletRouter

use of h2weibo.HttpServletRouter in project twitter-2-weibo by rjyo.

the class LoginUserFilter method doFilter.

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRouter r = new HttpServletRouter((HttpServletRequest) req);
    r.setPattern("/:id");
    HttpSession session = ((HttpServletRequest) req).getSession();
    String user = (String) session.getAttribute(Keys.SESSION_LOGIN_USER);
    String uri = ((HttpServletRequest) req).getRequestURI();
    log.info("Filtering " + uri);
    if ("/u/save".equals(uri) || r.is(":id", user)) {
        chain.doFilter(req, res);
    } else {
        if ("/u/logout".equals(uri)) {
            log.info("Logged @" + user + " out");
            session.removeAttribute(Keys.SESSION_LOGIN_USER);
            ((HttpServletResponse) res).sendRedirect("/");
        } else {
            log.info("Not logged in. Redirect to twitter login.");
            ((HttpServletResponse) res).sendRedirect("/auth/twitter");
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpSession(javax.servlet.http.HttpSession) HttpServletRouter(h2weibo.HttpServletRouter) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 5 with HttpServletRouter

use of h2weibo.HttpServletRouter 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)

Aggregations

HttpServletRouter (h2weibo.HttpServletRouter)5 HttpSession (javax.servlet.http.HttpSession)4 WeiboException (weibo4j.model.WeiboException)3 DBHelper (h2weibo.model.DBHelper)2 T2WUser (h2weibo.model.T2WUser)2 Twitter (twitter4j.Twitter)2 TwitterException (twitter4j.TwitterException)2 TwitterFactory (twitter4j.TwitterFactory)2 Oauth (weibo4j.Oauth)2 PrintWriter (java.io.PrintWriter)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 twitter4j (twitter4j)1 AccessToken (twitter4j.auth.AccessToken)1 RequestToken (twitter4j.auth.RequestToken)1 Account (weibo4j.Account)1 Users (weibo4j.Users)1 Weibo (weibo4j.Weibo)1 AccessToken (weibo4j.http.AccessToken)1 User (weibo4j.model.User)1