List of usage examples for java.lang StringBuffer subSequence
@Override public synchronized CharSequence subSequence(int start, int end)
From source file:Main.java
public static void main(String[] arg) { StringBuffer buffer = new StringBuffer("from java2s.com"); System.out.println(buffer.subSequence(1, 2)); }
From source file:Main.java
/** * Generate a unicast MAC address./*from w w w .j a va 2s.co m*/ * A unicast MAC address is the one with an even second hex. * i.e. x[0,2,4,6,8,A,C,E]:xx:xx:xx:xx:xx * * @return Unicast MAC address */ public static String generateRandomMACAddress() { Random r = new Random(); StringBuffer sb = new StringBuffer(); sb.append(Integer.toHexString(r.nextInt(16))); int i = r.nextInt(16); while (i % 2 != 0) i = r.nextInt(16); sb.append(Integer.toHexString(i)); while (sb.length() <= 12) sb.append(Integer.toHexString(r.nextInt())); String address = prepareMACAddress(sb.subSequence(0, 12).toString()); if (address.equals("ff:ff:ff:ff:ff:ff")) return generateRandomMACAddress(); return address; }
From source file:com.capitalone.dashboard.util.ClientUtil.java
/** * Converts a Jira string representation of sprint artifacts into a * canonical JSONArray format./*from w w w . ja v a 2 s . c om*/ * * @param nativeRs * a sanitized String representation of a sprint artifact link * from Jira * @return A canonical JSONArray of Jira sprint artifacts */ @SuppressWarnings("unchecked") public JSONObject toCanonicalSprintJSON(String nativeRs) { JSONObject canonicalRs = new JSONObject(); CharSequence interrimChar; int start = 0; int end = 0; if ((nativeRs != null) && !(nativeRs.isEmpty())) { start = nativeRs.indexOf('[') + 1; end = nativeRs.length() - 1; StringBuffer interrimBuf = new StringBuffer(nativeRs); interrimChar = interrimBuf.subSequence(start, end); String interrimStr = interrimChar.toString(); List<String> list = Arrays.asList(interrimStr.split(",")); if ((list != null) && !(list.isEmpty())) { Iterator<String> listIt = list.iterator(); while (listIt.hasNext()) { String temp = listIt.next(); List<String> keyValuePair = Arrays.asList(temp.split("=", 2)); if ((keyValuePair != null) && !(keyValuePair.isEmpty())) { String key = keyValuePair.get(0).toString(); String value = keyValuePair.get(1).toString(); if ("<null>".equalsIgnoreCase(value)) { value = ""; } canonicalRs.put(key, value); } } } } else { canonicalRs.clear(); } return canonicalRs; }
From source file:com.stimulus.archiva.language.NGramProfile.java
/** * @param word// www. j a va 2 s .com * @param n sequence length */ private void add(StringBuffer word, int n) { for (int i = 0; i <= word.length() - n; i++) { add(word.subSequence(i, i + n)); } }
From source file:info.magnolia.cms.beans.config.PropertiesInitializer.java
/** * Parse the given String value recursively, to be able to resolve nested placeholders. Partly borrowed from * org.springframework.beans.factory.config.PropertyPlaceholderConfigurer (original author: Juergen Hoeller) * * @deprecated since 4.5 this is now done by {@link info.magnolia.init.AbstractMagnoliaConfigurationProperties#parseStringValue}. *///www .j a va 2 s . c o m protected String parseStringValue(String strVal, Set<String> visitedPlaceholders) { StringBuffer buf = new StringBuffer(strVal); int startIndex = strVal.indexOf(PLACEHOLDER_PREFIX); while (startIndex != -1) { int endIndex = -1; int index = startIndex + PLACEHOLDER_PREFIX.length(); int withinNestedPlaceholder = 0; while (index < buf.length()) { if (PLACEHOLDER_SUFFIX.equals(buf.subSequence(index, index + PLACEHOLDER_SUFFIX.length()))) { if (withinNestedPlaceholder > 0) { withinNestedPlaceholder--; index = index + PLACEHOLDER_SUFFIX.length(); } else { endIndex = index; break; } } else if (PLACEHOLDER_PREFIX.equals(buf.subSequence(index, index + PLACEHOLDER_PREFIX.length()))) { withinNestedPlaceholder++; index = index + PLACEHOLDER_PREFIX.length(); } else { index++; } } if (endIndex != -1) { String placeholder = buf.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex); if (!visitedPlaceholders.add(placeholder)) { log.warn("Circular reference detected in properties, \"{}\" is not resolvable", strVal); return strVal; } // Recursive invocation, parsing placeholders contained in the placeholder key. placeholder = parseStringValue(placeholder, visitedPlaceholders); // Now obtain the value for the fully resolved key... String propVal = SystemProperty.getProperty(placeholder); if (propVal != null) { // Recursive invocation, parsing placeholders contained in the // previously resolved placeholder value. propVal = parseStringValue(propVal, visitedPlaceholders); buf.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), propVal); startIndex = buf.indexOf(PLACEHOLDER_PREFIX, startIndex + propVal.length()); } else { // Proceed with unprocessed value. startIndex = buf.indexOf(PLACEHOLDER_PREFIX, endIndex + PLACEHOLDER_SUFFIX.length()); } visitedPlaceholders.remove(placeholder); } else { startIndex = -1; } } return buf.toString(); }
From source file:com.ss.language.model.gibblda.Estimator.java
/** * ???/*www .j a v a2s .c o m*/ * * @param docs */ private void writeEachwordsEachWord(Document[] docs) { if (docs != null && docs.length > 0) { BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader( new FileInputStream(trnModel.data.localDict.getWordIdsFile()), "UTF-8")); for (String wordId = br.readLine(); wordId != null; wordId = br.readLine()) { wordId = wordId == null ? "" : wordId.trim(); if (wordId.isEmpty()) { continue; } StringBuffer sb = new StringBuffer(); for (Document doc : docs) { String[] words = doc.getAllWords(); if (words != null && words.length > 0) { int times = 0; for (String w : words) { if (wordId.equals(w)) { times += 1; } } if (times > 0) { sb.append("("); sb.append(doc.getDocId()); sb.append(":"); sb.append(times); sb.append("),"); } } } // ??? if (sb.length() > 0) { File file = new File( option.dir + File.separator + option.wordMapFileName + "-statistic.txt"); sb.insert(0, "["); sb.insert(sb.length() - 1, "]"); FileUtils.write(file, sb.subSequence(0, sb.length() - 1) + IOUtils.LINE_SEPARATOR, "UTF-8", true); } } } catch (Exception e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (Exception e) { } } } } }
From source file:marytts.tools.dbselection.WikipediaMarkupCleaner.java
/**** * This is also special because the line might contain sections with [[ ... ]] so the ]] after a [[ * is not the endTag of [[image: ... ]] * @param s//from w ww. j a va 2 s . c o m * @param lineIn * @param iniTag * @param endTag * @param debug * @return */ private StringBuffer removeSectionImage(Scanner s, StringBuffer lineIn, String iniTag, String endTag) { String next; int index1 = 0, index2 = -1, index3 = -1, endTagLength = 0, numRef = 0, lastEndTag1 = 0, lastIniTag = 0; boolean closeRef = true; StringBuffer line = new StringBuffer(lineIn); StringBuffer nextLine; StringBuffer aux; if (debug) System.out.println("Removing tag: " + iniTag + " LINE (BEFORE): " + line); while ((index1 = line.indexOf(iniTag)) >= 0) { // in one line can be more than one iniTag numRef++; index3 = endTagLength = index1; while (s.hasNext() && numRef > 0) { while ((index2 = line.indexOf("]]", endTagLength)) >= 0 && numRef > 0) { aux = new StringBuffer(line.subSequence(index1 + 2, index2 + 2)); if (debug) System.out.println(" aux=" + aux); if ((index3 = aux.indexOf("[[")) == -1) { endTagLength = endTag.length() + index2; numRef--; } else { // The previous was a [[ ]] inside of a [[Image: so it has to be deleted index1 = index2; endTagLength = index2 + 2; index2 = -1; } } // so far it has not found the endTag, so get another line if (numRef > 0) line.append(s.nextLine()); } if (numRef == 0) { index1 = line.indexOf(iniTag); // get again this because the position might change if (endTagLength > index1) { if (debug) { System.out.println(" FINAL LINE: " + line); System.out.print("iniTag: " + iniTag + " index1=" + index1); System.out.print(" endTagLength=" + endTagLength); System.out.println(" line.length=" + line.length() + " line: " + line); System.out.println(" line.length=" + line.length()); } line.delete(index1, endTagLength); } else { if (debug) { System.out.println("removeSection: WARNING endTagLength > length of line: "); System.out.print("iniTag: " + iniTag + " index1=" + index1); System.out.print(" endTagLength=" + endTagLength); System.out.println(" line.length=" + line.length() + " line: " + line); System.out.println("removeSection: WARNING endTagLength > length of line: " + line); } line = new StringBuffer(""); } } else { if (debug) System.out.println("removeSection: WARNING no " + endTag); line = new StringBuffer(""); } } // while this line contains iniTag-s if (debug) System.out.println(" LINE (AFTER): " + line); return line; }
From source file:com.baidu.gcrm.customer.service.impl.CustomerServiceImpl.java
/** * //from ww w . j av a 2 s .c o m * ??: ? ???????? * processOtherInfo * @: chenchunhui01 * @: 2014715 ?3:55:46 * @param record * @param locale * @return void * @exception * @version */ private void processOtherInfo(Map<String, Object> record, LocaleConstants locale) { Object filed = record.get(ModifyRecordConstant.TABLEFIELD_KEY); if (filed == null) { return; } String filedName = filed.toString(); String newValueKey = ""; if (record.get(ModifyRecordConstant.NEWVALUE_KEY) != null) newValueKey = record.get(ModifyRecordConstant.NEWVALUE_KEY).toString(); String oldValueKey = ""; if (record.get(ModifyRecordConstant.OLDVALUE_KEY) != null) oldValueKey = record.get(ModifyRecordConstant.OLDVALUE_KEY).toString(); if ("customerType".equals(filedName)) { if (StringUtils.isNotBlank(newValueKey)) record.put(ModifyRecordConstant.NEWVALUE_KEY, MessageHelper.getMessage("customer.type." + newValueKey, locale)); if (StringUtils.isNotBlank(oldValueKey)) record.put(ModifyRecordConstant.OLDVALUE_KEY, MessageHelper.getMessage("customer.type." + oldValueKey, locale)); } else if ("companySize".equals(filedName)) { if (StringUtils.isNotBlank(newValueKey)) record.put(ModifyRecordConstant.NEWVALUE_KEY, MessageHelper.getMessage("customer.companySize." + newValueKey, locale)); if (StringUtils.isNotBlank(oldValueKey)) record.put(ModifyRecordConstant.OLDVALUE_KEY, MessageHelper.getMessage("customer.companySize." + oldValueKey, locale)); } else if ("country".equals(filedName)) { if (StringUtils.isNotBlank(newValueKey)) record.put(ModifyRecordConstant.NEWVALUE_KEY, countryCacheServiceImpl.getByIdAndLocale(newValueKey, locale).getI18nName()); if (StringUtils.isNotBlank(oldValueKey)) record.put(ModifyRecordConstant.OLDVALUE_KEY, countryCacheServiceImpl.getByIdAndLocale(oldValueKey, locale).getI18nName()); } else if ("industry".equals(filedName)) { if (StringUtils.isNotBlank(newValueKey)) record.put(ModifyRecordConstant.NEWVALUE_KEY, industryServiceImpl.getByIdAndLocale(newValueKey, locale).getI18nName()); if (StringUtils.isNotBlank(oldValueKey)) record.put(ModifyRecordConstant.OLDVALUE_KEY, industryServiceImpl.getByIdAndLocale(oldValueKey, locale).getI18nName()); } else if ("belongSales".equals(filedName) || "belongManager".equals(filedName)) { if (StringUtils.isNotBlank(newValueKey)) { User user = userService.findByUcid(Long.valueOf(newValueKey)); if (user != null) record.put(ModifyRecordConstant.NEWVALUE_KEY, user.getRealname()); else record.put(ModifyRecordConstant.NEWVALUE_KEY, ""); } if (StringUtils.isNotBlank(oldValueKey)) { User user = userService.findByUcid(Long.valueOf(oldValueKey)); if (user != null) record.put(ModifyRecordConstant.OLDVALUE_KEY, user.getRealname()); else record.put(ModifyRecordConstant.NEWVALUE_KEY, ""); } } else if ("agentType".equals(filedName)) { if (StringUtils.isNotBlank(newValueKey)) record.put(ModifyRecordConstant.NEWVALUE_KEY, MessageHelper.getMessage("customer.agentType." + newValueKey, locale)); if (StringUtils.isNotBlank(oldValueKey)) record.put(ModifyRecordConstant.OLDVALUE_KEY, MessageHelper.getMessage("customer.agentType." + oldValueKey, locale)); } else if ("agentRegional".equals(filedName)) { if (StringUtils.isNotBlank(newValueKey)) record.put(ModifyRecordConstant.NEWVALUE_KEY, agentRegionalService.getByIdAndLocale(newValueKey, locale).getI18nName()); if (StringUtils.isNotBlank(oldValueKey)) record.put(ModifyRecordConstant.OLDVALUE_KEY, agentRegionalService.getByIdAndLocale(oldValueKey, locale).getI18nName()); } else if ("agentCountry".equals(filedName)) { if (StringUtils.isNotBlank(newValueKey)) { String[] countryIds = newValueKey.split(","); StringBuffer countryName = new StringBuffer(); for (String countryId : countryIds) { countryName.append(countryCacheServiceImpl.getByIdAndLocale(countryId, locale).getI18nName()); countryName.append("?"); } if (countryName.length() > 0) { record.put(ModifyRecordConstant.NEWVALUE_KEY, countryName.subSequence(0, countryName.length() - 1)); } else { record.put(ModifyRecordConstant.NEWVALUE_KEY, ""); } } if (StringUtils.isNotBlank(oldValueKey)) { String[] countryIds = oldValueKey.split(","); StringBuffer countryName = new StringBuffer(); for (String countryId : countryIds) { countryName.append(countryCacheServiceImpl.getByIdAndLocale(countryId, locale).getI18nName()); countryName.append("?"); } if (countryName.length() > 0) { record.put(ModifyRecordConstant.OLDVALUE_KEY, countryName.subSequence(0, countryName.length() - 1)); } else { record.put(ModifyRecordConstant.OLDVALUE_KEY, ""); } } } else if ("businessType".equals(filedName)) { if (StringUtils.isNotBlank(newValueKey)) { String[] businessKeys = newValueKey.split(","); StringBuffer businessTypeNames = new StringBuffer(); for (String businessTypeKey : businessKeys) { businessTypeNames .append(MessageHelper.getMessage("customer.businessType." + businessTypeKey, locale)); businessTypeNames.append("?"); } if (businessTypeNames.length() > 0) { record.put(ModifyRecordConstant.NEWVALUE_KEY, businessTypeNames.subSequence(0, businessTypeNames.length() - 1)); } else { record.put(ModifyRecordConstant.NEWVALUE_KEY, ""); } } if (StringUtils.isNotBlank(oldValueKey)) { String[] businessKeys = oldValueKey.split(","); StringBuffer businessTypeNames = new StringBuffer(); for (String businessTypeKey : businessKeys) { businessTypeNames .append(MessageHelper.getMessage("customer.businessType." + businessTypeKey, locale)); businessTypeNames.append("?"); } if (businessTypeNames.length() > 0) { record.put(ModifyRecordConstant.OLDVALUE_KEY, businessTypeNames.subSequence(0, businessTypeNames.length() - 1)); } else { record.put(ModifyRecordConstant.OLDVALUE_KEY, ""); } } } else if ("registerTime".equals(filedName)) { if (StringUtils.isNotBlank(newValueKey)) { SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss 'CST' yyyy", Locale.ENGLISH); try { SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); record.put(ModifyRecordConstant.NEWVALUE_KEY, sdf1.format(sdf.parse(newValueKey))); } catch (ParseException e) { LoggerHelper.err(getClass(), e.getMessage(), e); } } if (StringUtils.isNotBlank(oldValueKey)) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); record.put(ModifyRecordConstant.OLDVALUE_KEY, sdf1.format(sdf.parse(oldValueKey))); } catch (ParseException e) { e.printStackTrace(); } } } else if ("currencyType".equals(filedName)) { if (StringUtils.isNotBlank(newValueKey)) record.put(ModifyRecordConstant.NEWVALUE_KEY, currencyTypeServiceImpl.getByIdAndLocale(newValueKey, locale).getI18nName()); if (StringUtils.isNotBlank(oldValueKey)) record.put(ModifyRecordConstant.OLDVALUE_KEY, currencyTypeServiceImpl.getByIdAndLocale(oldValueKey, locale).getI18nName()); } else if ("type".equals(filedName)) { //? if (StringUtils.isNotBlank(newValueKey)) record.put(ModifyRecordConstant.NEWVALUE_KEY, MessageHelper.getMessage("customer.attachment.type." + newValueKey, locale)); if (StringUtils.isNotBlank(oldValueKey)) record.put(ModifyRecordConstant.OLDVALUE_KEY, MessageHelper.getMessage("customer.attachment.type." + oldValueKey, locale)); } }
From source file:com.edgenius.wiki.render.filter.MacroFilter.java
public String filter(String input, final RenderContext context) { final List<Region> pairRegion = new ArrayList<Region>(); String result = singleMacroProvider.replaceByTokenVisitor(input, new TokenVisitor<Matcher>() { public void handleMatch(StringBuffer buffer, Matcher matcher) { handleMacro(false, buffer, matcher.toMatchResult(), context, pairRegion, null); }/*from www .j a v a 2s . co m*/ }); // scenarios (s = start, u = unknown - no any attributes in macro, so could be start or end): // A B B A - B is process by recursive inside A // A B A B - B is treat as invalid - ignore // Au Au Au Au - First 2 Au is paired, Last 2 Au is paired // As1 As2 Au2 Au1 - OK, this case is special, which can not process by original Paired Regex patter // because it will treat it as As1 and Au2 as paired, but ignore As2 and Au1. // Here just try to resolve this problem. //exceptions // As1 As2 Au1 - then As1 can not find pair - no processed , but As2 could match with Au1 int size = pairRegion.size(); if (size > 0) { StringBuffer inputBuf = new StringBuffer(result); for (int idx = 0; idx < size; idx++) { Region reg = pairRegion.get(idx); int deep = 0; Region pair = null; //looking for pairs... for (int chIdx = idx + 1; chIdx < size; chIdx++) { Region next = pairRegion.get(chIdx); if (StringUtils.equalsIgnoreCase(reg.getContent(), next.getContent())) { //start is unknown (no attribute), then end must be unknown if (MACRO_REGION_KEY_UNKNOWN.equals(reg.getKey()) && MACRO_REGION_KEY_UNKNOWN.equals(next.getKey())) { //matched pair = next; //skip all internal node - which is handle by embedded recursive idx = chIdx; break; } if (MACRO_REGION_KEY_START.equals(reg.getKey()) && MACRO_REGION_KEY_UNKNOWN.equals(next.getKey())) { if (deep == 0) { //matched; pair = next; //skip all internal node - which is handle by embedded recursive idx = chIdx; break; } else { //just another inner same name macro matched, deep minus deep--; } } if (MACRO_REGION_KEY_START.equals(next.getKey())) { //ok, it gets another start, in 4th scenarios - then add deep deep++; } } } //ok, success find paired if (pair != null) { CharSequence macroContent = inputBuf.subSequence(reg.getStart(), pair.getEnd()); //for example, {font:size=12}abc{font}, the value is start markup string,i.e., {font:size=12} //so far, this text is useful to display markup if it has errors - which need highlight and with hover text final String pairStartMarkup = pair.getBody(); result = pairedMacroProvider.replaceByTokenVisitor(macroContent, new TokenVisitor<Matcher>() { public void handleMatch(StringBuffer buffer, Matcher matcher) { handleMacro(true, buffer, matcher.toMatchResult(), context, null, pairStartMarkup); } }); reg.setBody(result); reg.setSubRegion(pair); reg.setKey(MACRO_REGION_KEY_PROCESSED); } } //reverse, and replace input by region processed string (region.getBody()) for (int idx = size - 1; idx >= 0; idx--) { Region reg = pairRegion.get(idx); if (!MACRO_REGION_KEY_PROCESSED.equals(reg.getKey())) continue; inputBuf.replace(reg.getStart(), reg.getSubRegion().getEnd(), reg.getBody()); } return inputBuf.toString(); } return result; }
From source file:com.edgenius.wiki.render.filter.MacroFilter.java
private void resetRegion(final int initPos, final CharSequence input, final List<Region> list) { final List<Region> pairRegions = new ArrayList<Region>(); singleMacroProvider.replaceByTokenVisitor(input, new TokenVisitor<Matcher>() { public void handleMatch(StringBuffer buffer, Matcher result) { String macroName = result.group(1); if (macroName != null && !macroName.startsWith("$")) { Macro macro = macroMgr.getMacro(macroName); if (macro != null && macro.isPaired()) { String body = result.group(0); int start = result.start(0); int end = result.end(0); Region pair = new Region(start, end); //no parameter, then mark as unknown, otherwise, must be a start macro if (StringUtils.isBlank(result.group(2))) { pair.setKey(MACRO_REGION_KEY_UNKNOWN); } else { pair.setKey(MACRO_REGION_KEY_START); }//from www . j a v a2 s. com //just for temporary to remember the macro name... pair.setContent(macroName); pair.setBody(body); //sum to list pairRegions.add(pair); } } } }); int size = pairRegions.size(); if (size > 0) { StringBuffer inputBuf = new StringBuffer(input); for (int idx = 0; idx < size; idx++) { Region reg = pairRegions.get(idx); int deep = 0; Region pair = null; //looking for pairs... for (int chIdx = idx + 1; chIdx < size; chIdx++) { Region next = pairRegions.get(chIdx); if (StringUtils.equalsIgnoreCase(reg.getContent(), next.getContent())) { //start is unknown (no attribute), then end must be unknown if (MACRO_REGION_KEY_UNKNOWN.equals(reg.getKey()) && MACRO_REGION_KEY_UNKNOWN.equals(next.getKey())) { //matched pair = next; //skip all internal node - which is handle by embedded recursive idx = chIdx; break; } if (MACRO_REGION_KEY_START.equals(reg.getKey()) && MACRO_REGION_KEY_UNKNOWN.equals(next.getKey())) { if (deep == 0) { //matched; pair = next; //skip all internal node - which is handle by embedded recursive idx = chIdx; break; } else { //just another inner same name macro matched, deep minus deep--; } } if (MACRO_REGION_KEY_START.equals(next.getKey())) { //ok, it gets another start, in 4th scenarios - then add deep deep++; } } } //ok, success find paired if (pair != null) { int start = initPos + reg.getStart(); int end = initPos + pair.getEnd(); int contentStart = initPos + reg.getEnd(); int contentEnd = initPos + pair.getStart(); String macroName = reg.getContent(); Macro macro = macroMgr.getMacro(macroName); boolean immutable = macro instanceof ImmutableContentMacro; list.add(new Region(MacroFilter.this, immutable, start, end, contentStart, contentEnd)); if (macro.isProcessEmbedded() && (end > start)) { resetRegion(contentStart, inputBuf.subSequence(contentStart - initPos, contentEnd - initPos), list); } } } } }