use of weibo4j.WeiboException in project twitter-2-weibo by rjyo.
the class HttpClient method httpRequest.
public Response httpRequest(String url, PostParameter[] postParams, boolean authenticated, String httpMethod) throws WeiboException {
int retriedCount;
int retry = retryCount + 1;
Response res = null;
for (retriedCount = 0; retriedCount < retry; retriedCount++) {
int responseCode = -1;
try {
HttpURLConnection con = null;
OutputStream osw = null;
try {
con = getConnection(url);
con.setDoInput(true);
setHeaders(url, postParams, con, authenticated, httpMethod);
if (null != postParams || "POST".equals(httpMethod)) {
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setDoOutput(true);
String postParam = "";
if (postParams != null) {
postParam = encodeParameters(postParams);
}
log("Post Params: ", postParam);
byte[] bytes = postParam.getBytes("UTF-8");
con.setRequestProperty("Content-Length", Integer.toString(bytes.length));
osw = con.getOutputStream();
osw.write(bytes);
osw.flush();
osw.close();
} else if ("DELETE".equals(httpMethod)) {
con.setRequestMethod("DELETE");
} else {
con.setRequestMethod("GET");
}
res = new Response(con);
responseCode = con.getResponseCode();
if (DEBUG) {
log("Response: ");
Map<String, List<String>> responseHeaders = con.getHeaderFields();
for (String key : responseHeaders.keySet()) {
List<String> values = responseHeaders.get(key);
for (String value : values) {
if (null != key) {
log(key + ": " + value);
} else {
log(value);
}
}
}
}
if (responseCode != OK) {
if (responseCode < INTERNAL_SERVER_ERROR || retriedCount == retryCount) {
throw new WeiboException(getCause(responseCode) + "\n" + res.asString(), responseCode);
}
// will retry if the status code is INTERNAL_SERVER_ERROR
} else {
break;
}
} finally {
try {
osw.close();
} catch (Exception ignore) {
}
}
} catch (IOException ioe) {
// connection timeout or read timeout
if (retriedCount == retryCount) {
throw new WeiboException(ioe.getMessage(), ioe, responseCode);
}
}
try {
if (DEBUG && null != res) {
res.asString();
}
log("Sleeping " + retryIntervalMillis + " millisecs for next retry.");
Thread.sleep(retryIntervalMillis);
} catch (InterruptedException ignore) {
// nothing to do
}
}
return res;
}
use of weibo4j.WeiboException in project twitter-2-weibo by rjyo.
the class HttpClient method multPartURL.
public Response multPartURL(String url, PostParameter[] params, ImageItem item, boolean authenticated) throws WeiboException {
PostMethod post = new PostMethod(url);
try {
org.apache.commons.httpclient.HttpClient client = getHttpClient();
long t = System.currentTimeMillis();
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());
}
post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
List<Header> headers = new ArrayList<Header>();
if (authenticated) {
if (oauth == null) {
}
String authorization = null;
if (null != oauth) {
// use OAuth
authorization = oauth.generateAuthorizationHeader("POST", url, params, oauthToken);
} else {
throw new IllegalStateException("Neither user ID/password combination nor OAuth consumer key/secret combination supplied");
}
headers.add(new Header("Authorization", authorization));
log("Authorization: " + authorization);
}
client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
client.executeMethod(post);
Response response = new Response();
response.setResponseAsString(post.getResponseBodyAsString());
response.setStatusCode(post.getStatusCode());
log("multPartURL URL:" + url + ", result:" + response + ", time:" + (System.currentTimeMillis() - t));
return response;
} catch (Exception ex) {
throw new WeiboException(ex.getMessage(), ex, -1);
} finally {
post.releaseConnection();
}
}
use of weibo4j.WeiboException in project twitter-2-weibo by rjyo.
the class HttpClient method getOAuthAccessToken.
/**
* @param 通过request token和pin获取access token
* @return access token
* @throws WeiboException
* @since Weibo4J 1.2.1
*/
public AccessToken getOAuthAccessToken(RequestToken token, String pin) throws WeiboException {
try {
this.oauthToken = token;
this.oauthToken = new AccessToken(httpRequest(accessTokenURL, new PostParameter[] { new PostParameter("oauth_verifier", pin) }, true));
} catch (WeiboException te) {
throw new WeiboException("The user has not given access to the account.", te, te.getStatusCode());
}
return (AccessToken) this.oauthToken;
}
use of weibo4j.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 {
weibo4j.User weiboUser = (weibo4j.User) session.getAttribute(Keys.SESSION_WEIBO_USER);
if (weiboUser == null) {
Weibo w = new Weibo();
w.setToken(user.getToken(), user.getTokenSecret());
weiboUser = w.verifyCredentials();
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");
}
use of weibo4j.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 token = (String) session.getAttribute(Keys.SESSION_TOKEN);
String tokenSecret = (String) session.getAttribute(Keys.SESSION_TOKEN_SECRET);
String oauthVerifier = request.getParameter("oauth_verifier");
DBHelper helper = (DBHelper) request.getAttribute(Keys.REQUEST_DB_HELPER);
if (r.is(":type", "weibo")) {
try {
Weibo weibo = new Weibo();
AccessToken accessToken = weibo.getOAuthAccessToken(token, tokenSecret, oauthVerifier);
if (accessToken != 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?");
}
tid.setToken(accessToken.getToken());
tid.setTokenSecret(accessToken.getTokenSecret());
helper.saveUser(tid);
} else {
log.error("Can't auth " + loginUser + " for Weibo. " + request.getQueryString());
}
} catch (WeiboException e) {
log.error("Weibo Exception", e);
throw new RuntimeException(e);
}
} 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);
}
}
Aggregations