Example usage for java.lang StringBuffer charAt

List of usage examples for java.lang StringBuffer charAt

Introduction

In this page you can find the example usage for java.lang StringBuffer charAt.

Prototype

@Override
public synchronized char charAt(int index) 

Source Link

Usage

From source file:com.globalsight.everest.webapp.pagehandler.edit.inctxrv.EditorPageHandler.java

private String removeSpecialChars(String segment) {
    if (segment == null) {
        return "";
    }//  w  w w  . ja  v  a 2s .  c  o  m

    StringBuffer sb = new StringBuffer();

    for (int i = 0; i < segment.length(); i++) {
        char ccc = segment.charAt(i);

        if (ccc == 9632) {
            continue;
        }

        if (i > 0) {
            char lastChar = sb.length() > 0 ? sb.charAt(sb.length() - 1) : 'N';
            // ignore tab
            if (ccc == '\t' && lastChar == ' ') {
                continue;
            }

            // ignore Hyphen char
            if (i < segment.length() - 1) {
                char nextChar = segment.charAt(i + 1);
                if (ccc == 173 && lastChar == ' ' && Character.isLetter(nextChar)) {
                    continue;
                }
            }
        }

        sb.append(ccc);
    }

    String result = sb.toString().trim();
    result = StringUtil.replace(result, "\t", " ");
    result = StringUtil.replaceWithRE(result, "[ \t]{2,}", " ");

    return result;
}

From source file:org.zkoss.poi.ss.format.CellNumberFormatter.java

private void writeInteger(StringBuffer result, StringBuffer output, List<Special> numSpecials,
        Set<StringMod> mods, boolean showCommas, boolean fraction) {//20100924, henrichen@zkoss.org: fraction has special treatment about zero
    //20100914, henrichen@zkoss.org: repect the current locale
    final char comma = Formatters.getGroupingSeparator(locale);
    final String commaStr = "" + comma;
    final String dot = "" + Formatters.getDecimalSeparator(locale);
    int pos = result.indexOf(dot) - 1;
    if (pos < 0) {
        if (exponent != null && numSpecials == integerSpecials)
            pos = result.indexOf("E") - 1;
        else//from  w ww.  j  a va2  s . c  o  m
            pos = result.length() - 1;
    }

    int strip;
    for (strip = 0; strip < pos; strip++) {
        char resultCh = result.charAt(strip);
        if (resultCh != '0' && resultCh != comma)
            break;
    }
    //20100924, henrichen@zkoss.org: handle all zero case
    final char posCh = !fraction && strip == pos && pos >= 0 ? result.charAt(pos) : '\000';
    final boolean allZeros = posCh == '0' || posCh == comma;

    ListIterator<Special> it = numSpecials.listIterator(numSpecials.size());
    boolean followWithComma = false;
    Special lastOutputIntegerDigit = null;
    int digit = 0;
    while (it.hasPrevious()) {
        char resultCh;
        if (pos >= 0)
            resultCh = result.charAt(pos);
        else {
            // If result is shorter than field, pretend there are leading zeros
            resultCh = '0';
        }
        Special s = it.previous();
        followWithComma = showCommas && digit > 0 && digit % 3 == 0;
        boolean zeroStrip = false;
        if (resultCh != '0' || s.ch == '0' || s.ch == '?' || pos >= strip) {
            zeroStrip = s.ch == '?' && (pos < strip || allZeros); //20100924, henrichen@zkoss.org: handle all zero case
            output.setCharAt(s.pos, (zeroStrip ? ' ' : resultCh));
            lastOutputIntegerDigit = s;
        }
        if (followWithComma) {
            //20100914, henrichen@zkoss.org: repect the current locale
            //mods.add(insertMod(s, zeroStrip ? " " : ",", StringMod.AFTER));
            mods.add(insertMod(s, zeroStrip ? " " : commaStr, StringMod.AFTER));
            followWithComma = false;
        }
        digit++;
        --pos;
    }
    StringBuffer extraLeadingDigits = new StringBuffer();
    if (pos >= 0) {
        // We ran out of places to put digits before we ran out of digits; put this aside so we can add it later
        ++pos; // pos was decremented at the end of the loop above when the iterator was at its end
        extraLeadingDigits = new StringBuffer(result.substring(0, pos));
        if (showCommas) {
            while (pos > 0) {
                if (digit > 0 && digit % 3 == 0)
                    //20100914, henrichen@zkoss.org: repect the current locale
                    //extraLeadingDigits.insert(pos, ',');
                    extraLeadingDigits.insert(pos, comma);
                digit++;
                --pos;
            }
        }
        mods.add(insertMod(lastOutputIntegerDigit, extraLeadingDigits, StringMod.BEFORE));
    }
}

