List of usage examples for twitter4j TwitterException TwitterException
public TwitterException(Exception cause)
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);/* w ww. j a v a 2s. co m*/ 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.hfoss.posit.android.functionplugin.twitter.TwitFindsActivity.java
License:Open Source License
/** * Send a tweet based on tweetString. /*from ww w .ja va 2 s . c o m*/ */ private void tweetMessage() { try { for (String message : formMessages(tweetString)) { if (message.length() == 0) { throw new TwitterException("Tweet Message Empty"); } mTwitter.updateStatus(message); } Toast.makeText(this, "Tweet Successful!", Toast.LENGTH_SHORT).show(); } catch (TwitterException e) { Toast.makeText(this, "Tweet error, try again later", Toast.LENGTH_SHORT).show(); } }
From source file:org.hfoss.posit.android.functionplugin.twitter.TwitFindsActivity.java
License:Open Source License
/** * Given a string message, the function breaks it up into messages. It looks for spaces to divide up the message. * The function returns an string array where each index does not contain more then 140 characters. * /*from w w w . j a v a2s .c o m*/ * @param data string array where each index does not contain more then 140 characters. * @return */ private String[] formMessages(String data) throws TwitterException { StringTokenizer tokenize = new StringTokenizer(data, " ", true); ArrayList<String> results = new ArrayList<String>(); StringBuffer result = new StringBuffer(); String next = ""; while (tokenize.hasMoreTokens()) { next = tokenize.nextToken(); // If the current message + the next token is too long, then save the current message in its own individual message. if (result.length() + next.length() > 140) { results.add(result.toString()); result = new StringBuffer(); } // If the current message is already saved, and the token is still too long, then we must subdivide the token. if (result.length() == 0 && next.length() > 140) { // If the token is just way too long, then we must stop. Else we might end up with thousands of messages. if (next.length() > 5 * 140) { throw new TwitterException("Twitter message Too Long"); } // Assert: the token is not too long. Subdivide the token into pieces of 140 characters. for (int i = 0; i < next.length(); i = i + 140) { if (next.length() > i + 140) { results.add(next.substring(i, i + 140)); } else { results.add(next.substring(i)); } } } else { result.append(next); } } results.add(result.toString()); return results.toArray(new String[results.size()]); }
From source file:org.mariotaku.twidere.loader.support.Twitter4JStatusesLoader.java
License:Open Source License
@SuppressWarnings("unchecked") @Override//from w ww .ja v a 2 s .c o m public final List<ParcelableStatus> loadInBackground() { final File serializationFile = getSerializationFile(); final List<ParcelableStatus> data = getData(); if (isFirstLoad() && getTabPosition() >= 0 && serializationFile != null) { final List<ParcelableStatus> cached = getCachedData(serializationFile); if (cached != null) { data.addAll(cached); if (mComparator != null) { Collections.sort(data, mComparator); } else { Collections.sort(data); } return new CopyOnWriteArrayList<>(data); } } if (!isFromUser()) return data; final List<Status> statuses; final boolean truncated; final Context context = getContext(); final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); final int loadItemLimit = prefs.getInt(KEY_LOAD_ITEM_LIMIT, DEFAULT_LOAD_ITEM_LIMIT); try { final Paging paging = new Paging(); paging.setCount(loadItemLimit); if (mMaxId > 0) { paging.setMaxId(mMaxId); } if (mSinceId > 0) { paging.setSinceId(mSinceId - 1); } statuses = new ArrayList<>(); final Twitter twitter = getTwitter(); if (twitter == null) { throw new TwitterException("Account is null"); } truncated = truncateStatuses(getStatuses(twitter, paging), statuses, mSinceId); } catch (final TwitterException e) { // mHandler.post(new ShowErrorRunnable(e)); Log.w(LOGTAG, e); return new CopyOnWriteArrayList<>(data); } final long minStatusId = statuses.isEmpty() ? -1 : Collections.min(statuses).getId(); final boolean insertGap = minStatusId > 0 && statuses.size() > 1 && !data.isEmpty() && !truncated; mHandler.post(CacheUsersStatusesTask.getRunnable(context, new StatusListResponse(mAccountId, statuses))); for (final Status status : statuses) { final long id = status.getId(); final boolean deleted = deleteStatus(data, id); data.add(new ParcelableStatus(status, mAccountId, minStatusId == id && insertGap && !deleted)); } final ParcelableStatus[] array = data.toArray(new ParcelableStatus[data.size()]); for (int i = 0, size = array.length; i < size; i++) { final ParcelableStatus status = array[i]; if (shouldFilterStatus(mDatabase, status) && !status.is_gap && i != size - 1) { deleteStatus(data, status.id); } } if (mComparator != null) { Collections.sort(data, mComparator); } else { Collections.sort(data); } saveCachedData(serializationFile, data); return new CopyOnWriteArrayList<>(data); }
From source file:org.mariotaku.twidere.util.httpclient.HttpClientImpl.java
License:Apache License
@Override public twitter4j.http.HttpResponse request(final twitter4j.http.HttpRequest req) throws TwitterException { try {//from w ww .j a va 2 s .c o m HttpRequestBase commonsRequest; final HostAddressResolver resolver = conf.getHostAddressResolver(); final String url_string = req.getURL(); final URI url_orig; try { url_orig = new URI(url_string); } catch (final URISyntaxException e) { throw new TwitterException(e); } final String host = url_orig.getHost(); final String resolved_host = resolver != null ? resolver.resolve(host) : null; final String resolved_url = !isEmpty(resolved_host) ? url_string.replace("://" + host, "://" + resolved_host) : url_string; if (req.getMethod() == RequestMethod.GET) { commonsRequest = new HttpGet(resolved_url); } else if (req.getMethod() == RequestMethod.POST) { final HttpPost post = new HttpPost(resolved_url); // parameter has a file? boolean hasFile = false; final HttpParameter[] params = req.getParameters(); if (params != null) { for (final HttpParameter parameter : params) { if (parameter.isFile()) { hasFile = true; break; } } if (!hasFile) { if (params.length > 0) { post.setEntity(new UrlEncodedFormEntity(params)); } } else { final MultipartEntity me = new MultipartEntity(); for (final HttpParameter parameter : params) { if (parameter.isFile()) { final ContentBody body = new FileBody(parameter.getFile(), parameter.getContentType()); me.addPart(parameter.getName(), body); } else { final ContentBody body = new StringBody(parameter.getValue(), "text/plain; charset=UTF-8", Charset.forName("UTF-8")); me.addPart(parameter.getName(), body); } } post.setEntity(me); } } post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); commonsRequest = post; } else if (req.getMethod() == RequestMethod.DELETE) { commonsRequest = new HttpDelete(resolved_url); } else if (req.getMethod() == RequestMethod.HEAD) { commonsRequest = new HttpHead(resolved_url); } else if (req.getMethod() == RequestMethod.PUT) { commonsRequest = new HttpPut(resolved_url); } else throw new TwitterException("Unsupported request method " + req.getMethod()); final Map<String, String> headers = req.getRequestHeaders(); for (final String headerName : headers.keySet()) { commonsRequest.addHeader(headerName, headers.get(headerName)); } String authorizationHeader; if (req.getAuthorization() != null && (authorizationHeader = req.getAuthorization().getAuthorizationHeader(req)) != null) { commonsRequest.addHeader("Authorization", authorizationHeader); } if (!isEmpty(resolved_host) && !resolved_host.equals(host)) { commonsRequest.addHeader("Host", host); } final ApacheHttpClientHttpResponseImpl res; try { res = new ApacheHttpClientHttpResponseImpl(client.execute(commonsRequest), conf); } catch (final IllegalStateException e) { throw new TwitterException("Please check your API settings.", e); } catch (final NullPointerException e) { // Bug http://code.google.com/p/android/issues/detail?id=5255 throw new TwitterException("Please check your APN settings, make sure not to use WAP APNs.", e); } catch (final OutOfMemoryError e) { // I don't know why OOM thown, but it should be catched. System.gc(); throw new TwitterException("Unknown error", e); } final int statusCode = res.getStatusCode(); if (statusCode < OK || statusCode > ACCEPTED) throw new TwitterException(res.asString(), req, res); return res; } catch (final IOException e) { throw new TwitterException(e); } }
From source file:org.mariotaku.twidere.util.net.HttpClientImpl.java
License:Apache License
@Override public twitter4j.http.HttpResponse request(final twitter4j.http.HttpRequest req) throws TwitterException { try {/*from w ww . j a v a2 s. c om*/ HttpRequestBase commonsRequest; final HostAddressResolver resolver = conf.getHostAddressResolver(); final String urlString = req.getURL(); final URI urlOrig; try { urlOrig = new URI(urlString); } catch (final URISyntaxException e) { throw new TwitterException(e); } final String host = urlOrig.getHost(), authority = urlOrig.getAuthority(); final String resolvedHost = resolver != null ? resolver.resolve(host) : null; final String resolvedUrl = !isEmpty(resolvedHost) ? urlString.replace("://" + host, "://" + resolvedHost) : urlString; final RequestMethod method = req.getMethod(); if (method == RequestMethod.GET) { commonsRequest = new HttpGet(resolvedUrl); } else if (method == RequestMethod.POST) { final HttpPost post = new HttpPost(resolvedUrl); // parameter has a file? boolean hasFile = false; final HttpParameter[] params = req.getParameters(); if (params != null) { for (final HttpParameter param : params) { if (param.isFile()) { hasFile = true; break; } } if (!hasFile) { if (params.length > 0) { post.setEntity(new UrlEncodedFormEntity(params)); } } else { final MultipartEntity me = new MultipartEntity(); for (final HttpParameter param : params) { if (param.isFile()) { final ContentBody body; if (param.getFile() != null) { body = new FileBody(param.getFile(), param.getContentType()); } else { body = new InputStreamBody(param.getFileBody(), param.getFileName(), param.getContentType()); } me.addPart(param.getName(), body); } else { final ContentBody body = new StringBody(param.getValue(), "text/plain; charset=UTF-8", Charset.forName("UTF-8")); me.addPart(param.getName(), body); } } post.setEntity(me); } } post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); commonsRequest = post; } else if (method == RequestMethod.DELETE) { commonsRequest = new HttpDelete(resolvedUrl); } else if (method == RequestMethod.HEAD) { commonsRequest = new HttpHead(resolvedUrl); } else if (method == RequestMethod.PUT) { commonsRequest = new HttpPut(resolvedUrl); } else throw new TwitterException("Unsupported request method " + method); final Map<String, String> headers = req.getRequestHeaders(); for (final String headerName : headers.keySet()) { commonsRequest.addHeader(headerName, headers.get(headerName)); } final Authorization authorization = req.getAuthorization(); final String authorizationHeader = authorization != null ? authorization.getAuthorizationHeader(req) : null; if (authorizationHeader != null) { commonsRequest.addHeader("Authorization", authorizationHeader); } if (resolvedHost != null && !resolvedHost.isEmpty() && !resolvedHost.equals(host)) { commonsRequest.addHeader("Host", authority); } final ApacheHttpClientHttpResponseImpl res; try { res = new ApacheHttpClientHttpResponseImpl(client.execute(commonsRequest), conf); } catch (final IllegalStateException e) { throw new TwitterException("Please check your API settings.", e); } catch (final NullPointerException e) { // Bug http://code.google.com/p/android/issues/detail?id=5255 throw new TwitterException("Please check your APN settings, make sure not to use WAP APNs.", e); } catch (final OutOfMemoryError e) { // I don't know why OOM thown, but it should be catched. System.gc(); throw new TwitterException("Unknown error", e); } final int statusCode = res.getStatusCode(); if (statusCode < OK || statusCode > ACCEPTED) throw new TwitterException(res.asString(), req, res); return res; } catch (final IOException e) { throw new TwitterException(e); } }
From source file:org.mariotaku.twidere.util.net.OkHttpClientImpl.java
License:Open Source License
@Override public HttpResponse request(HttpRequest req) throws TwitterException { final Builder builder = new Builder(); for (Entry<String, List<String>> headerEntry : req.getRequestHeaders().entrySet()) { final String name = headerEntry.getKey(); for (String value : headerEntry.getValue()) { builder.addHeader(name, value); }/* w w w . j a v a 2s . c o m*/ } final Authorization authorization = req.getAuthorization(); if (authorization != null) { final String authHeader = authorization.getAuthorizationHeader(req); if (authHeader != null) { builder.header("Authorization", authHeader); } } Response response = null; try { setupRequestBuilder(builder, req); response = client.newCall(builder.build()).execute(); return new OkHttpResponse(conf, null, response); } catch (IOException e) { throw new TwitterException(e); } }
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 . j a va2s .co m 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.mule.twitter.MuleHttpResponse.java
License:Open Source License
public MuleHttpResponse(HttpClientConfiguration conf, MuleMessage response) throws TwitterException { super(conf);/*from w w w . j ava2 s . c o m*/ this.response = response; try { this.is = response.getPayload(InputStream.class); } catch (TransformerException e) { throw new TwitterException(e); } }
From source file:org.mule.twitter.TwitterConnector.java
License:Open Source License
/** * Updates the authenticating user's status. A status update with text identical * to the authenticating user's text identical to the authenticating user's * current status will be ignored to prevent duplicates. <br> * This method calls http://api.twitter.com/1.1/statuses/update * <p/>//w ww . ja va 2 s .co m * {@sample.xml ../../../doc/twitter-connector.xml.sample twitter:updateStatus} * * @param status the text of your status update * @param inReplyTo The ID of an existing status that the update is in reply to. * @param latitude The latitude of the location this tweet refers to. This parameter will be ignored unless it is * inside the range -90.0 to +90.0 (North is positive) inclusive. * @param longitude he longitude of the location this tweet refers to. The valid ranges for longitude is -180.0 to * +180.0 (East is positive) inclusive. This parameter will be ignored if outside that range or if there not a * corresponding lat parameter. * @return the latest {@link Status} * @throws TwitterException when Twitter service or network is unavailable * @see <a href="http://dev.twitter.com/doc/post/statuses/update">POST * statuses/update | dev.twitter.com</a> */ @Processor public Status updateStatus(String status, @Default(value = "-1") @Optional long inReplyTo, @Placement(group = "Coordinates") @Optional Double latitude, @Placement(group = "Coordinates") @Optional Double longitude) throws TwitterException { StatusUpdate update = new StatusUpdate(status); if (inReplyTo > 0) { update.setInReplyToStatusId(inReplyTo); } if (latitude != null && longitude != null) { update.setLocation(new GeoLocation(latitude, longitude)); } Status response = twitter.updateStatus(update); //Twitter4j doesn't throw exception when json reponse has 'error: Could not authenticate with OAuth' if (response.getId() == -1) { throw new TwitterException("Could not authenticate with OAuth\n"); } return response; }