List of usage examples for java.lang StringBuffer setCharAt
@Override public synchronized void setCharAt(int index, char ch)
From source file:org.mortbay.jetty.webapp.WebAppContext.java
/** * Create a canonical name for a webapp tmp directory. * The form of the name is:/*from ww w .j a v a2s . c o m*/ * "Jetty_"+host+"_"+port+"__"+resourceBase+"_"+context+"_"+virtualhost+base36 hashcode of whole string * * host and port uniquely identify the server * context and virtual host uniquely identify the webapp * @return */ private String getCanonicalNameForWebAppTmpDir() { StringBuffer canonicalName = new StringBuffer(); canonicalName.append("Jetty"); //get the host and the port from the first connector Connector[] connectors = getServer().getConnectors(); //Get the host canonicalName.append("_"); String host = (connectors == null || connectors[0] == null ? "" : connectors[0].getHost()); if (host == null) host = "0.0.0.0"; canonicalName.append(host.replace('.', '_')); //Get the port canonicalName.append("_"); //try getting the real port being listened on int port = (connectors == null || connectors[0] == null ? 0 : connectors[0].getLocalPort()); //if not available (eg no connectors or connector not started), //try getting one that was configured. if (port < 0) port = connectors[0].getPort(); canonicalName.append(port); //Resource base canonicalName.append("_"); try { Resource resource = super.getBaseResource(); if (resource == null) { if (_war == null || _war.length() == 0) resource = Resource.newResource(getResourceBase()); // Set dir or WAR resource = Resource.newResource(_war); } String tmp = URIUtil.decodePath(resource.getURL().getPath()); if (tmp.endsWith("/")) tmp = tmp.substring(0, tmp.length() - 1); if (tmp.endsWith("!")) tmp = tmp.substring(0, tmp.length() - 1); //get just the last part which is the filename int i = tmp.lastIndexOf("/"); canonicalName.append(tmp.substring(i + 1, tmp.length())); } catch (Exception e) { Log.warn("Can't generate resourceBase as part of webapp tmp dir name", e); } //Context name canonicalName.append("_"); String contextPath = getContextPath(); contextPath = contextPath.replace('/', '_'); contextPath = contextPath.replace('\\', '_'); canonicalName.append(contextPath); //Virtual host (if there is one) canonicalName.append("_"); String[] vhosts = getVirtualHosts(); canonicalName.append((vhosts == null || vhosts[0] == null ? "" : vhosts[0])); //base36 hash of the whole string for uniqueness String hash = Integer.toString(canonicalName.toString().hashCode(), 36); canonicalName.append("_"); canonicalName.append(hash); // sanitize for (int i = 0; i < canonicalName.length(); i++) { char c = canonicalName.charAt(i); if (!Character.isJavaIdentifierPart(c)) canonicalName.setCharAt(i, '.'); } return canonicalName.toString(); }
From source file:org.apache.poi.ss.format.CellNumberFormatter.java
/** {@inheritDoc} */ public void formatValue(StringBuffer toAppendTo, Object valueObject) { double value = ((Number) valueObject).doubleValue(); value *= scale;//from w w w .j av a 2 s. co m // the '-' sign goes at the front, always, so we pick it out boolean negative = value < 0; if (negative) value = -value; // Split out the fractional part if we need to print a fraction double fractional = 0; if (slash != null) { if (improperFraction) { fractional = value; value = 0; } else { fractional = value % 1.0; //noinspection SillyAssignment value = (long) value; } } Set<StringMod> mods = new TreeSet<>(); StringBuffer output = new StringBuffer(desc); if (exponent != null) { writeScientific(value, output, mods); } else if (improperFraction) { writeFraction(value, null, fractional, output, mods); } else { StringBuffer result = new StringBuffer(); Formatter f = new Formatter(result); f.format(LOCALE, printfFmt, value); if (numerator == null) { writeFractional(result, output); writeInteger(result, output, integerSpecials, mods, integerCommas); } else { writeFraction(value, result, fractional, output, mods); } } // Now strip out any remaining '#'s and add any pending text ... ListIterator<Special> it = specials.listIterator(); Iterator<StringMod> changes = mods.iterator(); StringMod nextChange = (changes.hasNext() ? changes.next() : null); int adjust = 0; BitSet deletedChars = new BitSet(); // records chars already deleted while (it.hasNext()) { Special s = it.next(); int adjustedPos = s.pos + adjust; if (!deletedChars.get(s.pos) && output.charAt(adjustedPos) == '#') { output.deleteCharAt(adjustedPos); adjust--; deletedChars.set(s.pos); } while (nextChange != null && s == nextChange.special) { int lenBefore = output.length(); int modPos = s.pos + adjust; int posTweak = 0; switch (nextChange.op) { case StringMod.AFTER: // ignore adding a comma after a deleted char (which was a '#') if (nextChange.toAdd.equals(",") && deletedChars.get(s.pos)) break; posTweak = 1; //noinspection fallthrough case StringMod.BEFORE: output.insert(modPos + posTweak, nextChange.toAdd); break; case StringMod.REPLACE: int delPos = s.pos; // delete starting pos in original coordinates if (!nextChange.startInclusive) { delPos++; modPos++; } // Skip over anything already deleted while (deletedChars.get(delPos)) { delPos++; modPos++; } int delEndPos = nextChange.end.pos; // delete end point in original if (nextChange.endInclusive) delEndPos++; int modEndPos = delEndPos + adjust; // delete end point in current if (modPos < modEndPos) { if (nextChange.toAdd == "") output.delete(modPos, modEndPos); else { char fillCh = nextChange.toAdd.charAt(0); for (int i = modPos; i < modEndPos; i++) output.setCharAt(i, fillCh); } deletedChars.set(delPos, delEndPos); } break; default: throw new IllegalStateException("Unknown op: " + nextChange.op); } adjust += output.length() - lenBefore; if (changes.hasNext()) nextChange = changes.next(); else nextChange = null; } } // Finally, add it to the string if (negative) toAppendTo.append('-'); toAppendTo.append(output); }
From source file:de.rrze.idmone.utils.jpwgen.PwGenerator.java
/** * The real password generation is performed in this method * // w w w .j a va 2 s .co m * @param size * the length of the password * @param pw_flags * the settings for the password * @return the newly created password */ private synchronized static String phonemes(int size, int pw_flags, Random random) { int c, i, len, flags, feature_flags; int prev, should_be; boolean first; String str; char ch; StringBuffer buf = new StringBuffer(); do { buf.delete(0, buf.length()); feature_flags = pw_flags; c = 0; prev = 0; should_be = 0; first = true; should_be = random.nextBoolean() ? VOWEL : CONSONANT; while (c < size) { i = random.nextInt(PW_ELEMENTS.length); str = PW_ELEMENTS[i].getValue(); len = str.length(); flags = PW_ELEMENTS[i].getType(); /* Filter on the basic type of the next element */ if ((flags & should_be) == 0) { continue; } /* Handle the NOT_FIRST flag */ if (first && ((flags & NOT_FIRST) != 0)) continue; /* Don't allow VOWEL followed a Vowel/Dipthong pair */ if (((prev & VOWEL) != 0) && ((flags & VOWEL) != 0) && ((flags & DIPTHONG) != 0)) continue; /* Don't allow us to overflow the buffer */ if (len > size - c) continue; /* * OK, we found an element which matches our criteria, let's do * it! */ buf.append(str); c += len; /* Handle the AMBIGUOUS flag */ if ((pw_flags & PW_AMBIGUOUS) != 0) { int k = -1; for (int j = 0; j < PW_AMBIGUOUS_SYMBOLS.length(); j++) { k = buf.indexOf(String.valueOf(PW_AMBIGUOUS_SYMBOLS.charAt(j))); if (k != -1) break; } if (k != -1) { buf.delete(k, buf.length()); c = buf.length(); } } /* Time to stop? */ if (c >= size) { // System.out.println("BREAK 1: "+c + " - "+size); break; } /* * Handle PW_DIGITS */ if ((pw_flags & PW_DIGITS) != 0) { if (!first && (random.nextInt(10) < 3)) { do { ch = (new Integer(random.nextInt(10))).toString().charAt(0); } while (((pw_flags & PW_AMBIGUOUS) != 0) && (PW_AMBIGUOUS_SYMBOLS.indexOf(ch) != -1)); c++; buf = buf.append(ch); feature_flags &= ~PW_DIGITS; first = true; prev = 0; should_be = random.nextBoolean() ? VOWEL : CONSONANT; continue; } } /* Handle PW_SYMBOLS */ if ((pw_flags & PW_SYMBOLS) != 0) { if (!first && (random.nextInt(10) < 2)) { do { ch = PW_SPECIAL_SYMBOLS.charAt(random.nextInt(PW_SPECIAL_SYMBOLS.length())); } while (((pw_flags & PW_AMBIGUOUS) != 0) && (PW_AMBIGUOUS_SYMBOLS.indexOf(ch) != -1)); c++; buf = buf.append(ch); feature_flags &= ~PW_SYMBOLS; } } else if ((pw_flags & PW_SYMBOLS_REDUCED) != 0) { if (!first && (random.nextInt(10) < 2)) { do { ch = PW_SPECIAL_SYMBOLS_REDUCED .charAt(random.nextInt(PW_SPECIAL_SYMBOLS_REDUCED.length())); } while (((pw_flags & PW_AMBIGUOUS) != 0) && (PW_AMBIGUOUS_SYMBOLS.indexOf(ch) != -1)); c++; buf = buf.append(ch); feature_flags &= ~PW_SYMBOLS_REDUCED; } } /* Handle PW_UPPERS */ if ((pw_flags & PW_UPPERS) != 0) { if ((first || ((flags & CONSONANT) != 0)) && (random.nextInt(10) < 2)) { int lastChar = buf.length() - 1; buf.setCharAt(lastChar, Character.toUpperCase(buf.charAt(lastChar))); feature_flags &= ~PW_UPPERS; } } /* * OK, figure out what the next element should be */ if (should_be == CONSONANT) { should_be = VOWEL; } else { /* should_be == VOWEL */ if (((prev & VOWEL) != 0) || ((flags & DIPTHONG) != 0) || (random.nextInt(10) > 3)) should_be = CONSONANT; else should_be = VOWEL; } prev = flags; first = false; } } while ((feature_flags & (PW_UPPERS | PW_DIGITS | PW_SYMBOLS | PW_SYMBOLS_REDUCED)) != 0); return buf.toString(); }
From source file:org.zkoss.poi.ss.format.CellNumberFormatter.java
/** {@inheritDoc} */ public void formatValue(StringBuffer toAppendTo, Object valueObject) { double value = ((Number) valueObject).doubleValue(); value *= scale;/* ww w . ja va 2 s. c om*/ // For negative numbers: // - If the cell format has a negative number format, this method // is called with a positive value and the number format has // the negative formatting required, e.g. minus sign or brackets. // - If the cell format does not have a negative number format, // this method is called with a negative value and the number is // formatted with a minus sign at the start. boolean negative = value < 0; if (negative) value = -value; // Split out the fractional part if we need to print a fraction double fractional = 0; if (slash != null) { if (improperFraction) { fractional = value; value = 0; } else { fractional = value % 1.0; //noinspection SillyAssignment value = (long) value; } } Set<StringMod> mods = new TreeSet<StringMod>(); StringBuffer output = new StringBuffer(desc); if (exponent != null) { writeScientific(value, output, mods); } else if (improperFraction) { writeFraction(value, null, fractional, output, mods); } else { StringBuffer result = new StringBuffer(); Formatter f = new Formatter(result, locale); //ZSS-68 f.format(locale, printfFmt, value); //ZSS-68 if (numerator == null) { writeFractional(result, output); writeInteger(result, output, integerSpecials, mods, integerCommas, false); } else { writeFraction(value, result, fractional, output, mods); } } // Now strip out any remaining '#'s and add any pending text ... ListIterator<Special> it = specials.listIterator(); Iterator<StringMod> changes = mods.iterator(); StringMod nextChange = (changes.hasNext() ? changes.next() : null); int adjust = 0; BitSet deletedChars = new BitSet(); // records chars already deleted final String groupSeparator = "" + Formatters.getGroupingSeparator(locale); //ZSS-68 while (it.hasNext()) { Special s = it.next(); int adjustedPos = s.pos + adjust; if (!deletedChars.get(s.pos) && output.charAt(adjustedPos) == '#') { output.deleteCharAt(adjustedPos); adjust--; deletedChars.set(s.pos); } while (nextChange != null && s == nextChange.special) { int lenBefore = output.length(); int modPos = s.pos + adjust; int posTweak = 0; switch (nextChange.op) { case StringMod.AFTER: // ignore adding a comma after a deleted char (which was a '#') if (nextChange.toAdd.equals(groupSeparator) && deletedChars.get(s.pos)) //20110321, henrichen@zkoss.org: respect current locale break; posTweak = 1; //noinspection fallthrough case StringMod.BEFORE: output.insert(modPos + posTweak, nextChange.toAdd); break; case StringMod.REPLACE: int delPos = s.pos; // delete starting pos in original coordinates if (!nextChange.startInclusive) { delPos++; modPos++; } // Skip over anything already deleted while (deletedChars.get(delPos)) { delPos++; modPos++; } int delEndPos = nextChange.end.pos; // delete end point in original if (nextChange.endInclusive) delEndPos++; int modEndPos = delEndPos + adjust; // delete end point in current if (modPos < modEndPos) { if (nextChange.toAdd == "") output.delete(modPos, modEndPos); else { char fillCh = nextChange.toAdd.charAt(0); for (int i = modPos; i < modEndPos; i++) output.setCharAt(i, fillCh); } deletedChars.set(delPos, delEndPos); } break; default: throw new IllegalStateException("Unknown op: " + nextChange.op); } adjust += output.length() - lenBefore; if (changes.hasNext()) nextChange = changes.next(); else nextChange = null; } } // Finally, add it to the string if (negative) toAppendTo.append('-'); toAppendTo.append(output); }
From source file:edu.harvard.iq.dvn.core.web.admin.OptionsPage.java
private static boolean doValidate(Object value) { boolean valid = false; String address = value.toString(); // first, assume it's a domain name if (address.startsWith("*.")) { StringBuffer sb = new StringBuffer(address); sb.setCharAt(0, 'a'); address = sb.toString();/*w w w .ja va2s .c om*/ } valid = validateDomainName(address); if (!valid) { // Try to validate it as an ip address String ipAddress = value.toString(); // for the purposes of validation, if the string ends in ".*", // replace it with dummy data for the validator. if (ipAddress.endsWith(".*")) { StringBuffer sb = new StringBuffer(ipAddress); sb.setCharAt(ipAddress.length() - 1, '1'); ipAddress = sb.toString(); // if necessary, add dummy values to the end of the string, // so it will pass validation. String[] splitStrings = ipAddress.split("\\."); if (splitStrings.length == 2) { ipAddress += ".1.1"; } else if (splitStrings.length == 3) { ipAddress += ".1"; } } InetAddressValidator val = InetAddressValidator.getInstance(); valid = val.isValid(ipAddress); } return valid; }
From source file:UnicodeUtil.java
private static String composeHangul(String source) { final int firstLeadingConsonant = 0x1100; final int firstMedialVowel = 0x1161; final int firstTrailingConsonant = 0x11A7; final int numberOfLeadingConsonants = 19; final int numberOfMedialVowels = 21; final int numberOfTrailingConsonants = 28; final int numberOfFinalPairs = numberOfMedialVowels * numberOfTrailingConsonants; final int numberOfSyllables = numberOfLeadingConsonants * numberOfFinalPairs; final int length = source.length(); if (length == 0) return ""; StringBuffer result = new StringBuffer(length); char previous = source.charAt(0); result.append(previous);//w ww . j av a 2 s.c o m for (int i = 1; i < length; ++i) { char c = source.charAt(i); int leadingConsonant = previous - firstLeadingConsonant; if (0 <= leadingConsonant && leadingConsonant < numberOfLeadingConsonants) { int medialVowel = c - firstMedialVowel; if (medialVowel >= 0 && medialVowel < numberOfMedialVowels) { previous = (char) (FIRST_HANGUL_SYLLABLE + (leadingConsonant * numberOfMedialVowels + medialVowel) * numberOfTrailingConsonants); result.setCharAt(result.length() - 1, previous); continue; } } int syllable = previous - FIRST_HANGUL_SYLLABLE; if (syllable >= 0 && syllable < numberOfSyllables && (syllable % numberOfTrailingConsonants) == 0) { int trailingConsonant = c - firstTrailingConsonant; if (trailingConsonant >= 0 && trailingConsonant <= numberOfTrailingConsonants) { previous += trailingConsonant; result.setCharAt(result.length() - 1, previous); continue; } } previous = c; result.append(c); } return result.toString(); }
From source file:com.arksoft.epamms.ZGlobal1_Operation.java
public int SetStringUpperLowerCase(StringBuilder sbName) { String string;//from ww w . ja v a2 s. co m boolean bSuffix = false; int nBlankFound = 0; @SuppressWarnings("unused") int nLth; int k; int j; // Eliminate leading and trailing blanks. string = sbName.toString(); string = string.trim(); // Force first character to be upper case StringBuffer sb = new StringBuffer(string.toLowerCase()); // force string to lower case sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); for (k = 1; k < sb.length(); k++) { // Eliminate multiple consecutive blanks. if (sb.charAt(k) == ' ') { j = k; while (sb.charAt(j + 1) == ' ') j++; if (j > k) sb.delete(k + 1, j); } else // if ( sb.charAt( k ) != ' ' ) { if (sb.charAt(k - 1) == ' ') { nBlankFound++; char ch = Character.toUpperCase(sb.charAt(k)); sb.setCharAt(k, ch); if (ch == 'I' || ch == 'V') bSuffix = true; else bSuffix = false; } else { if (nBlankFound > 1 && bSuffix) // checking for II or III or IV or V or VI or VII or VIII { if ((sb.charAt(k) == 'i' || sb.charAt(k) == 'v') && (sb.charAt(k + 1) == '\0' || sb.charAt(k + 1) == 'i' || sb.charAt(k + 1) == 'v')) { sb.setCharAt(k, Character.toUpperCase(sb.charAt(k))); } else bSuffix = false; } else { bSuffix = false; // can't start with suffix } } } } zstrcpy(sbName, sb.toString()); return sbName.length(); }
From source file:org.pentaho.di.ui.spoon.Spoon.java
public boolean messageBox(final String message, final String text, final boolean allowCancel, final int type) { final StringBuffer answer = new StringBuffer("N"); display.syncExec(new Runnable() { @Override/* w ww. j av a2 s . c om*/ public void run() { int flags = SWT.OK; if (allowCancel) { flags |= SWT.CANCEL; } switch (type) { case Const.INFO: flags |= SWT.ICON_INFORMATION; break; case Const.ERROR: flags |= SWT.ICON_ERROR; break; case Const.WARNING: flags |= SWT.ICON_WARNING; break; default: break; } MessageBox mb = new MessageBox(shell, flags); // Set the Body Message mb.setMessage(message); // Set the title Message mb.setText(text); if (mb.open() == SWT.OK) { answer.setCharAt(0, 'Y'); } } }); return "Y".equalsIgnoreCase(answer.toString()); }