From source file:net.sourceforge.myvd.inserts.jdbc.JdbcInsert.java

private void createSELECT(ArrayList<Attribute> attributes, StringBuffer buf) {
    Iterator<Attribute> it = attributes.iterator();

    boolean foundRDN = false;
    boolean foundAttrib = false;
    if (attributes.size() == 0) {
        buf.append(" * ");
        return;//w w  w . j  a v a 2 s . co  m
    }

    while (it.hasNext()) {
        foundAttrib = false;
        String attrib = it.next().getAttribute().getName();

        if (attrib.equalsIgnoreCase(this.rdn)) {
            foundRDN = true;
        }

        if (attrib.equalsIgnoreCase("*")) {
            buf.append("* ");
        } else {

            String ldap2dbVal = ldap2db.get(attrib.toLowerCase());
            if (ldap2dbVal != null) {
                buf.append(ldap2dbVal).append(' ');
                foundAttrib = true;
            } else {
                continue;
            }
        }

        if ((it.hasNext() || !foundRDN) && foundAttrib) {
            buf.append(',');
        }
    }

    if (!foundRDN) {
        buf.append(this.ldap2db.get(this.rdn.toLowerCase())).append(" ,");
    }

    if (!foundAttrib) {
        buf.setLength(buf.lastIndexOf(",") - 1);
    }

    if (buf.charAt(buf.length() - 1) == ',') {
        buf.setLength(buf.length() - 1);
    }

}

From source file:org.exist.http.SOAPServer.java

/**
 * Writes a parameter for an XQuery function call
 * //from  w  ww .  java  2 s  . co  m
 * @param paramType   The type of the Parameter (from the internal description of the XQWS)
 * @param paramCardinality The cardinality of the Parameter (from the internal description of the XQWS)
 * @param SOAPParam   The Node from the SOAP request for the Paremeter of the Function call from the Http Request 
 * 
 * @return A String representation of the parameter, suitable for use in the function call 
 */
private StringBuffer writeXQueryFunctionParameter(String paramType, int paramCardinality, Node nSOAPParam)
        throws XPathException {
    String prefix = new String();
    String postfix = prefix;

    //determine the type of the parameter
    final int type = Type.getType(paramType);
    final int isAtomic = (Type.subTypeOf(type, Type.ATOMIC)) ? 1 : ((Type.subTypeOf(type, Type.NODE)) ? -1 : 0);

    if (isAtomic >= 0) {
        if (isAtomic > 0 && type != Type.STRING) {
            final String typeName = Type.getTypeName(type);
            if (typeName != null) {
                prefix = typeName + "(\"";
                postfix = "\")";
            }
        } else {
            prefix = "\"";
            postfix = prefix;
        }
    }

    final StringBuffer param = new StringBuffer();

    //determine the cardinality of the parameter
    if (paramCardinality >= Cardinality.MANY) {
        //sequence
        param.append("(");

        final NodeList nlParamSequenceItems = nSOAPParam.getChildNodes();
        for (int i = 0; i < nlParamSequenceItems.getLength(); i++) {
            final Node nParamSeqItem = nlParamSequenceItems.item(i);
            if (nParamSeqItem.getNodeType() == Node.ELEMENT_NODE) {
                processParameterValue(param, nParamSeqItem, prefix, postfix, isAtomic);

                param.append(","); //seperator for next item in sequence
            }
        }

        //remove last superflurous seperator
        if (param.charAt(param.length() - 1) == ',') {
            param.deleteCharAt(param.length() - 1);
        }

        param.append(")");
    } else {
        processParameterValue(param, nSOAPParam, prefix, postfix, isAtomic);
    }

    return param;
}

