List of usage examples for java.lang StringBuffer substring
@Override public synchronized String substring(int start, int end)
From source file:org.opencron.common.utils.StringUtils.java
public static String joinString(Collection<?> collection, String separator) { AssertUtils.notEmpty(collection, "joinString arguments collection and separator can not be null"); StringBuffer collStr = new StringBuffer(); for (Object o : collection) { collStr.append(o).append(separator); }// w w w. java 2s . co m return collStr.substring(0, collStr.length() - separator.length()); }
From source file:org.locationtech.jtstest.util.StringUtil.java
/** * Replaces all instances of the String o with the String n in the * StringBuffer orig if all is true, or only the first instance if all is * false. Posted by Steve Chapel <schapel@breakthr.com> on UseNet *//*from w w w .j a v a 2 s . co m*/ public static void replace(StringBuffer orig, String o, String n, boolean all) { if (orig == null || o == null || o.length() == 0 || n == null) { throw new IllegalArgumentException("Null or zero-length String"); } int i = 0; while (i + o.length() <= orig.length()) { if (orig.substring(i, i + o.length()).equals(o)) { orig.replace(i, i + o.length(), n); if (!all) { break; } else { i += n.length(); } } else { i++; } } }
From source file:org.guzz.util.PropertyUtil.java
/** * >= JDK1.4//from w w w . j ava2 s . com * resolve ${...} placeholders in the @param text , then trim() the value and return. * @param props Map * @param text the String text to replace * @return the resolved value * * @see #PLACEHOLDER_PREFIX * @see #PLACEHOLDER_SUFFIX */ public static String getTrimStringMatchPlaceholdersInMap(Map props, String text) { if (text == null || props == null || props.isEmpty()) { return text; } StringBuffer buf = new StringBuffer(text); int startIndex = buf.indexOf(PLACEHOLDER_PREFIX); while (startIndex != -1) { int endIndex = buf.indexOf(PLACEHOLDER_SUFFIX, startIndex + PLACEHOLDER_PREFIX.length()); if (endIndex != -1) { String placeholder = buf.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex); String propVal = (String) props.get(placeholder); if (propVal != null) { buf.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), propVal); startIndex = buf.indexOf(PLACEHOLDER_PREFIX, startIndex + propVal.length()); } else { log.warn("Could not resolve placeholder '" + placeholder + "' in [" + text + "]"); startIndex = buf.indexOf(PLACEHOLDER_PREFIX, endIndex + PLACEHOLDER_SUFFIX.length()); } } else { startIndex = -1; } } return buf.toString().trim(); }
From source file:com.kolich.curacao.mappers.request.types.body.EncodedRequestBodyMapper.java
private static final Map.Entry<String, String> getNextNameValuePair(final StringBuffer buffer, final Cursor cursor) { boolean terminated = false; int pos = cursor.getPosition(), indexFrom = cursor.getPosition(), indexTo = cursor.getUpperBound(); // Find name/* w w w. ja v a 2s.com*/ String name = null; while (pos < indexTo) { final char ch = buffer.charAt(pos); if (ch == KEY_VALUE_EQUALS) { break; } if (ch == DELIMITER) { terminated = true; break; } pos++; } if (pos == indexTo) { terminated = true; name = buffer.substring(indexFrom, indexTo).trim(); } else { name = buffer.substring(indexFrom, pos).trim(); pos++; } if (terminated) { cursor.updatePosition(pos); return Maps.immutableEntry(name, null); } // Find value String value = null; int i1 = pos; boolean quoted = false, escaped = false; while (pos < indexTo) { char ch = buffer.charAt(pos); if (ch == VALUE_DOUBLE_QUOTE && !escaped) { quoted = !quoted; } if (!quoted && !escaped && ch == DELIMITER) { terminated = true; break; } if (escaped) { escaped = false; } else { escaped = quoted && ch == '\\'; } pos++; } int i2 = pos; // Trim leading white space while (i1 < i2 && (Whitespace.isWhitespace(buffer.charAt(i1)))) { i1++; } // Trim trailing white space while ((i2 > i1) && (Whitespace.isWhitespace(buffer.charAt(i2 - 1)))) { i2--; } // Strip away quotes if necessary if (((i2 - i1) >= 2) && (buffer.charAt(i1) == '"') && (buffer.charAt(i2 - 1) == '"')) { i1++; i2--; } value = buffer.substring(i1, i2); if (terminated) { pos++; } cursor.updatePosition(pos); return Maps.immutableEntry(name, value); }
From source file:eap.util.EDcodeUtil.java
public static byte[] gbk2utf8(String chenese) { char c[] = chenese.toCharArray(); byte[] fullByte = new byte[3 * c.length]; for (int i = 0; i < c.length; i++) { int m = (int) c[i]; String word = Integer.toBinaryString(m); StringBuffer sb = new StringBuffer(); int len = 16 - word.length(); for (int j = 0; j < len; j++) { sb.append("0"); }//w w w .j a va 2s . co m sb.append(word); sb.insert(0, "1110"); sb.insert(8, "10"); sb.insert(16, "10"); byte[] bf = new byte[3]; bf[0] = Integer.valueOf(sb.substring(0, 8), 2).byteValue(); fullByte[i * 3] = bf[0]; bf[1] = Integer.valueOf(sb.substring(8, 16), 2).byteValue(); fullByte[i * 3 + 1] = bf[1]; bf[2] = Integer.valueOf(sb.substring(16), 2).byteValue(); fullByte[i * 3 + 2] = bf[2]; } return fullByte; }
From source file:org.apache.hadoop.contrib.failmon.Environment.java
/** * Scans the configuration file to determine which monitoring * utilities are available in the system. For each one of them, a * job is created. All such jobs are scheduled and executed by * Executor.//from w w w . j a v a 2 s . co m * * @return an ArrayList that contains jobs to be executed by theExecutor. */ public static ArrayList<MonitorJob> getJobs() { ArrayList<MonitorJob> monitors = new ArrayList<MonitorJob>(); int timeInt = 0; // for Hadoop Log parsing String[] fnames_r = getProperty("log.hadoop.filenames").split(",\\s*"); String tmp = getProperty("log.hadoop.enabled"); String[] fnames = expandDirs(fnames_r, ".*(.log).*"); timeInt = setValue("log.hadoop.interval", DEFAULT_LOG_INTERVAL); if ("true".equalsIgnoreCase(tmp) && fnames[0] != null) for (String fname : fnames) { File f = new File(fname); if (f.exists() && f.canRead()) { monitors.add(new MonitorJob(new HadoopLogParser(fname), "hadoopLog", timeInt)); logInfo("Created Monitor for Hadoop log file: " + f.getAbsolutePath()); } else if (!f.exists()) logInfo("Skipping Hadoop log file " + fname + " (file not found)"); else logInfo("Skipping Hadoop log file " + fname + " (permission denied)"); } // for System Log parsing fnames_r = getProperty("log.system.filenames").split(",\\s*"); tmp = getProperty("log.system.enabled"); fnames = expandDirs(fnames_r, ".*(messages).*"); timeInt = setValue("log.system.interval", DEFAULT_LOG_INTERVAL); if ("true".equalsIgnoreCase(tmp)) for (String fname : fnames) { File f = new File(fname); if (f.exists() && f.canRead()) { monitors.add(new MonitorJob(new SystemLogParser(fname), "systemLog", timeInt)); logInfo("Created Monitor for System log file: " + f.getAbsolutePath()); } else if (!f.exists()) logInfo("Skipping system log file " + fname + " (file not found)"); else logInfo("Skipping system log file " + fname + " (permission denied)"); } // for network interfaces tmp = getProperty("nic.enabled"); timeInt = setValue("nics.interval", DEFAULT_POLL_INTERVAL); if ("true".equalsIgnoreCase(tmp)) { monitors.add(new MonitorJob(new NICParser(), "nics", timeInt)); logInfo("Created Monitor for NICs"); } // for cpu tmp = getProperty("cpu.enabled"); timeInt = setValue("cpu.interval", DEFAULT_POLL_INTERVAL); if ("true".equalsIgnoreCase(tmp)) { monitors.add(new MonitorJob(new CPUParser(), "cpu", timeInt)); logInfo("Created Monitor for CPUs"); } // for disks tmp = getProperty("disks.enabled"); timeInt = setValue("disks.interval", DEFAULT_POLL_INTERVAL); if ("true".equalsIgnoreCase(tmp)) { // check privileges if a disk with no disks./dev/xxx/.source is found boolean smart_present = checkExistence("smartctl"); int disks_ok = 0; String devicesStr = getProperty("disks.list"); String[] devices = null; if (devicesStr != null) devices = devicesStr.split(",\\s*"); for (int i = 0; i < devices.length; i++) { boolean file_present = false; boolean disk_present = false; String fileloc = getProperty("disks." + devices[i] + ".source"); if (fileloc != null && fileloc.equalsIgnoreCase("true")) file_present = true; if (!file_present) if (superuser) { StringBuffer sb = runCommand("sudo smartctl -i " + devices[i]); String patternStr = "[(failed)(device not supported)]"; Pattern pattern = Pattern.compile(patternStr); Matcher matcher = pattern.matcher(sb.toString()); if (matcher.find(0)) disk_present = false; else disk_present = true; } if (file_present || (disk_present && smart_present)) { disks_ok++; } else devices[i] = null; } // now remove disks that dont exist StringBuffer resetSB = new StringBuffer(); for (int j = 0; j < devices.length; j++) { resetSB.append(devices[j] == null ? "" : devices[j] + ", "); if (devices[j] != null) logInfo("Found S.M.A.R.T. attributes for disk " + devices[j]); } // fix the property if (resetSB.length() >= 2) setProperty("disks.list", resetSB.substring(0, resetSB.length() - 2)); if (disks_ok > 0) { monitors.add(new MonitorJob(new SMARTParser(), "disks", timeInt)); logInfo("Created Monitor for S.M.A.R.T disk attributes"); } } // for lm-sensors tmp = getProperty("sensors.enabled"); timeInt = setValue("sensors.interval", DEFAULT_POLL_INTERVAL); if ("true".equalsIgnoreCase(tmp) && checkExistence("sensors")) { monitors.add(new MonitorJob(new SensorsParser(), "sensors", timeInt)); logInfo("Created Monitor for lm-sensors output"); } return monitors; }
From source file:org.protorabbit.model.impl.DefaultEngine.java
public static void renderCommands(List<ICommand> cmds, StringBuffer buff, IContext ctx, OutputStream out) { if (cmds == null) { getLogger().log(Level.SEVERE, "Error rendering content."); }//from w ww .j a va2 s . c om try { int index = 0; for (ICommand c : cmds) { // output everything before the first command // include profiler episodes.js if (ctx.getConfig().profile()) { String preText = buff.substring(index, c.getStartIndex()); int headStart = preText.indexOf("<head>"); if (headStart != -1) { long serverTime = ((Episode) ctx.getAttribute(Config.EPISODE)).getTimestamp(); preText = preText.substring(0, headStart + 6) + "<script>var timeshift=0;var serverTimestamp = " + serverTime + ";</script>" + "<script src=\"prt?resourceid=episodes.js\"></script>" + "<script>var t_pingStart1 = (new Date()).getTime();</script>" + "<script src=\"prt?command=ping\"></script>" + "<script>var t_now1 = (new Date()).getTime();" + "var t_transit1= Math.round((t_now1 - t_pingStart1) / 2);" + "var t_pingStart2 = (new Date()).getTime();" + "document.write(\"<scr\" + \"ipt src='prt?command=timeshift&clientTime=\" + t_pingStart2 + \"'></scr\" + \"ipt>\");\n" + "var t_now2 = (new Date()).getTime();\n" + "var t_transit2= Math.round((t_now2 - t_pingStart2) / 2);\n" + "var t_transit= Math.round((t_transit1 + t_transit2) / 4);\n" + "if ((t_transit * 2) < timeshift) {timeshift = timeshift - (t_transit * 2);} else if (timeshift < 0) {timeshift+=(t_transit * 2);}" + "var t_sync='prt?command=episodesync×tamp=" + serverTime + "&transitTime=' + t_transit;" + "document.write(\"<scr\" + \"ipt src='\" + t_sync + \"'></scr\" + \"ipt>\");</script>" + preText.substring(headStart + 6, preText.length()); } out.write(preText.getBytes()); } else { out.write(buff.substring(index, c.getStartIndex()).getBytes()); } index = c.getEndIndex(); try { // if we have a sub document context render it IDocumentContext dc = c.getDocumentContext(); if (dc != null) { if ((dc.getAllCommands() == null || (dc.getAllCommands() != null && dc.getAllCommands().size() == 0)) /* && dc.getDocument() != null */) { if (dc.getDocument() != null) { out.write(dc.getDocument().toString().getBytes()); } } renderCommands(dc.getAllCommands(), dc.getDocument(), ctx, out); } ByteArrayOutputStream bos = ctx.getBuffer(c.getUUId()); if (bos != null) { out.write(bos.toByteArray()); } } catch (IOException e) { getLogger().log(Level.SEVERE, "Error rendering commands ", e); } } // now write everything after the last command if (cmds.size() > 0) { ICommand lc = cmds.get(cmds.size() - 1); out.write(buff.substring(lc.getEndIndex()).getBytes()); } } catch (Exception e) { getLogger().log(Level.SEVERE, "Error rendering ", e); } }
From source file:org.apache.oltu.oauth2.common.utils.OAuthUtils.java
/** * Construct a WWW-Authenticate header//from www .jav a2s. c om */ public static String encodeOAuthHeader(Map<String, Object> entries) { StringBuffer sb = new StringBuffer(); sb.append(OAuth.OAUTH_HEADER_NAME).append(" "); for (Map.Entry<String, Object> entry : entries.entrySet()) { String value = entry.getValue() == null ? null : String.valueOf(entry.getValue()); if (!OAuthUtils.isEmpty(entry.getKey()) && !OAuthUtils.isEmpty(value)) { sb.append(entry.getKey()); sb.append("=\""); sb.append(value); sb.append("\","); } } return sb.substring(0, sb.length() - 1); }
From source file:com.genentech.application.calcProps.SDFCalcProps.java
/** * Sort commands by dependencies ex. Solubility_Index requires cLogD7.4 * Need to calculate cLogD7.4 before calculating solubility_index * cLogD7.4 command line need to appear before solubility_index command line *//*from w ww . j av a 2 s . co m*/ private static List<Calculator> sortByDependencies(ArrayList<Calculator> calculators, int noCalculatorSizeChangeCount) { int oldCalculatorsSize = calculators.size(); List<Calculator> sorted = new ArrayList<Calculator>(); if (!calculators.isEmpty()) { Calculator calc = calculators.remove(0); //get first element in list Set<String> reqCalculators = calc.getRequiredCalculators(); if (reqCalculators.size() == 0) { // no dependencies, add to beginning sorted.add(0, calc); } else { //there are dependencies // are any dependencies left in the list of calculators to be sorted if (anyDependenciesInList(reqCalculators, calculators)) { calculators.add(calc); //add calc back to the end of the list to be sorted later } else { //they must be in the sorted list, add calc to the end of sorted list sorted.add(calc); //append to end of sorted calculators } } } if (calculators.size() == oldCalculatorsSize) noCalculatorSizeChangeCount = noCalculatorSizeChangeCount + 1; else noCalculatorSizeChangeCount = 0; /*If the number of calculators in the list has not going down within calculators.size() times*/ if (noCalculatorSizeChangeCount == calculators.size() && calculators.size() > 0) { StringBuffer calculatorText = new StringBuffer(); for (Calculator calc : calculators) calculatorText = calculatorText.append(calc.getName()).append(" "); throw new Error("There is a circular dependencies amongst following calculators: " + calculatorText.substring(0, calculatorText.length())); } //recursively sort remaining calculators if (calculators.size() > 0) { //append rest to sorted sorted.addAll(sortByDependencies(calculators, noCalculatorSizeChangeCount)); } return sorted; }
From source file:org.protorabbit.model.impl.DefaultEngine.java
public static List<ICommand> getDocumentCommands(Config cfg, StringBuffer doc) { List<ICommand> commands = new ArrayList<ICommand>(); if (doc == null) return null; int index = 0; int len = doc.length(); while (index < len) { index = doc.indexOf(COMMAND_START, index); int end = doc.indexOf(COMMAND_END, index); if (index == -1 || end == -1) { break; }/* ww w. j a va 2 s . c om*/ // find the full expression String exp = doc.substring(index + 2, end); //find the command int paramStart = exp.indexOf("("); int paramEnd = exp.lastIndexOf(")"); if (paramStart != -1 && paramEnd != -1 && paramEnd > paramStart) { // get commandType String commandTypeString = exp.substring(0, paramStart).trim(); ICommand cmd = cfg.getCommand(commandTypeString); if (cmd != null) { // get the params String paramsString = exp.substring(paramStart + 1, paramEnd); // need to parse out JSON IParameter[] params = getParams(paramsString); if (params != null) { cmd.setParams(params); } cmd.setStartIndex(index); cmd.setEndIndex(end + 2); if ("include".equals(commandTypeString) && params.length > 0) { if ("scripts".equals(params[0]) || "styles".equals(params[0])) { cmd.setType(ICommand.INCLUDE_RESOURCES); } else { cmd.setType(ICommand.INCLUDE); } } else if ("insert".equals(commandTypeString)) { cmd.setType(ICommand.INSERT); } else { cmd.setType(ICommand.CUSTOM); } commands.add(cmd); } } // start the process over index = end + 2; } return commands; }