List of usage examples for twitter4j TwitterException getStatusCode
public int getStatusCode()
From source file:jp.gihyo.wicket.AppSession.java
License:Apache License
public boolean login(String userName, String password) { Twitter client = new TwitterClient(userName, password); try {/* ww w . ja va 2s .c o m*/ User user = client.verifyCredentials(); if (user != null) { twitterUser = user; twitterSession = client; return true; } } catch (TwitterException ex) { if (ex.getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED) { lastUnauthorizedMessage = ex.getMessage(); return false; } } return false; }
From source file:jp.gihyo.wicket.page.ajax.AjaxTimeline.java
License:Apache License
private void constructPage() { final TweetForm form = new TweetForm("tweetForm"); add(form);//from w w w .ja v a 2s .c o m feedback = new FeedbackPanel("feedback"); feedback.setOutputMarkupId(true); add(feedback); IModel<List<Status>> statusModel = new LoadableDetachableModel<List<Status>>() { @Override protected List<Status> load() { try { Twitter twitter = AppSession.get().getTwitterSession(); return twitter.getFriendsTimeline(new Paging(currentPageNumber, ITEMS_PER_PAGE)); } catch (TwitterException ex) { AjaxTimeline.this.error(getString("canNotRetrieveFriendTimeline")); return Collections.emptyList(); } } }; ListView<Status> timeline = new ListView<Status>("statusView", statusModel) { @Override protected void populateItem(final ListItem<Status> item) { final Status status = item.getModelObject(); String userUrl = "http://twitter.com/" + status.getUser().getScreenName(); ExternalLink imageLink = new ExternalLink("imageLink", userUrl); //ImageR|?[lg?A<img>^Osrc??X`?X WebMarkupContainer userImage = new WebMarkupContainer("userImage"); userImage.add(new SimpleAttributeModifier("src", status.getUser().getProfileImageURL().toString())); imageLink.add(userImage); item.add(imageLink); ExternalLink screenNameLink = new ExternalLink("screenName", userUrl, status.getUser().getScreenName()); item.add(screenNameLink); Label content = new Label("tweetContent", status.getText()); item.add(content); ExternalLink tweetLink = new ExternalLink("tweetLink", userUrl + "/status/" + status.getId(), null); item.add(tweetLink); Label time = new Label("tweetTime", new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(status.getCreatedAt())); tweetLink.add(time); Label clientName = new Label("clientName", status.getSource()); item.add(clientName.setEscapeModelStrings(false)); /* * YXe?[^XCo^\xNX?B * ?\bh?A??[JNX`?B * ??[JNX?ANXOstatus?ANZX?B */ class FavorateLabel extends Label { private static final long serialVersionUID = -2194580825236126312L; private Status targetStatus; private boolean needRefresh; public FavorateLabel(String id) { super(id); this.targetStatus = status; setDefaultModel(new AbstractReadOnlyModel<String>() { @Override public String getObject() { try { if (needRefresh) { targetStatus = getCurrentStatus(status.getId()); needRefresh = false; } return targetStatus == null ? "" : targetStatus.isFavorited() ? "unfav" : "fav"; } catch (TwitterException ex) { LOGGER.error("Can not fetch current status for status id = " + status.getId(), ex); return "error"; } } }); } public void setNeedRefresh(boolean needRefresh) { this.needRefresh = needRefresh; } } //CNx final FavorateLabel favName = new FavorateLabel("favName"); favName.setOutputMarkupId(true); /* * AjaxCN?B * Xe?[^XCo^o^?Ao^???s?B * o^???AAjaxg?Ay?[WS?ACo^Xe?[^X * Nx??B */ AjaxLink<Void> favLink = new AjaxLink<Void>("favLink") { @Override public void onClick(AjaxRequestTarget target) { try { Status currentStatus = getCurrentStatus(status.getId()); Twitter twitterSession = AppSession.get().getTwitterSession(); if (currentStatus.isFavorited()) { twitterSession.destroyFavorite(currentStatus.getId()); info(getString("favorateRemoved")); } else { twitterSession.createFavorite(currentStatus.getId()); info(getString("favorateRegistered")); } favName.setNeedRefresh(true); target.addComponent(feedback); //o^?bZ?[W\?AtB?[hobNpl?X?V?B target.addComponent(favName); } catch (TwitterException ex) { String message = getString("catNotCreateFavorite") + ": " + ex.getStatusCode(); error(message); LOGGER.error(message, ex); } } }; item.add(favLink); favLink.add(favName); //AJAX LINK item.add(new AjaxLink<Void>("replyLink") { @Override public void onClick(AjaxRequestTarget target) { String targetScreenName = status.getUser().getScreenName(); form.insertText(target, "@" + targetScreenName + " "); } }); //Q?l?AreplyLinkJavaScriptp // item.add(new Link<Void>("replyLink") { // @Override // public void onClick() { // } // // @Override // protected CharSequence getOnClickScript(CharSequence url) { // return "getElementById('" + form.getTextAreaId() + "').value = '@" + status.getUser().getScreenName() + " ';" + // "getElementById('" + form.getTextAreaId() + "').focus(); return false;"; // } // }); } }; //ListView\e?s????BreuseItemsv?peB??A //y?[W\?Ay?[WTu~bg?AXgeIuWFNg\??B //twitterey?[We?X??AXg????AXge? //Xe?[^Xu?A??dv?B timeline.setReuseItems(true); add(timeline); /* * y?[WO?EirQ?[^ */ add(new PagingLink("paging", AjaxTimeline.class, new AbstractReadOnlyModel<Integer>() { @Override public Integer getObject() { return getCurrentPage(); } })); }
From source file:jp.gihyo.wicket.page.paging.PagingTimeline.java
License:Apache License
private void constructPage() { final TweetForm form = new TweetForm("tweetForm"); add(form);// w w w. j ava 2 s.c o m feedback = new FeedbackPanel("feedback"); feedback.setOutputMarkupId(true); add(feedback); /* * ^CCpIModel?B * ??[hf?[^NGXg?EX|X?ETCNLbV?A * LoadableDetachableModelNXgp?B */ IModel<List<Status>> statusModel = new LoadableDetachableModel<List<Status>>() { @Override protected List<Status> load() { try { Twitter twitter = AppSession.get().getTwitterSession(); return twitter.getFriendsTimeline(new Paging(currentPageNumber, ITEMS_PER_PAGE)); } catch (TwitterException ex) { PagingTimeline.this.error(getString("canNotRetrieveFriendTimeline")); return Collections.emptyList(); } } }; /* * ^CCXg */ ListView<Status> timeline = new ListView<Status>("statusView", statusModel) { @Override protected void populateItem(final ListItem<Status> item) { final Status status = item.getModelObject(); String userUrl = "http://twitter.com/" + status.getUser().getScreenName(); ExternalLink imageLink = new ExternalLink("imageLink", userUrl); //ImageR|?[lg?A<img>^Osrc??X`?X WebMarkupContainer userImage = new WebMarkupContainer("userImage"); userImage.add(new SimpleAttributeModifier("src", status.getUser().getProfileImageURL().toString())); imageLink.add(userImage); item.add(imageLink); ExternalLink screenNameLink = new ExternalLink("screenName", userUrl, status.getUser().getScreenName()); item.add(screenNameLink); Label content = new Label("tweetContent", status.getText()); item.add(content); ExternalLink tweetLink = new ExternalLink("tweetLink", userUrl + "/status/" + status.getId(), null); item.add(tweetLink); Label time = new Label("tweetTime", new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(status.getCreatedAt())); tweetLink.add(time); Label clientName = new Label("clientName", status.getSource()); item.add(clientName.setEscapeModelStrings(false)); /* * CNx?BIModel?f?A?fav/unfav * \?B */ final Label favName = new Label("favName", new AbstractReadOnlyModel<String>() { @Override public String getObject() { return status.isFavorited() ? "unfav" : "fav"; } }); /* * CN?BNbN?C?E??s?B */ Link<Void> favLink = new Link<Void>("favLink") { @Override public void onClick() { try { Twitter twitterSession = AppSession.get().getTwitterSession(); if (status.isFavorited()) { twitterSession.destroyFavorite(status.getId()); info(getString("favorateRemoved")); } else { twitterSession.createFavorite(status.getId()); info(getString("favorateRegistered")); } } catch (TwitterException ex) { String message = getString("catNotCreateFavorite") + ": " + ex.getStatusCode(); error(message); LOGGER.error(message, ex); } } }; item.add(favLink); favLink.add(favName); /* * vCpN?B * ?u@screenName?v?B */ item.add(new Link<Void>("replyLink") { @Override public void onClick() { String targetScreenName = status.getUser().getScreenName(); form.insertText("@" + targetScreenName + " "); } }); } }; //ListView\e?s????BreuseItemsv?peB??A //y?[W\?Ay?[WTu~bg?AXgeIuWFNg\??B //twitterey?[We?X??AXg????AXge? //Xe?[^Xu?A??dv?B timeline.setReuseItems(true); add(timeline); /* * y?[WO?EirQ?[^ */ add(new PagingLink("paging", PagingTimeline.class, new AbstractReadOnlyModel<Integer>() { @Override public Integer getObject() { return getCurrentPage(); } })); }
From source file:jp.gihyo.wicket.page.simple.MyTimeline.java
License:Apache License
private void constructPage() { final TweetForm form = new TweetForm("tweetForm"); add(form);/*from w w w . j a v a 2 s . c om*/ feedback = new FeedbackPanel("feedback"); feedback.setOutputMarkupId(true); add(feedback); /* * ^CCpIModel?B * ??[hf?[^NGXg?EX|X?ETCNLbV?A * LoadableDetachableModelNXgp?B */ IModel<List<Status>> statusModel = new LoadableDetachableModel<List<Status>>() { @Override protected List<Status> load() { try { Twitter twitter = AppSession.get().getTwitterSession(); return twitter.getFriendsTimeline(new Paging(1, ITEMS_PER_PAGE)); } catch (TwitterException ex) { MyTimeline.this.error(getString("canNotRetrieveFriendTimeline")); return Collections.emptyList(); } } }; /* * ^CCXg */ ListView<Status> timeline = new ListView<Status>("statusView", statusModel) { @Override protected void populateItem(final ListItem<Status> item) { final Status status = item.getModelObject(); String userUrl = "http://twitter.com/" + status.getUser().getScreenName(); ExternalLink imageLink = new ExternalLink("imageLink", userUrl); byte[] byteArray = {};/* f?[^?? */ UrlResourceStream stream = new UrlResourceStream(status.getUser().getProfileImageURL()); try { stream.getInputStream().read(byteArray); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ResourceStreamNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Image userImage = new Image("userImage", new ByteArrayResource("image/jpeg", byteArray)); imageLink.add(userImage); item.add(imageLink); ExternalLink screenNameLink = new ExternalLink("screenName", userUrl, status.getUser().getScreenName()); item.add(screenNameLink); Label content = new Label("tweetContent", status.getText()); item.add(content); ExternalLink tweetLink = new ExternalLink("tweetLink", userUrl + "/status/" + status.getId(), null); item.add(tweetLink); Label time = new Label("tweetTime", new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(status.getCreatedAt())); tweetLink.add(time); Label clientName = new Label("clientName", status.getSource()); item.add(clientName.setEscapeModelStrings(false)); /* * CNx?BIModel?f?A?fav/unfav * \?B */ final Label favName = new Label("favName", new AbstractReadOnlyModel<String>() { @Override public String getObject() { return status.isFavorited() ? "unfav" : "fav"; } }); /* * CN?BNbN?C?E??s?B */ Link<Void> favLink = new Link<Void>("favLink") { @Override public void onClick() { try { Twitter twitterSession = AppSession.get().getTwitterSession(); if (status.isFavorited()) { twitterSession.destroyFavorite(status.getId()); info(getString("favorateRemoved")); } else { twitterSession.createFavorite(status.getId()); info(getString("favorateRegistered")); } } catch (TwitterException ex) { String message = getString("catNotCreateFavorite") + ": " + ex.getStatusCode(); error(message); LOGGER.error(message, ex); } } }; item.add(favLink); favLink.add(favName); /* * vCpN?B * ?u@screenName?v?B */ item.add(new Link<Void>("replyLink") { @Override public void onClick() { String targetScreenName = status.getUser().getScreenName(); form.insertText("@" + targetScreenName + " "); } }); } }; //ListView\e?s????BreuseItemsv?peB??A //y?[W\?Ay?[WTu~bg?AXgeIuWFNg\??B //twitterey?[We?X??AXg????AXge? //Xe?[^Xu?A??dv?B timeline.setReuseItems(true); add(timeline); }
From source file:jp.ky.twittersample.UpdateStatus.java
License:Apache License
/** * Usage: java twitter4j.examples.tweets.UpdateStatus [text] * * @param args message/*w w w . j ava 2 s . c o m*/ */ public static void main(String[] args) { // if (args.length < 1) { // System.out.println("Usage: java twitter4j.examples.tweets.UpdateStatus [text]"); // System.exit(-1); // } String message = "Test5"; try { Twitter twitter = new TwitterFactory().getInstance(); try { // get request token. // this will throw IllegalStateException if access token is already available RequestToken requestToken = twitter.getOAuthRequestToken(); System.out.println("Got request token."); System.out.println("Request token: " + requestToken.getToken()); System.out.println("Request token secret: " + requestToken.getTokenSecret()); AccessToken accessToken = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { System.out.println("Open the following URL and grant access to your account:"); System.out.println(requestToken.getAuthorizationURL()); System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(requestToken); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } System.out.println("Got access token."); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Access token secret: " + accessToken.getTokenSecret()); } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is not set. if (!twitter.getAuthorization().isEnabled()) { System.out.println("OAuth consumer key/secret is not set."); System.exit(-1); } } //Status status = twitter.updateStatus(message); //System.out.println("Successfully updated the status to [" + status.getText() + "]."); AccountSettings as = twitter.getAccountSettings(); System.out.println("accountsettings:" + as.getScreenName()); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); System.exit(-1); } catch (IOException ioe) { ioe.printStackTrace(); System.out.println("Failed to read the system input."); System.exit(-1); } }
From source file:main.TokenManager.java
License:Open Source License
public void initialize() { // Log the user in twitter = new Twitter(); twitter.setOAuthConsumer(Global.MY_TOKEN, Global.MY_SECRET); String YN = "#"; String PIN = null;/* w ww .ja va 2 s . co m*/ if (readMyToken() == false) { RequestToken requestToken = null; try { requestToken = twitter.getOAuthRequestToken(); } catch (TwitterException e) { // TODO Auto-generated catch block System.out.println("Error in twitter.getOAuthRequestToken()"); } accessToken = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { System.out.println("Open the following URL and grant access to your account:"); System.out.println(requestToken.getAuthorizationURL()); System.out.print("Once you are done, type in the PIN code:"); try { PIN = br.readLine(); } catch (IOException e) { } try { accessToken = twitter.getOAuthAccessToken(requestToken, PIN); } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } username = accessToken.getScreenName(); System.out.print("Access granted. Do you want to save the token for future use? (Y/N) "); while (YN.charAt(0) != 'Y' && YN.charAt(0) != 'y' && YN.charAt(0) != 'N' && YN.charAt(0) != 'n') { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { YN = in.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } switch (YN.charAt(0)) { case 'Y': case 'y': try { storeAccessToken(twitter.verifyCredentials().getId(), accessToken); } catch (TwitterException e) { System.out.println("twitter.verifyCredentials().getId()"); } break; } } else { accessToken = new AccessToken(myToken, myTokenSecret); twitter.setOAuthAccessToken(accessToken); } }
From source file:net.catchpole.pimpmylight.twitter.TwitterClient.java
License:Apache License
private void accessTokens(String consumerKey, String secretKey) throws Exception { twitter.setOAuthConsumer(consumerKey, secretKey); RequestToken requestToken = twitter.getOAuthRequestToken(); System.out.println("Open the following URL..."); System.out.println(requestToken.getAuthorizationURL()); AccessToken accessToken = null;/*w ww . j a v a 2 s . c o m*/ while (null == accessToken) { String pin = JOptionPane.showInputDialog("PIN?"); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } System.out.println("token: " + accessToken.getToken()); System.out.println("secretToken: " + accessToken.getTokenSecret()); System.exit(0); }
From source file:net.chrissearle.flickrvote.service.cli.TwitterOAuthCLI.java
License:Apache License
public void authorize(String key, String secret) throws TwitterException, IOException { Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(key, secret); RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null;//from w w w. j a va 2 s . com BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { System.out.println("Open the following URL and grant access to your account:"); System.out.println(requestToken.getAuthorizationURL()); System.out.print("Enter the PIN(if available) or just hit enter.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(); } System.out.println("Token: " + accessToken.getToken()); System.out.println("TokenSecret: " + accessToken.getTokenSecret()); } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } }
From source file:onl.area51.a51li.twitter.TwitterAuth.java
License:Apache License
public static void main(String args[]) throws Exception { final String consumerKey = args[0]; final String consumerSecret = args[1]; // The factory instance is re-useable and thread safe. Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer(consumerKey, consumerSecret); RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null;/*from www.java 2s . c om*/ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { System.out.println("Open the following URL and grant access to your account:"); System.out.println(requestToken.getAuthorizationURL()); System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } //persist to the accessToken for future reference. storeAccessToken(twitter.verifyCredentials().getId(), accessToken); Status status = twitter.updateStatus(args[0]); System.out.println("Successfully updated the status to [" + status.getText() + "]."); System.exit(0); }
From source file:org.apache.nutch.protocol.http.api.HttpBase.java
License:Apache License
public ProtocolOutput getProtocolOutput(String url, WebPage page) { try {/*from w w w.j a v a2 s . c o m*/ host = null; response = null; contents = null; u = null; code = 0; c = null; if (url.indexOf("graph.facebook") > 0) { url = handleFaceBookContent(url); } else if (url.indexOf("api.twitter.com") > 0) { try { handleTwitterContent(url); } catch (TwitterException e) { e.printStackTrace(System.err); code = e.getStatusCode(); c = null; } } else { handleSiteContent(url, page); } // request if (code == 200) { // got a good response return new ProtocolOutput(c); // return it } else if (code == 410) { // page is gone return new ProtocolOutput(c, ProtocolStatusUtils.makeStatus(ProtocolStatusCodes.GONE, "Http: " + code + " url=" + url)); } else if (code >= 300 && code < 400) { // handle redirect String location = response.getHeader("Location"); // some broken servers, such as MS IIS, use lowercase header // name... if (location == null) location = response.getHeader("location"); if (location == null) location = ""; u = new URL(u, location); int protocolStatusCode; switch (code) { case 300: // multiple choices, preferred value in Location protocolStatusCode = ProtocolStatusCodes.MOVED; break; case 301: // moved permanently case 305: // use proxy (Location is URL of proxy) protocolStatusCode = ProtocolStatusCodes.MOVED; break; case 302: // found (temporarily moved) case 303: // see other (redirect after POST) case 307: // temporary redirect protocolStatusCode = ProtocolStatusUtils.TEMP_MOVED; break; case 304: // not modified protocolStatusCode = ProtocolStatusUtils.NOTMODIFIED; break; default: protocolStatusCode = ProtocolStatusUtils.MOVED; } // handle this in the higher layer. return new ProtocolOutput(c, ProtocolStatusUtils.makeStatus(protocolStatusCode, u)); } else if (code == 400) { // bad request, mark as GONE if (logger.isTraceEnabled()) { logger.trace("400 Bad request: " + u); } return new ProtocolOutput(c, ProtocolStatusUtils.makeStatus(ProtocolStatusCodes.GONE, u)); } else if (code == 401) { // requires authorization, but no valid // auth provided. if (logger.isTraceEnabled()) { logger.trace("401 Authentication Required"); } return new ProtocolOutput(c, ProtocolStatusUtils.makeStatus(ProtocolStatusCodes.ACCESS_DENIED, "Authentication required: " + url)); } else if (code == 404) { return new ProtocolOutput(c, ProtocolStatusUtils.makeStatus(ProtocolStatusCodes.NOTFOUND, u)); } else if (code == 410) { // permanently GONE return new ProtocolOutput(c, ProtocolStatusUtils.makeStatus(ProtocolStatusCodes.GONE, u)); } else { return new ProtocolOutput(c, ProtocolStatusUtils.makeStatus(ProtocolStatusCodes.EXCEPTION, "Http code=" + code + ", url=" + u)); } } catch (Throwable e) { e.printStackTrace(LogUtil.getErrorStream(logger)); return new ProtocolOutput(null, ProtocolStatusUtils.makeStatus(ProtocolStatusCodes.EXCEPTION, e.toString())); } }