From source file:org.infoglue.deliver.invokers.PageInvoker.java

private void generateExtensionBundles(Map<String, Set<String>> extensionBundles, String contentType,
        String targetElement) {//from  w  ww  . j a v  a 2 s. c o m
    Timer t = new Timer();

    Set<String> bundledSignatures = new HashSet<String>();

    Iterator<String> scriptExtensionBundlesIterator = extensionBundles.keySet().iterator();
    while (scriptExtensionBundlesIterator.hasNext()) {
        String bundleName = scriptExtensionBundlesIterator.next();
        if (logger.isInfoEnabled())
            logger.info("bundleName:" + bundleName);

        Set<String> scriptExtensionFileNames = extensionBundles.get(bundleName);

        if (scriptExtensionFileNames != null && scriptExtensionFileNames.size() > 0) {
            String scriptBundle = "";

            int i = 0;
            String filePath = CmsPropertyHandler.getDigitalAssetPath0();
            while (filePath != null) {
                try {
                    File extensionsDirectory = new File(filePath + File.separator + "extensions");
                    extensionsDirectory.mkdirs();

                    File extensionsBundleFile = new File(
                            filePath + File.separator + "extensions" + File.separator + bundleName + ".js");
                    if (contentType.equalsIgnoreCase("text/css"))
                        extensionsBundleFile = new File(filePath + File.separator + "extensions"
                                + File.separator + bundleName + ".css");

                    if (!extensionsBundleFile.exists()) {
                        if (logger.isInfoEnabled())
                            logger.info("No script - generating:" + bundleName);
                        if (scriptBundle.equals("")) {
                            Iterator<String> scriptExtensionFileNamesIterator = scriptExtensionFileNames
                                    .iterator();
                            while (scriptExtensionFileNamesIterator.hasNext()) {
                                String scriptExtensionFileName = scriptExtensionFileNamesIterator.next();
                                if (logger.isInfoEnabled())
                                    logger.info("scriptExtensionFileName:" + scriptExtensionFileName);
                                try {
                                    File file = new File(filePath + File.separator + scriptExtensionFileName);
                                    String signature = "" + file.getName() + "_" + file.length();
                                    if (logger.isInfoEnabled())
                                        logger.info("Checking file:" + filePath + File.separator
                                                + scriptExtensionFileName);

                                    if (file.exists() && !bundledSignatures.contains(signature)) {
                                        StringBuffer content = new StringBuffer(
                                                FileHelper.getFileAsStringOpt(file));
                                        //Wonder what is the best signature..
                                        bundledSignatures.add(signature);

                                        //If CSS we should change url:s to point to the original folder
                                        if (contentType.equalsIgnoreCase("text/css")) {
                                            if (logger.isInfoEnabled())
                                                logger.info("contentType:" + contentType);
                                            String extensionPath = file.getPath().substring(
                                                    extensionsDirectory.getPath().length() + 1,
                                                    file.getPath().lastIndexOf("/") + 1);
                                            if (logger.isInfoEnabled())
                                                logger.info("extensionPath:" + extensionPath);

                                            int urlStartIndex = content.indexOf("url(");
                                            while (urlStartIndex > -1) {
                                                if (content.charAt(urlStartIndex + 4) == '"'
                                                        || content.charAt(urlStartIndex + 4) == '\'')
                                                    content.insert(urlStartIndex + 5, extensionPath);
                                                else
                                                    content.insert(urlStartIndex + 4, extensionPath);
                                                urlStartIndex = content.indexOf("url(",
                                                        urlStartIndex + extensionPath.length());
                                            }
                                        }
                                        //logger.info("transformed content:" + content.substring(0, 500));

                                        scriptBundle = scriptBundle + "\n\n" + content;
                                    } else {
                                        if (logger.isInfoEnabled())
                                            logger.info("Not adding:" + signature + " as " + file.exists() + ":"
                                                    + bundledSignatures.contains(signature));
                                    }
                                } catch (Exception e) {
                                    logger.warn("Error trying to parse file and bundle it ("
                                            + scriptExtensionFileName + "):" + e.getMessage());
                                }
                            }
                        }

                        if (logger.isInfoEnabled())
                            logger.info("scriptBundle:" + scriptBundle.length());
                        if (scriptBundle != null && !scriptBundle.equals("")) {
                            if (contentType.equalsIgnoreCase("text/javascript")) {
                                try {
                                    JSMin jsmin = new JSMin(new ByteArrayInputStream(scriptBundle.getBytes()),
                                            new FileOutputStream(extensionsBundleFile));
                                    jsmin.jsmin();
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                            } else {
                                FileHelper.writeToFile(extensionsBundleFile, scriptBundle, false);
                            }
                            if (logger.isInfoEnabled())
                                logger.info("extensionsBundleFile:" + extensionsBundleFile.length());
                        }
                    }

                    i++;
                    filePath = CmsPropertyHandler.getProperty("digitalAssetPath." + i);
                } catch (Exception e) {
                    logger.warn("Error trying to write bundled scripts:" + e.getMessage());
                }
            }
            try {
                SiteNodeVO siteNodeVO = NodeDeliveryController.getNodeDeliveryController(deliveryContext)
                        .getSiteNodeVO(getDatabase(), getTemplateController().getSiteNodeId());
                String dnsName = CmsPropertyHandler.getWebServerAddress();
                if (siteNodeVO != null) {
                    RepositoryVO repositoryVO = RepositoryController.getController()
                            .getRepositoryVOWithId(siteNodeVO.getRepositoryId(), getDatabase());
                    if (repositoryVO.getDnsName() != null && !repositoryVO.getDnsName().equals(""))
                        dnsName = repositoryVO.getDnsName();
                }

                String bundleUrl = "";
                String bundleUrlTag = "";

                if (contentType.equalsIgnoreCase("text/javascript")) {
                    bundleUrl = URLComposer.getURLComposer().composeDigitalAssetUrl(dnsName, "extensions",
                            bundleName + ".js", deliveryContext);
                    bundleUrlTag = "<script type=\"text/javascript\" src=\"" + bundleUrl + "\"></script>";
                } else if (contentType.equalsIgnoreCase("text/css")) {
                    bundleUrl = URLComposer.getURLComposer().composeDigitalAssetUrl(dnsName, "extensions",
                            bundleName + ".css", deliveryContext);
                    bundleUrlTag = "<link href=\"" + bundleUrl + "\" rel=\"stylesheet\" type=\"text/css\" />";
                }

                if (targetElement.equalsIgnoreCase("head"))
                    this.getTemplateController().getDeliveryContext().getHtmlHeadItems().add(bundleUrlTag);
                else
                    this.getTemplateController().getDeliveryContext().getHtmlBodyEndItems().add(bundleUrlTag);
            } catch (Exception e) {
                logger.warn("Error trying  get assetBaseUrl:" + e.getMessage());
            }
        }

    }
    if (logger.isInfoEnabled())
        t.printElapsedTime("Generating bundles took");
}

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;//  ww w .ja  v 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:com.sun.socialsite.util.Utilities.java

/**
 * Need need to get rid of any user-visible HTML tags once all text has been
 * removed such as &lt;BR&gt;. This sounds like a better approach than removing
 * all HTML tags and taking the chance to leave some tags un-closed.
 *
 * WARNING: this method has serious performance problems a
 *
 * @author Alexis Moussine-Pouchkine (alexis.moussine-pouchkine@france.sun.com)
 * @author Lance Lavandowska//from ww w .  j av a2  s. c om
 * @param str the String object to modify
 * @return the new String object without the HTML "visible" tags
 */
private static String removeVisibleHTMLTags(String str) {
    str = stripLineBreaks(str);
    StringBuffer result = new StringBuffer(str);
    StringBuffer lcresult = new StringBuffer(str.toLowerCase());

    // <img should take care of smileys
    String[] visibleTags = { "<img" }; // are there others to add?
    int stringIndex;
    for (int j = 0; j < visibleTags.length; j++) {
        while ((stringIndex = lcresult.indexOf(visibleTags[j])) != -1) {
            if (visibleTags[j].endsWith(">")) {
                result.delete(stringIndex, stringIndex + visibleTags[j].length());
                lcresult.delete(stringIndex, stringIndex + visibleTags[j].length());
            } else {
                // need to delete everything up until next closing '>', for <img for instance
                int endIndex = result.indexOf(">", stringIndex);
                if (endIndex > -1) {
                    // only delete it if we find the end!  If we don't the HTML may be messed up, but we
                    // can't safely delete anything.
                    result.delete(stringIndex, endIndex + 1);
                    lcresult.delete(stringIndex, endIndex + 1);
                }
            }
        }
    }

    // TODO:  This code is buggy by nature.  It doesn't deal with nesting of tags properly.
    // remove certain elements with open & close tags
    String[] openCloseTags = { "li", "a", "div", "h1", "h2", "h3", "h4" }; // more ?
    for (int j = 0; j < openCloseTags.length; j++) {
        // could this be better done with a regular expression?
        String closeTag = "</" + openCloseTags[j] + ">";
        int lastStringIndex = 0;
        while ((stringIndex = lcresult.indexOf("<" + openCloseTags[j], lastStringIndex)) > -1) {
            lastStringIndex = stringIndex;
            // Try to find the matching closing tag  (ignores possible nesting!)
            int endIndex = lcresult.indexOf(closeTag, stringIndex);
            if (endIndex > -1) {
                // If we found it delete it.
                result.delete(stringIndex, endIndex + closeTag.length());
                lcresult.delete(stringIndex, endIndex + closeTag.length());
            } else {
                // Try to see if it is a self-closed empty content tag, i.e. closed with />.
                endIndex = lcresult.indexOf(">", stringIndex);
                int nextStart = lcresult.indexOf("<", stringIndex + 1);
                if (endIndex > stringIndex && lcresult.charAt(endIndex - 1) == '/'
                        && (endIndex < nextStart || nextStart == -1)) {
                    // Looks like it, so remove it.
                    result.delete(stringIndex, endIndex + 1);
                    lcresult.delete(stringIndex, endIndex + 1);

                }
            }
        }
    }

    return result.toString();
}

From source file:architecture.common.util.TextUtils.java

private final static void linkURL(StringBuffer str, String target) {
    String urlToDisplay;// w  w  w.j a  v  a 2 s  . c  o  m

    int lastEndIndex = -1; // Stores the index position, within the whole
    // string, of the ending char of the last URL
    // found.

    String targetString = ((target == null) || (target.trim().length() == 0)) ? ""
            : (" target=\"" + target.trim() + '\"');

    while (true) {
        int linkStartIndex = getStartUrl(str, lastEndIndex);

        // if no more links found - then end the loop
        if (linkStartIndex == -1) {
            break;
        } else {
            // Get the whole URL...
            // We move forward and add each character to the URL string
            // until we encounter
            // an invalid URL character (we assume that the URL ends there).
            int linkEndIndex = linkStartIndex;
            String urlStr = "";

            while (true) {
                // if char at linkEndIndex is '&' then we look at the next 4
                // chars
                // to see if they make up "&amp;" altogether. This is the
                // html coded
                // '&' and will pretty much stuff up an otherwise valid link
                // becos of the ';'.
                // We therefore have to remove it before proceeding...
                if (str.charAt(linkEndIndex) == '&') {
                    if (((linkEndIndex + 6) <= str.length())
                            && "&quot;".equals(str.substring(linkEndIndex, linkEndIndex + 6))) {
                        break;
                    } else if (((linkEndIndex + 5) <= str.length())
                            && "&amp;".equals(str.substring(linkEndIndex, linkEndIndex + 5))) {
                        str.replace(linkEndIndex, linkEndIndex + 5, "&");
                    }
                }

                if (isValidURLChar(str.charAt(linkEndIndex))) {
                    urlStr += str.charAt(linkEndIndex);
                    linkEndIndex++;

                    if (linkEndIndex == str.length()) { // Reached end of
                        // str...

                        break;
                    }
                } else {
                    break;
                }
            }

            // if the characters before the linkStart equal 'href="' then
            // don't link the url - CORE-44
            if (linkStartIndex >= 6) { // 6 = "href\"".length()

                String prefix = str.substring(linkStartIndex - 6, linkStartIndex);

                if ("href=\"".equals(prefix)) {
                    lastEndIndex = linkEndIndex;

                    continue;
                }
            }

            // if the characters after the linkEnd are '</a>' then this url
            // is probably already linked - CORE-44
            if (str.length() >= (linkEndIndex + 4)) { // 4 = "</a>".length()

                String suffix = str.substring(linkEndIndex, linkEndIndex + 4);

                if ("</a>".equals(suffix)) {
                    lastEndIndex = linkEndIndex + 4;

                    continue;
                }
            }

            // Decrement linkEndIndex back by 1 to reflect the real ending
            // index position of the URL...
            linkEndIndex--;

            // If the last char of urlStr is a '.' we exclude it. It is most
            // likely a full stop and
            // we don't want that to be part of an url.
            while (true) {
                char lastChar = urlStr.charAt(urlStr.length() - 1);

                if (lastChar == '.') {
                    urlStr = urlStr.substring(0, urlStr.length() - 1);
                    linkEndIndex--;
                } else {
                    break;
                }
            }

            // if the URL had a '(' before it, and has a ')' at the end,
            // trim the last ')' from the url
            // ie '(www.opensymphony.com)' => '(<a
            // href="http://www.openymphony.com/">www.opensymphony.com</a>)'
            char lastChar = urlStr.charAt(urlStr.length() - 1);

            if (lastChar == ')') {
                if ((linkStartIndex > 0) && ('(' == (str.charAt(linkStartIndex - 1)))) {
                    urlStr = urlStr.substring(0, urlStr.length() - 1);
                    linkEndIndex--;
                }
            } else if (lastChar == '\'') {
                if ((linkStartIndex > 0) && ('\'' == (str.charAt(linkStartIndex - 1)))) {
                    urlStr = urlStr.substring(0, urlStr.length() - 1);
                    linkEndIndex--;
                }
            }
            // perhaps we ended with '&gt;', '&lt;' or '&quot;'
            // We need to strip these
            // ie '&quot;www.opensymphony.com&quot;' => '&quot;<a
            // href="http://www.openymphony.com/">www.opensymphony.com</a>&quot;'
            // ie '&lt;www.opensymphony.com&gt;' => '&lt;<a
            // href="http://www.openymphony.com/">www.opensymphony.com</a>&gt;'
            else if (lastChar == ';') {
                // 6 = "&quot;".length()
                if ((urlStr.length() > 6) && "&quot;".equalsIgnoreCase(urlStr.substring(urlStr.length() - 6))) {
                    urlStr = urlStr.substring(0, urlStr.length() - 6);
                    linkEndIndex -= 6;
                }
                // 4 = "&lt;".length() || "&gt;".length()
                else if (urlStr.length() > 4) {
                    final String endingStr = urlStr.substring(urlStr.length() - 4);

                    if ("&lt;".equalsIgnoreCase(endingStr) || "&gt;".equalsIgnoreCase(endingStr)) {
                        urlStr = urlStr.substring(0, urlStr.length() - 4);
                        linkEndIndex -= 4;
                    }
                }
            }

            // we got the URL string, now we validate it and convert it into
            // a hyperlink...
            urlToDisplay = htmlEncode(urlStr);

            if (urlStr.toLowerCase().startsWith("www.")) {
                urlStr = "http://" + urlStr;
            }

            if (verifyHierachicalURI(urlStr, new String[] { "javascript" })) {
                // Construct the hyperlink for the url...
                String urlLink = "<a href=\"" + urlStr + '\"' + targetString + '>' + urlToDisplay + "</a>";

                // Remove the original urlStr from str and put urlLink there
                // instead...
                str.replace(linkStartIndex, linkEndIndex + 1, urlLink);

                // Set lastEndIndex to reflect the position of the end of
                // urlLink
                // within the whole string...
                lastEndIndex = (linkStartIndex - 1) + urlLink.length();
            } else {
                // lastEndIndex is different from the one above cos' there's
                // no
                // <a href...> tags added...
                lastEndIndex = (linkStartIndex - 1) + urlStr.length();
            }
        }
    }
}

From source file:org.josso.selfservices.password.generator.PasswordGeneratorImpl.java

/**
 * The real password generation is performed in this method
 *
 * @param size     the length of the password
 * @param pw_flags the settings for the password
 * @return the newly created password/*  w w w  . j  a  va2  s .  c  o  m*/
 */
private String phonemes(int size, int pw_flags) {
    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);

            /* 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;
                }
            }

            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)
                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;
                }
            }

            /*
             * 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;

            /* 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;
                }
            }

        }
    } while ((feature_flags & (PW_UPPERS | PW_DIGITS | PW_SYMBOLS)) != 0);

    return buf.toString();
}

From source file:com.wabacus.system.component.application.report.configbean.crosslist.AbsCrossListReportColAndGroupBean.java

protected void createStatisForWholeRow(CrossListReportType crossListReportType, StringBuffer dynselectedColsBuf,
        List lstChildren, String allColConditions, Map<String, Boolean> mDynamicColGroupDisplayType) {
    if (this.lstDisplayStatisBeansOfReport == null || this.lstDisplayStatisBeansOfReport.size() == 0)
        return;//from ww  w  . ja va 2s . c o  m
    DisplayBean disbean = this.getOwner().getReportBean().getDbean();
    ReportRequest rrequest = crossListReportType.getReportRequest();
    for (CrossListReportStatiDisplayBean statisdBeanTmp : this.lstDisplayStatisBeansOfReport) {//?
        if (!mDynamicColGroupDisplayType.get(statisdBeanTmp.getStatiBean().getId()))
            continue;
        int colidx = crossListReportType.generateColGroupIdxId();
        lstChildren.add(createDynamicCrossStatiColBean(disbean,
                rrequest.getI18NStringValue(statisdBeanTmp.getLabel()),
                statisdBeanTmp.getLabelstyleproperty(rrequest), statisdBeanTmp.getValuestyleproperty(rrequest),
                statisdBeanTmp.getStatiBean().getDatatypeObj(), colidx));
        dynselectedColsBuf.append(statisdBeanTmp.getStatiBean().getType() + "(");
        if (!allColConditions.trim().equals("")) {
            dynselectedColsBuf.append("case when ").append(allColConditions).append(" then ")
                    .append(statisdBeanTmp.getStatiBean().getColumn()).append("  end ");
        } else {
            dynselectedColsBuf.append(statisdBeanTmp.getStatiBean().getColumn());
        }
        dynselectedColsBuf.append(") as ").append("column_" + colidx).append(",");
    }
    if (dynselectedColsBuf.length() > 0 && dynselectedColsBuf.charAt(dynselectedColsBuf.length() - 1) == ',') {
        dynselectedColsBuf.deleteCharAt(dynselectedColsBuf.length() - 1);
    }
}