List of usage examples for java.lang StringBuffer length
@Override public synchronized int length()
From source file:com.example.android.ennis.barrett.popularmovies.asynchronous.TMDbSyncUtil.java
/** * makes the network call to fetch the data and the calls storeJsonMovies * @param type Flag for the try of movie to fetch. * @return Returns an array of ids of the movies that were inserted *///from w w w .j a v a 2s .co m public static int[] fetchMovies(int type, Context context) { int[] ids = {}; HttpURLConnection connection = null; BufferedReader reader = null; String rawJSON = null; String MOVIE_BASE_URL = "http://api.themoviedb.org/3/movie"; final String API_KEY_PARAM = "api_key"; /* example urls http://api.themoviedb.org/3/movie/top_rated?api_key=xxxxxxx http://api.themoviedb.org/3/movie/popular?api_key=xxxxxxxx */ //TODO build Uri programmatically using APIs switch (type) { case MOVIES_POPULAR: MOVIE_BASE_URL += "/popular" + "?"; break; case MOVIES_TOP_RATED: MOVIE_BASE_URL += "/top_rated" + "?"; break; default: throw new IllegalArgumentException( "Unrecognized id passed as params[0]. Params[0] must be the id for the url. See static constants of this class"); } try { Uri droidUri = Uri.parse(MOVIE_BASE_URL).buildUpon() .appendQueryParameter(API_KEY_PARAM, BuildConfig.TMDb_API_KEY).build(); Log.v(TAG, "URL used: " + droidUri.toString()); URL url = new URL(droidUri.toString()); //java.net Malformed uri exception connection = (HttpURLConnection) url.openConnection(); //java.io. IO exception connection.setRequestMethod("GET"); //java.net.ProtocolException && unnecessary connection.connect(); //java.io.IOExecption InputStream inputStream = connection.getInputStream(); // java.io.IOException StringBuffer stringBuffer = new StringBuffer(); if (inputStream == null) { return ids; } reader = new BufferedReader(new InputStreamReader(inputStream)); //Make the string more readable String line; while ((line = reader.readLine()) != null) { stringBuffer.append(line + "\n"); } if (stringBuffer.length() == 0) { Log.e(TAG + "doInBackground", "empty string"); return ids; } rawJSON = stringBuffer.toString(); Log.d(TAG + "doInBackground", rawJSON); switch (type) { case MOVIES_POPULAR: ids = storeJsonMovies(rawJSON.toString(), type, context); break; case MOVIES_TOP_RATED: ids = storeJsonMovies(rawJSON.toString(), type, context); break; } } catch (IOException e) { Log.e(TAG, "Error ", e); e.printStackTrace(); } catch (JSONException e) { Log.e(TAG, e.getMessage(), e); e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(TAG, "Error closing stream", e); e.printStackTrace(); } } } return ids; }
From source file:com.vmware.bdd.utils.CommonUtil.java
public static <K, V> String inputsConvert(Map<K, V> wordsMap) { StringBuffer wordsBuff = new StringBuffer(); if (wordsMap != null && !wordsMap.isEmpty()) { for (Entry<K, V> entry : wordsMap.entrySet()) { wordsBuff.append(entry.getKey()).append(":").append(entry.getValue()).append(","); }//from w w w .ja va2 s .co m wordsBuff.delete(wordsBuff.length() - 1, wordsBuff.length()); } return wordsBuff.toString(); }
From source file:gov.jgi.meta.MetaUtils.java
/** * generate a set (unique) of all sequences ({ATGC} only) from start sequence * to distance steps (Hamming distance)//from w w w.ja va 2 s . c om * * @param start the start sequence * @param distance the number of steps to travel * @return s set containing all neighbors including itself. */ public static Set<String> generateAllNeighbors(StringBuffer start, int distance) { char[] bases = { 'a', 't', 'g', 'c' }; Set<String> s = new HashSet<String>(); if (distance == 0) { s.add(start.toString()); return (s); } for (int i = 0; i < start.length(); i++) { char old = start.charAt(i); for (char basePair : bases) { start.setCharAt(i, basePair); s.addAll(generateAllNeighbors(start, distance - 1)); } start.setCharAt(i, old); } return (s); }
From source file:hu.qgears.xtextdoc.util.EscapeString.java
/** * <p>// w ww .jav a 2s . c om * Unescapes any Java literals found in the <code>String</code> to a * <code>Writer</code>. * </p> * * <p> * For example, it will turn a sequence of <code>'\'</code> and <code>'n'</code> into * a newline character, unless the <code>'\'</code> is preceded by another <code>'\'</code>. * </p> * * <p> * A <code>null</code> string input has no effect. * </p> * * @param out * the <code>Writer</code> used to output unescaped characters * @param str * the <code>String</code> to unescape, may be null * @throws IllegalArgumentException * if the Writer is <code>null</code> * @throws IOException * if error occurs on underlying Writer */ public static void unescapeJava(Writer out, String str) throws IOException { if (out == null) { throw new IllegalArgumentException("The Writer must not be null"); } if (str == null) { return; } int sz = str.length(); StringBuffer unicode = new StringBuffer(4); boolean hadSlash = false; boolean inUnicode = false; for (int i = 0; i < sz; i++) { char ch = str.charAt(i); if (inUnicode) { // if in unicode, then we're reading unicode // values in somehow unicode.append(ch); if (unicode.length() == 4) { // unicode now contains the four hex digits // which represents our unicode character try { int value = Integer.parseInt(unicode.toString(), 16); out.write((char) value); unicode.setLength(0); inUnicode = false; hadSlash = false; } catch (NumberFormatException nfe) { throw new RuntimeException("Unable to parse unicode value: " + unicode, nfe); } } continue; } if (hadSlash) { // handle an escaped value hadSlash = false; switch (ch) { case '\\': out.write('\\'); break; case '\'': out.write('\''); break; case '\"': out.write('"'); break; case 'r': out.write('\r'); break; case 'f': out.write('\f'); break; case 't': out.write('\t'); break; case 'n': out.write('\n'); break; case 'b': out.write('\b'); break; case 'u': { // uh-oh, we're in unicode country.... inUnicode = true; break; } default: out.write(ch); break; } continue; } else if (ch == '\\') { hadSlash = true; continue; } out.write(ch); } if (hadSlash) { // then we're in the weird case of a \ at the end of the // string, let's output it anyway. out.write('\\'); } }
From source file:StringUtils.java
/** * Parse collection of objects to String by calling toString on each element. * //ww w. j a v a 2 s .c om * @param colObjects - * collection of data objects to parse * @param strDel - * String deliminer * @return String - parsed array */ public static String parseCollectionToString(Collection colObjects, String strDel) { StringBuffer strbInts = new StringBuffer(); if ((colObjects != null) && (!colObjects.isEmpty())) { for (Iterator items = colObjects.iterator(); items.hasNext();) { if (strbInts.length() > 0) { strbInts.append(strDel); } strbInts.append(items.next().toString()); } } return strbInts.toString(); }
From source file:org.mwc.debrief.editable.test.EditableTests.java
public static void waitForJobs(long maxIdle) { long start = System.currentTimeMillis(); while (!Job.getJobManager().isIdle()) { delay(1000);//ww w. j av a 2s.co m if ((System.currentTimeMillis() - start) > maxIdle) { Job[] jobs = Job.getJobManager().find(null); StringBuffer buffer = new StringBuffer(); for (Job job : jobs) { if (job.getThread() != null) { buffer.append(job.getName()).append(" (").append(job.getClass()).append(")\n"); } } if (buffer.length() > 0) throw new RuntimeException("Invalid jobs found:" + buffer.toString()); //$NON-NLS-1$ } } }
From source file:Util.java
public static String dateToIsoDateTime(String date) { StringBuffer sb = new StringBuffer(date); if (date.length() >= 8) { //20070101 -> 2007-01-01 //insert hyphens between year, month, and day sb.insert(4, '-'); sb.insert(7, '-'); //2007-01-01T173012 -> 2007-01-01T17:30:12 if (date.length() >= 15) { //insert colons between hours, minutes, and seconds sb.insert(13, ':'); sb.insert(16, ':'); //2007-01-01T17:30:12 -> 2007-01-01T17:30:12.000 //append milliseconds if (sb.toString().length() > 19) sb.insert(20, ".000"); else// w w w . j ava 2 s .c o m sb.append(".000"); //2007-01-01T17:30:12.000 -> 2007-01-01T17:30:12.000Z //append UTC indicator if exists if (date.length() > 15 && date.charAt(15) == 'Z') sb.append('Z'); } if (sb.length() > 19) sb.setLength(19); } return sb.toString(); }
From source file:cn.kk.exia.MangaDownloader.java
public static final boolean appendCookies(final StringBuffer cookies, final HttpURLConnection conn) throws IOException { try {//ww w.j av a2 s . co m boolean changed = false; final List<String> values = conn.getHeaderFields().get("Set-Cookie"); if (values != null) { for (final String v : values) { if (v.indexOf("deleted") == -1) { if (cookies.length() > 0) { cookies.append("; "); } cookies.append(v.split(";")[0]); changed = true; } } } return changed; } catch (final Throwable e) { throw new IOException(e); } }
From source file:com.concursive.connect.web.modules.search.utils.SearchUtils.java
/** * Description of the Method//from w ww . j av a 2s .co m * * @param searchText Description of the Parameter * @return Description of the Return Value */ public static ArrayList<String> parseSearchTerms(String searchText) { ArrayList<String> terms = new ArrayList<String>(); StringBuffer sb = new StringBuffer(); boolean returnTokens = true; String currentDelims = WHITESPACE_AND_QUOTES; StringTokenizer parser = new StringTokenizer(searchText, currentDelims, returnTokens); String token = null; while (parser.hasMoreTokens()) { token = parser.nextToken(currentDelims); if (!isDoubleQuote(token)) { if (hasText(token)) { String gotToken = token.trim().toLowerCase(); if ("and".equals(gotToken) || "or".equals(gotToken) || "not".equals(gotToken)) { } else { if (sb.length() > 0) { sb.append(" "); } sb.append(gotToken); terms.add(sb.toString()); sb.setLength(0); } } } else { currentDelims = flipDelimiters(currentDelims); } } return terms; }
From source file:org.hdiv.util.HDIVUtil.java
/** * Strips a servlet session ID from <tt>url</tt>. The session ID is encoded as a URL "path parameter" beginning with * "jsessionid=". We thus remove anything we find between ";jsessionid=" (inclusive) and either EOS or a subsequent * ';' (exclusive)./*w w w . j ava2 s . c o m*/ * * @param url * url * @return url without sessionId */ public static String stripSession(String url) { if (log.isDebugEnabled()) { log.debug("Stripping jsessionid from url " + url); } StringBuffer u = new StringBuffer(url); int sessionStart; while (((sessionStart = u.toString().indexOf(";jsessionid=")) != -1) || ((sessionStart = u.toString().indexOf(";JSESSIONID=")) != -1)) { int sessionEnd = u.toString().indexOf(";", sessionStart + 1); if (sessionEnd == -1) { sessionEnd = u.toString().indexOf("?", sessionStart + 1); } if (sessionEnd == -1) { // still sessionEnd = u.length(); } u.delete(sessionStart, sessionEnd); } return u.toString(); }