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;
}
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();
}
}
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);
}
}
}
Aggregations