@Override public void saveConfig() { String str = this.getConfig().saveToString(); StringBuilder sb = new StringBuilder(str); sb.insert( sb.indexOf("\nversion:") + 1, "\n# Configuration version used during upgrade. Do not change.\n"); sb.insert( sb.indexOf("\nmute_minutes") + 1, "\n# The default number of minutes a player will remain muted.\n"); sb.insert( sb.indexOf("\nprotect_boats") + 1, "\n# When true, protects boats from breakage unless deliberately broken.\n"); final File cfg_file = new File(this.getDataFolder(), "config.yml"); final String cfg_str = sb.toString(); final Logger logger = this.getLogger(); new BukkitRunnable() { @Override public void run() { cfg_file.delete(); try (PrintWriter writer = new PrintWriter(cfg_file, "UTF-8")) { cfg_file.createNewFile(); writer.write(cfg_str); writer.close(); } catch (IOException ex) { logger.severe("Error saving configuration!"); } } }.runTaskAsynchronously(this); }
private String getSegment() { String segment = null; int pos = m_sb.indexOf(SEPARATOR); int sl = SEPARATOR.length(); if (pos > 0 && pos + sl < m_sb.length() && m_sb.charAt(pos + sl) == '\r') { sl++; } if (pos > 0 && pos + sl < m_sb.length() && m_sb.charAt(pos + sl) == '\n') { sl++; } if (pos >= 0) { segment = m_sb.substring(0, pos); m_sb.delete(0, pos + sl); } else { pos = m_sb.indexOf(TERMINATOR); if (pos >= 0) { m_last = true; segment = m_sb.substring(0, pos); } } return segment; }
private static void mapLines( TextBuffer code, StructLineNumberTableAttribute table, BytecodeMappingTracer tracer, int startLine) { // build line start offsets map HashMap<Integer, Set<Integer>> lineStartOffsets = new HashMap<Integer, Set<Integer>>(); for (Map.Entry<Integer, Integer> entry : tracer.getMapping().entrySet()) { Integer lineNumber = entry.getValue() - startLine; Set<Integer> curr = lineStartOffsets.get(lineNumber); if (curr == null) { curr = new TreeSet<Integer>(); // requires natural sorting! } curr.add(entry.getKey()); lineStartOffsets.put(lineNumber, curr); } String lineSeparator = DecompilerContext.getNewLineSeparator(); StringBuilder text = code.getOriginalText(); int pos = text.indexOf(lineSeparator); int lineNumber = 0; while (pos != -1) { Set<Integer> startOffsets = lineStartOffsets.get(lineNumber); if (startOffsets != null) { for (Integer offset : startOffsets) { int number = table.findLineNumber(offset); if (number >= 0) { code.setLineMapping(number, pos); break; } } } pos = text.indexOf(lineSeparator, pos + 1); lineNumber++; } }
public static URL container(String resource, ClassLoader cl) { final URL resUrl = cl.getResource(resource); if (resUrl == null) { throw new IllegalArgumentException("Resource not found: " + resource); } final StringBuilder url = new StringBuilder(resUrl.toExternalForm()); try { if ("jar".equalsIgnoreCase(resUrl.getProtocol())) { url.delete(0, 4).delete(url.indexOf(resource) - 2, url.length()); } else if ("file".equalsIgnoreCase(resUrl.getProtocol())) { url.delete(url.indexOf(resource), url.length()); } else { throw new UnsupportedOperationException( "Cannot get container for resource [" + resource + "]. Unsupported URL protocol [" + resUrl.getProtocol() + "]."); } return new URL(url.toString()); } catch (MalformedURLException e) { throw new UnsupportedOperationException( "Cannot get container for resource [" + resource + "]. Malformed URL [" + url + "]."); } }
public static StringBuilder replaceAll(StringBuilder in, String p, String r) { int pl = p.length(), rl = r.length(), s = in.indexOf(p, 0); if (pl == 0) return in; while (s >= 0) { in.replace(s, s + pl, r); s = in.indexOf(p, s + rl); } return in; }
public void searchTags() { StringBuilder strTags = new StringBuilder(); for (int i = 0; i < tempStrBuilder.length() - 1; i++) { i = tempStrBuilder.indexOf("<"); if (i == -1) { break; } strTags.append(tempStrBuilder.substring(i, tempStrBuilder.indexOf(">") + 1)); tempStrBuilder.delete(i, tempStrBuilder.indexOf(">") + 1); tags.add(strTags.toString()); strTags.delete(0, strTags.length()); } }
/** * @param str The string to find the replacements for. * @param fromIndex The index from which replacements are found. * @param level The recursion level. The search stops if level is > MAX_RECURSION_LEVEL. * @return A list of all possible replacements of a {#link str} given string */ public List<String> getAllReplacements(final String str, final int fromIndex, final int level) { List<String> replaced = new ArrayList<>(); if (level > MAX_RECURSION_LEVEL) { // Stop searching at some point replaced.add(str); return replaced; } StringBuilder sb = new StringBuilder(); sb.append(str); int index = MAX_WORD_LENGTH; String key = ""; int keyLength = 0; boolean found = false; // find first possible replacement after fromIndex position for (final String auxKey : replacementsTheRest.keySet()) { int auxIndex = sb.indexOf(auxKey, fromIndex); if (auxIndex > -1 && (auxIndex < index || (auxIndex == index && !(auxKey.length() < keyLength)))) { // select the longest possible key index = auxIndex; key = auxKey; keyLength = auxKey.length(); } } if (index < MAX_WORD_LENGTH) { for (final String rep : replacementsTheRest.get(key)) { // start a branch without replacement (only once per key) if (!found) { replaced.addAll(getAllReplacements(str, index + key.length(), level + 1)); found = true; } // avoid unnecessary replacements (ex. don't replace L by L·L when L·L already present) int ind = sb.indexOf(rep, fromIndex - rep.length() + 1); if (rep.length() > key.length() && ind > -1 && (ind == index || ind == index - rep.length() + 1)) { continue; } // start a branch with replacement sb.replace(index, index + key.length(), rep); replaced.addAll(getAllReplacements(sb.toString(), index + rep.length(), level + 1)); sb.setLength(0); sb.append(str); } } if (!found) { replaced.add(sb.toString()); } return replaced; }
private LimitType limitQuery( String limitPattern, LimitType limitType, String queryString, StringBuilder queryResult, Integer firstResult, Integer maxResults) { if (limitPattern == null) return null; int ix = limitPattern.indexOf("$S"); if (ix >= 0) { limitType.afterSql = limitPattern.indexOf("$", ix + 1) > 0; queryResult.append(limitPattern.substring(0, ix)); queryResult.append(queryString); queryResult.append(limitPattern.substring(ix + 2)); } else { ix = limitPattern.indexOf("$s"); if (ix >= 0) { limitType.afterSql = limitPattern.indexOf("$", ix + 1) > 0; int ix2 = queryString.toLowerCase().indexOf("select"); if (ix2 < 0) return null; queryResult.append(limitPattern.substring(0, ix)); queryResult.append(queryString.substring(ix2 + 6)); queryResult.append(limitPattern.substring(ix + 2)); } else { return null; } } if (limitType.alsoFirst) { ix = queryResult.indexOf("$F"); if (ix >= 0) { if (queryResult.indexOf("$m", ix) < 0 && queryResult.indexOf("$M", ix) < 0) limitType.maxBeforeFirst = true; queryResult.replace(ix, ix + 2, "?"); } else { ix = queryResult.indexOf("$f"); if (ix >= 0) { limitType.zeroBasedFirst = true; if (queryResult.indexOf("$m", ix) < 0 && queryResult.indexOf("$M", ix) < 0) limitType.maxBeforeFirst = true; queryResult.replace(ix, ix + 2, "?"); } else { return null; } } } ix = queryResult.indexOf("$M"); if (ix >= 0) { queryResult.replace(ix, ix + 2, "?"); } else { ix = queryResult.indexOf("$m"); if (ix >= 0) { limitType.rowidBasedMax = true; queryResult.replace(ix, ix + 2, "?"); } else { return null; } } return limitType; }
private String getTag(Document d) { StringBuilder ab = new StringBuilder( d.getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0].replace( "E:\\I:\\ACM_complete_dataset\\", "")); return ab.substring(0, ab.indexOf("\\")).toString(); }
/** * Construct a URL from its basic parts. * * @param base The base URL. * @param url The URL that was found on the base URL's page. * @param stripRef True if the URL's reference should be stripped. * @return The new URL, built upon the base URL. * @throws IOException Thrown if any IO error occurs. */ public static URL constructURL(final URL base, final String url, final boolean stripRef) throws IOException { URL result = new URL(base, url); String file = result.getFile(); final String protocol = result.getProtocol(); final String host = result.getHost(); final int port = result.getPort(); final String ref = result.getRef(); final StringBuilder sb = new StringBuilder(file); int index = sb.indexOf(" "); while (index != -1) { if (index != -1) { sb.replace(index, index + 1, "%20"); } index = sb.indexOf(" "); } file = sb.toString(); if ((ref != null) && !stripRef) { result = new URL(protocol, host, port, file + "#" + ref); } else { result = new URL(protocol, host, port, file); } return result; }
/** * Checks if the first lines of a text files looks like a MIB. * * @param file the file to check * @return true if the file is probably a MIB file, or false otherwise * @since 2.9 */ private static boolean isMib(File file) { if (!file.canRead() || !file.isFile()) { return false; } StringBuilder buffer = new StringBuilder(); BufferedReader in = null; try { in = new BufferedReader(new FileReader(file)); String str; int line = 0; while (line++ < 100 && (str = in.readLine()) != null) { buffer.append(str); } } catch (FileNotFoundException ignore) { // Do nothing } catch (IOException ignore) { // Do nothing } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { // Do nothing } } } return buffer.indexOf("DEFINITIONS") > 0 && buffer.indexOf("::=") > 0 && buffer.indexOf("BEGIN") > 0; }
private static String refactorString(final String string) { // Avoid error when content is "". if (string.compareTo("") == 0) { return " "; } /* * If the font of "\n" is "" or "\n", insert " " in front of it. For * example: "\nabc" -> " \nabc" "\nabc\n\n" -> " \nabc\n \n". */ final StringBuilder strBuilder = new StringBuilder(string); int start = 0; int index = strBuilder.indexOf("\n"); while (index != -1) { if (index == 0 || strBuilder.charAt(index - 1) == '\n') { strBuilder.insert(start, " "); start = index + 2; } else { start = index + 1; } if (start > strBuilder.length() || index == strBuilder.length()) { break; } index = strBuilder.indexOf("\n", start); } return strBuilder.toString(); }
/** * Formats a URI by adding a forward slash and removing the last forward slash from the URI. * * <p>e.g. some/random/uri/ -> /some/random/uri e.g. some/random/uri -> /some/random/uri e.g. * /some/random/uri/ -> /some/random/uri e.g. / -> / e.g. ////// -> / * * @param uri * @return */ public static String formatUri(String uri) { if (StringUtilities.nullSafeStartsWith(uri, "\\")) { // windows file system return uri; } if (StringUtilities.isBlank(uri) || StringUtilities.nullSafeEqualsIgnoreCase("/", uri)) { return "/"; } final StringBuilder externalName = new StringBuilder(uri); if (externalName.charAt(0) != '/') { externalName.insert(0, "/"); } int doubleSlash = externalName.indexOf("//"); while (doubleSlash > -1) { // removes leading '/' externalName.replace(doubleSlash, doubleSlash + 2, "/"); doubleSlash = externalName.indexOf("//"); } if (externalName.charAt(externalName.length() - 1) == '/' && externalName.length() != 1) { externalName.deleteCharAt(externalName.length() - 1); } return externalName.toString(); }
/** * 删除所有在startStr和endStr之间的字符串,包括startStr和endStr,即删除闭区间[startStr,endStr] * * @param sb * @param startStr * @param endStr */ public static void deleteAllIn(StringBuilder sb, String startStr, String endStr) { int startIndex = 0; int endIndex = 0; while ((startIndex = sb.indexOf(startStr)) >= 0 && (endIndex = sb.indexOf(endStr)) >= 0) { sb.delete(startIndex, endIndex + endStr.length()); } }
public void setWikipediaUrl(String wikipediaUrl) { // Log.d(TAG, "link item is " + wikipediaUrl); if (!wikipediaUrl.contains("http://")) { sb.append("http://").append(wikipediaUrl); } else { sb.append(wikipediaUrl); index = sb.indexOf("http"); if (index > 0) { sb.delete(0, index); } } index = sb.indexOf(".m."); if (index == -1) { index = sb.indexOf("."); // Log.d(TAG, "dot index is " + index); sb.insert(index, ".m"); } /*if(sb.indexOf("featured_article") > 0) { Log.d(TAG, "article url is " + sb.toString()); }*/ this.wikipediaUrl = sb.toString(); sb.setLength(0); }
protected String parseStringValue( String strVal, PlaceholderResolver placeholderResolver, Set<String> visitedPlaceholders) { StringBuilder buf = new StringBuilder(strVal); int startIndex = strVal.indexOf(this.placeholderPrefix); while (startIndex != -1) { int endIndex = findPlaceholderEndIndex(buf, startIndex); if (endIndex != -1) { String placeholder = buf.substring(startIndex + this.placeholderPrefix.length(), endIndex); String originalPlaceholder = placeholder; if (!visitedPlaceholders.add(originalPlaceholder)) { throw new IllegalArgumentException( "Circular placeholder reference '" + originalPlaceholder + "' in property definitions"); } // Recursive invocation, parsing placeholders contained in the placeholder key. placeholder = parseStringValue(placeholder, placeholderResolver, visitedPlaceholders); // Now obtain the value for the fully resolved key... String propVal = placeholderResolver.resolvePlaceholder(placeholder); if (propVal == null && this.valueSeparator != null) { int separatorIndex = placeholder.indexOf(this.valueSeparator); if (separatorIndex != -1) { String actualPlaceholder = placeholder.substring(0, separatorIndex); String defaultValue = placeholder.substring(separatorIndex + this.valueSeparator.length()); propVal = placeholderResolver.resolvePlaceholder(actualPlaceholder); if (propVal == null) { propVal = defaultValue; } } } if (propVal != null) { // Recursive invocation, parsing placeholders contained in the // previously resolved placeholder value. propVal = parseStringValue(propVal, placeholderResolver, visitedPlaceholders); buf.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal); if (logger.isTraceEnabled()) { logger.trace("Resolved placeholder '" + placeholder + "'"); } startIndex = buf.indexOf(this.placeholderPrefix, startIndex + propVal.length()); } else if (this.ignoreUnresolvablePlaceholders) { // Proceed with unprocessed value. startIndex = buf.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length()); } else { throw new IllegalArgumentException("Could not resolve placeholder '" + placeholder + "'"); } visitedPlaceholders.remove(originalPlaceholder); } else { startIndex = -1; } } return buf.toString(); }
/** * 替换字符串 * * @param sb * @param what * @param with * @return */ public static StringBuilder replace(StringBuilder sb, String what, String with) { int pos = sb.indexOf(what); while (pos > -1) { sb.replace(pos, pos + what.length(), with); pos = sb.indexOf(what); } return sb; }
private static void strip(final StringBuilder input, final String prefix, final String suffix) { int start = input.indexOf(prefix); while (start != -1) { int end = input.indexOf(suffix, start + prefix.length()); if (end == -1) end = input.length(); input.delete(start, end + suffix.length()); start = input.indexOf(prefix, start); } }
private static void replace(final StringBuilder input, final String from, final String to) { int start = input.indexOf(from); int length = from.length(); while (start != -1) { input.delete(start, start + length); input.insert(start, to); start = input.indexOf(from, start); } }
/** * Replaces all occurrences of the given string in the string builder * * @param stringBuilder The string builder to update with replaced strings * @param toReplace The string to replace in the string builder * @param replaceWith The string to replace with */ public static void replaceAll(StringBuilder stringBuilder, String toReplace, String replaceWith) { int index = stringBuilder.indexOf(toReplace); while (index != -1) { stringBuilder.replace(index, index + toReplace.length(), replaceWith); index += replaceWith.length(); // Move to the end of the replacement index = stringBuilder.indexOf(toReplace, index); } }
/* * Replace all occurances of the searchString in the originalString with the replaceString. Faster than the * String.replace() method. Does not use regexes. * <p/> * If your searchString is empty, this will spin forever. * * * @param originalString * @param searchString * @param replaceString * @return */ public static String replace(String originalString, String searchString, String replaceString) { StringBuilder sb = new StringBuilder(originalString); int index = sb.indexOf(searchString); while (index != -1) { sb.replace(index, index + searchString.length(), replaceString); index += replaceString.length(); index = sb.indexOf(searchString, index); } return sb.toString(); }
/** * Build a list of commands matching the given string. * * @param caller the {@link MessageReceiver} * @param command the command name * @return nullchar separated stringbuilder */ public StringBuilder matchCommand( MessageReceiver caller, String command, boolean onlySubcommands) { int matches = 0; int maxMatches = 4; StringBuilder matching = new StringBuilder(); command = command.toLowerCase(); // Match base commands for (String key : commands.keySet()) { if (!onlySubcommands) { if (key.toLowerCase().equals(command)) { // Perfect match if (matching.indexOf("/".concat(key)) == -1) { if (commands.get(key).canUse(caller) && matches <= maxMatches) { ++matches; matching.append("/").append(key).append("\u0000"); } } } else if (key.toLowerCase().startsWith(command)) { // Partial match if (matching.indexOf("/".concat(key)) == -1) { if (commands.get(key).canUse(caller) && matches <= maxMatches) { ++matches; matching.append("/").append(key).append("\u0000"); } } } } // Match sub commands for (CanaryCommand cmd : commands.get(key).getSubCommands(new ArrayList<CanaryCommand>())) { for (String alias : cmd.meta.aliases()) { if (alias.toLowerCase().equals(command)) { // full match if (matching.indexOf(alias) == -1) { if (cmd.canUse(caller) && matches <= maxMatches) { ++matches; matching.append(alias).append("\u0000"); } } } else if (alias.toLowerCase().startsWith(command)) { // partial match if (matching.indexOf(alias) == -1) { if (cmd.canUse(caller) && matches <= maxMatches) { ++matches; matching.append(alias).append("\u0000"); } } } } } } return matching; }
protected String getDomainIdFromXmi(StringBuilder sb) { int datasourceModelTagPosition = sb.indexOf("datasourceModel"); if (datasourceModelTagPosition != -1) { String tag = "<CWM:Description body="; int startTagPosition = sb.indexOf(tag, datasourceModelTagPosition); int startPosition = startTagPosition + tag.length() + 1; int endPosition = sb.indexOf("\"", startPosition); return StringEscapeUtils.unescapeXml(sb.substring(startPosition, endPosition)); } else { return null; } }
public static int numberOfOccurence(String str, String subStr) { int count = 0; int indexSubStr; StringBuilder strBuild = new StringBuilder(str); indexSubStr = strBuild.indexOf(subStr); while (indexSubStr >= 0) { count++; strBuild.delete(0, indexSubStr + 1); indexSubStr = strBuild.indexOf(subStr); } return count; }
private String toRegex(String text) { StringBuilder result = new StringBuilder(text); int i = -1; while ((i = result.indexOf("[", i + 1)) != -1) { result.insert(i++, '\\'); } i = -1; while ((i = result.indexOf("]", i + 1)) != -1) { result.insert(i++, '\\'); } return result.toString(); }
/** * Expand one macro reference * * @param text Expand macros found in this text * @param macroName Macro name */ private void expand(StringBuilder sb, String macroName) { int index; /* * Replace every occurance of the macro in the parameter list */ index = sb.indexOf(macroName); while (index != -1) { String macroValue = URLEncoder.encode(getMacroValue(macroName)); sb.replace(index, (index + macroName.length()), macroValue); index = sb.indexOf(macroName, (index + macroValue.length())); } }
public static void main(String[] args) { StringBuilder sb = new StringBuilder("A dog"); System.out.println(sb.append("!")); System.out.println(sb.insert(2, "barking ")); int beginIndex = sb.indexOf("bark"); int endIndex = sb.indexOf("!"); System.out.println(sb.replace(beginIndex, endIndex, "meowing cat")); beginIndex = sb.indexOf("meow"); endIndex = sb.indexOf("cat"); System.out.println(sb.delete(beginIndex, endIndex)); System.out.println(sb.substring(2, sb.length())); }
@Override public synchronized void run() { while (!quit) { // filter_input(); try { Thread.sleep(1); // poll at 1kHz // grab data from shared buffer and move it the local one ourBuffer.append(sharedBuffer.take()); // System.out.print(ourBuffer); // create a matcher to find an open tag in the buffer int endCloseTag; int startOpenTag; Matcher closeTagMatcher = closeTagPattern.matcher(ourBuffer); // look or a closing tag in our buffer if (closeTagMatcher.find()) { endCloseTag = closeTagMatcher.end(); openTag = "<" + ourBuffer.charAt(closeTagMatcher.start() + 2) + ">"; // find corresponding opening tag startOpenTag = ourBuffer.indexOf(openTag); // send the input string to the GUI for processing if (startOpenTag >= 0 && startOpenTag < endCloseTag) { gui.incoming(ourBuffer.substring(startOpenTag, endCloseTag)); // clear our buffer ourBuffer.delete(startOpenTag, endCloseTag); } else { ourBuffer.delete(0, endCloseTag); } } } catch (Exception e) { System.out.print(e + "\n"); } } }
public static String getReadableVersion(String version) { try { String number = version.substring(version.indexOf("-") + 1, version.lastIndexOf("-")); String date = version.substring( version.lastIndexOf("-") + 1, version.endsWith(".zip") ? version.lastIndexOf(".") : version.length()); SimpleDateFormat curFormater = new SimpleDateFormat("yyyyMMdd"); Date dateObj = null; try { dateObj = curFormater.parse(date); } catch (ParseException e) { // ignore } SimpleDateFormat postFormater = new SimpleDateFormat("MMMM dd, yyyy"); if (dateObj == null) { return number; } String newDateStr = postFormater.format(dateObj); StringBuilder b = new StringBuilder(newDateStr); int i = 0; do { b.replace(i, i + 1, b.substring(i, i + 1).toUpperCase()); i = b.indexOf(" ", i) + 1; } while (i > 0 && i < b.length()); return number + " - " + b.toString(); } catch (Exception ex) { // unknown version format return version; } }
private void replaceNextPlaceHolders( StringBuilder sqlWithQuestionMarks, Object... valuesToReplace) { for (Object nextValue : valuesToReplace) { int index = sqlWithQuestionMarks.indexOf("?"); sqlWithQuestionMarks.replace(index, index + 1, String.valueOf(nextValue)); } }