List of usage examples for twitter4j TwitterException getStatusCode
public int getStatusCode()
From source file:org.gabrielebaldassarre.twitter.tweet.TalendFlowQueryResultBehaviour.java
License:Open Source License
/** * Perform a single twitter search and stores output in target {@link TalendFlow} * /*from w ww. j av a 2 s.c o m*/ * @throws RuntimeException if something went wrong during a search * @throws IllegalStateException if target flow was not visited before triggering the search * @throws IllegalStateException if no valid query object was passed to this visitor before triggering the search */ @SuppressWarnings("static-access") public void search() throws IllegalStateException { ResourceBundle rb = ResourceBundle.getBundle("tTwitterInput", Locale.getDefault()); if (valid == false) throw new IllegalStateException(rb.getString("exception.visitTargetBefore")); if (q == null) throw new IllegalStateException(rb.getString("exception.defineQueryBefore")); TalendRowFactory rowFactory = target.getModel().getRowFactory(); TalendRow current; List<Status> statusSet = null; int howMany = 0; try { qr = client.search(q); howMany = getLimit() - alreadyRetrieved() > qr.getTweets().size() ? qr.getTweets().size() : getLimit() - alreadyRetrieved(); current = rowFactory.newRow(target); Iterator<Entry<TalendColumn, QueryResultField>> i = associations.entrySet().iterator(); while (i.hasNext()) { Map.Entry<TalendColumn, QueryResultField> row = (Map.Entry<TalendColumn, QueryResultField>) i .next(); if (target != null && !row.getKey().getFlow().equals(target)) { throw new IllegalArgumentException(String.format(rb.getString("exception.columnNotInFlow"), row.getKey().getName(), target.getName())); } switch (row.getValue()) { case COMPLETED_IN: current.setValue(row.getKey(), qr.getCompletedIn()); break; case COUNT: current.setValue(row.getKey(), qr.getCount()); break; case HAS_NEXT: current.setValue(row.getKey(), qr.hasNext()); break; case MAX_ID: current.setValue(row.getKey(), qr.getMaxId()); break; case NEXT_QUERY: current.setValue(row.getKey(), qr.nextQuery()); break; case QUERY: current.setValue(row.getKey(), qr.getQuery()); break; case REFRESH_URL: current.setValue(row.getKey(), qr.getRefreshURL()); break; case SINCE_ID: current.setValue(row.getKey(), qr.getSinceId()); break; case STATUS_SET: statusSet = new ArrayList<Status>(getLimit() - alreadyRetrieved() < qr.getTweets().size() ? qr.getTweets().subList(0, getLimit() - alreadyRetrieved()) : qr.getTweets()); current.setValue(row.getKey(), statusSet); break; default: throw new IllegalArgumentException( String.format(rb.getString("exception.unparseableColumn"), row.getKey().getName())); } } } catch (TwitterException te) { try { switch (te.getStatusCode()) { case 503: /* Four seconds courtesy delay because of a fail whale */ setChanged(); notifyObservers(new TwitterLogger("USER_DEF_LOG", Thread.currentThread().getId(), "WARNING", String.format(Locale.getDefault(), rb.getString("log.failWhale"), 4))); Thread.currentThread().sleep(4000); break; case 420: /* Wait a safety-interval because of a rate limit */ case 429: setChanged(); notifyObservers(new TwitterLogger("USER_DEF_LOG", Thread.currentThread().getId(), "WARNING", String.format(Locale.getDefault(), rb.getString("log.rateLimit"), te.getRetryAfter()))); Thread.currentThread().sleep(te.getRetryAfter()); break; default: throw new RuntimeException(te); } } catch (InterruptedException e) { throw new RuntimeException(e); } } this.retrieved += (statusSet != null ? statusSet.size() : 0); setChanged(); notifyObservers(new TwitterLogger("USER_DEF_LOG", Thread.currentThread().getId(), "INFO", String.format(Locale.getDefault(), rb.getString("log.searchStatus"), qr.getCompletedIn(), howMany, alreadyRetrieved(), getLimit() - alreadyRetrieved()))); if (getLimit() - alreadyRetrieved() == 0 || qr.hasNext() == false) { setChanged(); notifyObservers(new TwitterLogger("USER_DEF_LOG", Thread.currentThread().getId(), "INFO", String.format(rb.getString("log.searchEnd"), alreadyRetrieved()))); } }
From source file:org.gatein.security.oauth.portlet.twitter.TwitterPortletRequest.java
License:Apache License
public T executeRequest() throws IOException, PortletException { try {/* ww w .j av a 2 s . c o m*/ return invokeRequest(); } catch (TwitterException te) { String jspErrorPage; if (te.getStatusCode() == 401) { request.setAttribute(OAuthPortletFilter.ATTRIBUTE_ERROR_MESSAGE, "Twitter access token is invalid."); request.setAttribute(OAuthPortletFilter.ATTRIBUTE_OAUTH_PROVIDER, oauthProvider); jspErrorPage = "/jsp/error/token.jsp"; } else { request.setAttribute(OAuthPortletFilter.ATTRIBUTE_ERROR_MESSAGE, getErrorMessage(te)); jspErrorPage = "/jsp/error/error.jsp"; } System.err.println(getErrorMessage(te)); PortletRequestDispatcher prd = portletContext.getRequestDispatcher(jspErrorPage); prd.include(request, response); } return null; }
From source file:org.gatein.security.oauth.portlet.twitter.TwitterPortletRequest.java
License:Apache License
private String getErrorMessage(TwitterException te) { String errorMessage = "Twitter error occured. StatusCode: " + te.getStatusCode() + ", Details: " + te.getMessage();//from w w w.j a v a2s. c om if (te.getCause() != null) { errorMessage = errorMessage + ", Cause: " + te.getCause(); } return errorMessage; }
From source file:org.gatein.security.oauth.twitter.TwitterProcessorImpl.java
License:Open Source License
@Override public TwitterAccessTokenContext validateTokenAndUpdateScopes(TwitterAccessTokenContext accessToken) throws OAuthException { try {//from w w w.j a v a2 s .co m // Perform validation by obtaining some info about user Twitter twitter = getAuthorizedTwitterInstance(accessToken); twitter.verifyCredentials(); return accessToken; } catch (TwitterException tw) { if (tw.getStatusCode() == 401) { throw new OAuthException(OAuthExceptionCode.ACCESS_TOKEN_ERROR, "Error when verifying twitter access token: " + tw.getMessage(), tw); } else { throw new OAuthException(OAuthExceptionCode.IO_ERROR, "IO Error when obtaining tokenInfo: " + tw.getClass() + ": " + tw.getMessage(), tw); } } }
From source file:org.getlantern.firetweet.util.Utils.java
License:Open Source License
public static HttpResponse getRedirectedHttpResponse(final HttpClientWrapper client, final String url, final String signUrl, final Authorization auth, final HashMap<String, List<String>> additionalHeaders) throws TwitterException { if (url == null) return null; final ArrayList<String> urls = new ArrayList<>(); urls.add(url);//from w w w. ja v a 2 s . com HttpResponse resp; try { resp = client.get(url, signUrl, auth, additionalHeaders); } catch (final TwitterException te) { Crashlytics.logException(te); if (isRedirected(te.getStatusCode())) { resp = te.getHttpResponse(); } else throw te; } while (resp != null && isRedirected(resp.getStatusCode())) { final String request_url = resp.getResponseHeader("Location"); if (request_url == null) return null; if (urls.contains(request_url)) throw new TwitterException("Too many redirects"); urls.add(request_url); try { resp = client.get(request_url, request_url, additionalHeaders); } catch (final TwitterException te) { Crashlytics.logException(te); if (isRedirected(te.getStatusCode())) { resp = te.getHttpResponse(); } else throw te; } } return resp; }
From source file:org.hornetq.integration.twitter.impl.OutgoingTweetsHandler.java
License:Apache License
public HandleStatus handle(final MessageReference ref) throws Exception { if (filter != null && !filter.match(ref.getMessage())) { return HandleStatus.NO_MATCH; }// w ww . j a v a 2 s . c o m synchronized (this) { ref.handled(); ServerMessage message = ref.getMessage(); StatusUpdate status = new StatusUpdate(message.getBodyBuffer().readString()); // set optional property if (message.containsProperty(TwitterConstants.KEY_IN_REPLY_TO_STATUS_ID)) { status.setInReplyToStatusId(message.getLongProperty(TwitterConstants.KEY_IN_REPLY_TO_STATUS_ID)); } if (message.containsProperty(TwitterConstants.KEY_GEO_LOCATION_LATITUDE)) { double geolat = message.getDoubleProperty(TwitterConstants.KEY_GEO_LOCATION_LATITUDE); double geolong = message.getDoubleProperty(TwitterConstants.KEY_GEO_LOCATION_LONGITUDE); status.setLocation(new GeoLocation(geolat, geolong)); } if (message.containsProperty(TwitterConstants.KEY_PLACE_ID)) { status.setPlaceId(message.getStringProperty(TwitterConstants.KEY_PLACE_ID)); } if (message.containsProperty(TwitterConstants.KEY_DISPLAY_COODINATES)) { status.setDisplayCoordinates(message.getBooleanProperty(TwitterConstants.KEY_DISPLAY_COODINATES)); } // send to Twitter try { this.twitter.updateStatus(status); } catch (TwitterException e) { if (e.getStatusCode() == 403) { // duplicated message HornetQTwitterLogger.LOGGER.error403(connectorName); queue.acknowledge(ref); return HandleStatus.HANDLED; } else { throw e; } } queue.acknowledge(ref); HornetQTwitterLogger.LOGGER.debug(connectorName + ": forwarded to twitter: " + message.getMessageID()); return HandleStatus.HANDLED; } }
From source file:org.luwrain.app.twitter.Auth.java
License:Open Source License
public static void main(String[] args) { if (args.length < 2) { System.err.println("You must provide consumer key and consumer secret"); return;//w w w. j a v a 2 s. c o m } Twitter twitter = null; try { ConfigurationLuwrain conf = new ConfigurationLuwrain(args[0], args[1], null, null); twitter = new TwitterFactory(conf).getInstance(); final 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 (accessToken == null) { 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 (te.getStatusCode() == 401) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } //while(); System.out.println("Got access token."); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Access token secret: " + accessToken.getTokenSecret()); } catch (IllegalStateException e) { if (!twitter.getAuthorization().isEnabled()) System.out.println("OAuth consumer key/secret is not set."); else e.printStackTrace(); } catch (TwitterException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.mariotaku.twidere.util.imageloader.TwidereImageDownloader.java
License:Open Source License
@Override protected InputStream getStreamFromNetwork(final String uriString, final Object extras) throws IOException { if (uriString == null) return null; final ParcelableMedia media = MediaPreviewUtils.getAllAvailableImage(uriString, mFullImage, mFullImage || !mFastImageLoading ? mClient : null); try {/*from w w w . j av a2s.co m*/ final String mediaUrl = media != null ? media.media_url : uriString; if (isTwitterProfileImage(uriString)) { final String replaced = getTwitterProfileImageOfSize(mediaUrl, mTwitterProfileImageSize); return getStreamFromNetworkInternal(replaced, extras); } else return getStreamFromNetworkInternal(mediaUrl, extras); } catch (final TwitterException e) { final int statusCode = e.getStatusCode(); if (statusCode != -1 && isTwitterProfileImage(uriString) && !uriString.contains("_normal.")) { try { return getStreamFromNetworkInternal(getNormalTwitterProfileImage(uriString), extras); } catch (final TwitterException ignored) { } } throw new IOException( String.format(Locale.US, "Error downloading image %s, error code: %d", uriString, statusCode)); } }
From source file:org.mariotaku.twidere.util.Utils.java
License:Open Source License
public static HttpResponse getRedirectedHttpResponse(final HttpClientWrapper client, final String url, final String signUrl, final Authorization auth, final HashMap<String, List<String>> additionalHeaders) throws TwitterException { if (url == null) return null; final ArrayList<String> urls = new ArrayList<>(); urls.add(url);//ww w .ja v a2s. c om HttpResponse resp; try { resp = client.get(url, signUrl, auth, additionalHeaders); } catch (final TwitterException te) { if (isRedirected(te.getStatusCode())) { resp = te.getHttpResponse(); } else throw te; } while (resp != null && isRedirected(resp.getStatusCode())) { final String request_url = resp.getResponseHeader("Location"); if (request_url == null) return null; if (urls.contains(request_url)) throw new TwitterException("Too many redirects"); urls.add(request_url); try { resp = client.get(request_url, request_url, additionalHeaders); } catch (final TwitterException te) { if (isRedirected(te.getStatusCode())) { resp = te.getHttpResponse(); } else throw te; } } return resp; }
From source file:org.n52.twitter.TwitterAccessTokenRetriever.java
License:Open Source License
public static void main(String args[]) throws Exception { String[] props = readProperties(); Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer(props[0], props[1]); RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null;// w w w .j a v a2 s .c om BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { LOGGER.info("Open the following URL and grant access to your account:"); LOGGER.info(requestToken.getAuthorizationURL()); LOGGER.info("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()) { LOGGER.error("Unable to get the access token."); } else { LOGGER.error(te.getErrorMessage(), te); } } } storeAccessToken(accessToken.getToken(), accessToken.getTokenSecret()); }