Example usage for java.lang StringBuffer replace

List of usage examples for java.lang StringBuffer replace

Introduction

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

Prototype

@Override
public synchronized StringBuffer replace(int start, int end, String str) 

Source Link

Usage

From source file:net.sf.jabref.logic.groups.KeywordGroup.java

/**
 * Removes matches of searchString in the entry's field. This is only
 * possible if the search expression is not a regExp.
 *//*w  ww .  j  a va  2 s.  co  m*/
private void removeMatches(BibEntry entry) {
    if (!entry.hasField(searchField)) {
        return; // nothing to modify
    }
    String content = entry.getField(searchField);
    StringBuffer sbOrig = new StringBuffer(content);
    StringBuffer sbLower = new StringBuffer(content.toLowerCase());
    StringBuffer haystack = caseSensitive ? sbOrig : sbLower;
    String needle = caseSensitive ? searchExpression : searchExpression.toLowerCase();
    int i;
    int j;
    int k;
    final String separator = jabRefPreferences.get(JabRefPreferences.KEYWORD_SEPARATOR);
    while ((i = haystack.indexOf(needle)) >= 0) {
        sbOrig.replace(i, i + needle.length(), "");
        sbLower.replace(i, i + needle.length(), "");
        // reduce spaces at i to 1
        j = i;
        k = i;
        while (((j - 1) >= 0) && (separator.indexOf(haystack.charAt(j - 1)) >= 0)) {
            --j;
        }
        while ((k < haystack.length()) && (separator.indexOf(haystack.charAt(k)) >= 0)) {
            ++k;
        }
        sbOrig.replace(j, k, (j >= 0) && (k < sbOrig.length()) ? separator : "");
        sbLower.replace(j, k, (j >= 0) && (k < sbOrig.length()) ? separator : "");
    }

    String result = sbOrig.toString().trim();
    if (result.isEmpty()) {
        entry.clearField(searchField);
    } else {
        entry.setField(searchField, result);
    }
}

From source file:net.sf.jabref.groups.structure.KeywordGroup.java

/**
 * Removes matches of searchString in the entry's field. This is only
 * possible if the search expression is not a regExp.
 *///from w w w .  j a  v a2 s  .  com
private void removeMatches(BibEntry entry) {
    if (!entry.hasField(searchField)) {
        return; // nothing to modify
    }
    String content = entry.getField(searchField);
    StringBuffer sbOrig = new StringBuffer(content);
    StringBuffer sbLower = new StringBuffer(content.toLowerCase());
    StringBuffer haystack = caseSensitive ? sbOrig : sbLower;
    String needle = caseSensitive ? searchExpression : searchExpression.toLowerCase();
    int i;
    int j;
    int k;
    final String separator = Globals.prefs.get(JabRefPreferences.GROUP_KEYWORD_SEPARATOR);
    while ((i = haystack.indexOf(needle)) >= 0) {
        sbOrig.replace(i, i + needle.length(), "");
        sbLower.replace(i, i + needle.length(), "");
        // reduce spaces at i to 1
        j = i;
        k = i;
        while (((j - 1) >= 0) && (separator.indexOf(haystack.charAt(j - 1)) >= 0)) {
            --j;
        }
        while ((k < haystack.length()) && (separator.indexOf(haystack.charAt(k)) >= 0)) {
            ++k;
        }
        sbOrig.replace(j, k, (j >= 0) && (k < sbOrig.length()) ? separator : "");
        sbLower.replace(j, k, (j >= 0) && (k < sbOrig.length()) ? separator : "");
    }

    String result = sbOrig.toString().trim();
    if (result.isEmpty()) {
        entry.clearField(searchField);
    } else {
        entry.setField(searchField, result);
    }
}

From source file:org.openbravo.dal.core.DalMappingGenerator.java

private String generateOneToMany(Property p) {
    final StringBuffer sb = new StringBuffer();
    StringBuffer order = new StringBuffer();
    if (p.isOneToMany()) {
        if (p.getTargetEntity().getOrderByProperties().size() > 0) {
            order.append("order-by=\"");
            for (final Property po : p.getTargetEntity().getOrderByProperties()) {
                order.append(po.getColumnName() + " ASC,");
            }/*from  w  w  w. ja v a2s. c  om*/
            order = order.replace(order.length() - 1, order.length(), "");
            order.append("\"");
        }

        String mutable = "";
        String cascade = "";
        if (p.isChild()) {
            cascade = " cascade=\"all,delete-orphan\" ";
        }
        if (p.getEntity().isView() || p.getTargetEntity().isView()) {
            mutable = " mutable=\"false\" ";
            cascade = "";
        }

        sb.append(TAB2 + "<bag name=\"" + p.getName() + "\" " + cascade + order + getAccessorAttribute()
                + mutable + " inverse=\"true\">" + NL);
        sb.append(TAB3 + "<key column=\"" + p.getReferencedProperty().getColumnName() + "\""
                + (p.getReferencedProperty().isMandatory() ? " not-null=\"true\"" : "") + "/>" + NL);
        sb.append(TAB3 + "<one-to-many entity-name=\"" + p.getTargetEntity().getName() + "\"/>" + NL);

        if (p.getTargetEntity().isActiveEnabled()) {
            sb.append(TAB3 + getActiveFilter());
        }
        sb.append(TAB2 + "</bag>" + NL);

    }
    return sb.toString();
}

From source file:util.StripHTMLTags.java

/**
 * This method strips all tags from the body except those given in
 * in the tag array./*from  w w w  .  j a  v a 2 s .c o m*/
 *
 * @param body The body or text to strip
 * @param tags The tag array for strip exclusion
 * @return String Return the body with the stripped tags.
 */
public String stripTags(String body, String[] tags) {
    if (null == body)
        return body;
    Pattern pattern = Pattern.compile("<.*?>", Pattern.DOTALL);
    Pattern[] tagPatterns = null;
    if (tags != null) {
        tagPatterns = new Pattern[tags.length];
        for (int i = 0; i < tags.length; i++) {
            tagPatterns[i] = Pattern.compile("<(\\s*?)(/??)(\\s*?)" + tags[i] + "((\\s*?>)||(\\s(.*?)>))",
                    Pattern.DOTALL);
        }
    }
    StringBuffer bodyStr = new StringBuffer(body);

    bodyStr = stripCSS(bodyStr);
    bodyStr = stripJS(bodyStr);

    Matcher matcher = pattern.matcher(bodyStr);
    while (matcher.find()) {
        logger.debug("Match: " + matcher.group());
        boolean matches = false;
        if ((tags != null) && (tags.length != 0)) {
            for (int i = 0; i < tags.length && (!matches); i++) {
                logger.debug("Pattern: " + tagPatterns[i].pattern());
                Matcher ematcher = tagPatterns[i].matcher(matcher.group());
                matches = matches || ematcher.matches();
            }
        }
        if (!matches) {
            logger.debug("Substituting Match");
            bodyStr = bodyStr.replace(matcher.start(), matcher.end(), "");
            matcher = pattern.matcher(bodyStr);
        }
    }
    return bodyStr.toString();
}

From source file:org.ormma.controller.OrmmaAssetController.java

/**
 * Write an input stream to a file wrapping it with ormma stuff
 * //w  w w .j a  v  a 2  s.co m
 * @param in
 *            the input stream
 * @param file
 *            the file to store it in
 * @param storeInHashedDirectory
 *            use a hashed directory name
 * @return the path where it was stored
 * @throws IllegalStateException
 *             the illegal state exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public String writeToDiskWrap(InputStream in, String file, boolean storeInHashedDirectory, String injection,
        String bridgePath, String ormmaPath) throws IllegalStateException, IOException
/**
 * writes a HTTP entity to the specified filename and location on disk
 */
{
    byte buff[] = new byte[1024];

    MessageDigest digest = null;
    if (storeInHashedDirectory) {
        try {
            digest = java.security.MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    // check for html tag in the input
    ByteArrayOutputStream fromFile = new ByteArrayOutputStream();
    FileOutputStream out = null;
    try {
        do {
            int numread = in.read(buff);

            if (numread <= 0) {
                break;
            }

            if (storeInHashedDirectory && digest != null) {
                digest.update(buff);
            }

            fromFile.write(buff, 0, numread);

        } while (true);

        String wholeHTML = fromFile.toString();
        Log.d("html", wholeHTML);
        boolean hasHTMLWrap = wholeHTML.indexOf("</html>") >= 0;

        // TODO cannot have injection when full html

        StringBuffer wholeHTMLBuffer = null;

        if (hasHTMLWrap) {
            wholeHTMLBuffer = new StringBuffer(wholeHTML);

            int start = wholeHTMLBuffer.indexOf("/ormma_bridge.js");

            if (start <= 0) {
                // TODO error
            }

            wholeHTMLBuffer.replace(start, start + "/ormma_bridge.js".length(), "file:/" + bridgePath);

            start = wholeHTMLBuffer.indexOf("/ormma.js");

            if (start <= 0) {
                // TODO error
            }

            wholeHTMLBuffer.replace(start, start + "/ormma.js".length(), "file:/" + ormmaPath);
        }

        out = getAssetOutputString(file);

        if (!hasHTMLWrap) {
            out.write("<html>".getBytes());
            out.write("<head>".getBytes());
            out.write("<meta name='viewport' content='user-scalable=no initial-scale=1.0' />".getBytes());
            out.write("<title>Advertisement</title> ".getBytes());

            out.write(
                    ("<script src=\"file:/" + bridgePath + "\" type=\"text/javascript\"></script>").getBytes());
            out.write(
                    ("<script src=\"file:/" + ormmaPath + "\" type=\"text/javascript\"></script>").getBytes());

            if (injection != null) {
                out.write("<script type=\"text/javascript\">".getBytes());
                out.write(injection.getBytes());
                out.write("</script>".getBytes());
            }
            out.write("</head>".getBytes());
            out.write("<body style=\"margin:0; padding:0; overflow:hidden; background-color:transparent;\">"
                    .getBytes());
            out.write("<div align=\"center\"> ".getBytes());
        }

        if (!hasHTMLWrap) {
            out.write(fromFile.toByteArray());
        } else {
            out.write(wholeHTMLBuffer.toString().getBytes());
        }

        if (!hasHTMLWrap) {
            out.write("</div> ".getBytes());
            out.write("</body> ".getBytes());
            out.write("</html> ".getBytes());
        }

        out.flush();
        //         out.close();
        //         in.close();
    } finally {
        if (fromFile != null) {
            try {
                fromFile.close();
            } catch (Exception e) {
                // TODO: handle exception
            }
            fromFile = null;
        }
        if (out != null) {
            try {
                out.close();
            } catch (Exception e) {
                // TODO: handle exception
            }
            out = null;
        }
    }
    String filesDir = getFilesDir();

    if (storeInHashedDirectory && digest != null) {
        filesDir = moveToAdDirectory(file, filesDir, asHex(digest));
    }
    return filesDir;
}

From source file:de.dfki.km.perspecting.obie.model.Document.java

/***************************************************************************
 * Gets the pure plain text out of a html text. All html tags are replaced
 * by spaces. To do so, the head is replaced, all remaining javascript tags
 * (including the content) and finally all remaining html tags. Thus,
 * absolute positioning is possible.//from w ww  . j  ava 2 s . c om
 * 
 * @param text
 *            content of the html document as text
 * @return text where all html was replaced by spaces
 */
private String extractPlainTextFromHtml(String text) {
    Collection<Pattern> patterns = new ArrayList<Pattern>(3);
    // Delete the head, then all remaining javascript items that might exist
    // in the body, then all remaining html tags.
    patterns.add(
            Pattern.compile("<head.*/head>", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.DOTALL));
    // .*? makes it non greedy -> take the shortes match
    // DOTALL does also include new lines
    patterns.add(Pattern.compile("<script.*?/script>",
            Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.DOTALL));
    patterns.add(Pattern.compile("<.+?>", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE));
    StringBuffer s = new StringBuffer(text);

    // Go for all patterns.
    for (Pattern p : patterns) {
        Matcher matcher = p.matcher(s);

        // As long as the matcher finds another occurance of the pattern we
        // replace it by the same number of spaces but keep new lines.
        while (matcher.find())
            s.replace(matcher.start(), matcher.end(), matcher.group().replaceAll(".", " "));
    }
    return s.toString();
}

From source file:com.google.dart.tools.ui.text.dart.CompletionProposalLabelProvider.java

/**
 * Returns the display string for a Dart type signature.
 * //from w  w w . j a  va  2  s.c  om
 * @param typeSignature the type signature to create a display name for
 * @return the display name for <code>typeSignature</code>
 * @throws IllegalArgumentException if <code>typeSignature</code> is not a valid signature
 * @see Signature#toCharArray(char[])
 * @see Signature#getSimpleName(char[])
 */
private char[] createTypeDisplayName(char[] typeSignature) throws IllegalArgumentException {
    char[] displayName = Signature.getSimpleName(Signature.toCharArray(typeSignature));

    // XXX see https://bugs.eclipse.org/bugs/show_bug.cgi?id=84675
    boolean useShortGenerics = false;
    if (useShortGenerics) {
        StringBuffer buf = new StringBuffer();
        buf.append(displayName);
        int pos;
        do {
            pos = buf.indexOf("? extends "); //$NON-NLS-1$
            if (pos >= 0) {
                buf.replace(pos, pos + 10, "+"); //$NON-NLS-1$
            } else {
                pos = buf.indexOf("? super "); //$NON-NLS-1$
                if (pos >= 0) {
                    buf.replace(pos, pos + 8, "-"); //$NON-NLS-1$
                }
            }
        } while (pos >= 0);
        return buf.toString().toCharArray();
    }
    return displayName;
}

From source file:com.seajas.search.contender.service.modifier.AbstractModifierService.java

/**
 * Create a StringBuffer out of the given reader content.
 * /*from w w w .j  a va2  s  .co  m*/
 * @param buffer
 * @param reader
 * @param cleanFromProlog
 * @return Reader
 */
protected Reader readerToBuffer(final StringBuffer buffer, final Reader reader, final boolean cleanFromProlog) {
    Integer lastProlog = -1;

    try {
        char[] characterBuffer = new char[8192];

        for (int count; (count = reader.read(characterBuffer)) > 0;) {
            buffer.append(characterBuffer, 0, count);

            // When cleaning by prolog, we stop writing out the buffer after the second prolog

            if (cleanFromProlog) {
                if (lastProlog == -1)
                    lastProlog = buffer.indexOf("<?xml");
                if (lastProlog != -1 && (lastProlog = buffer.indexOf("<?xml", lastProlog + 1)) != -1) {
                    logger.warn("Input document contains more than one XML prolog. Stripping any extra ones.");

                    buffer.replace(lastProlog, buffer.length(), "");

                    break;
                }
            }
        }

        reader.close();

        return new StringReader(buffer.toString().trim());
    } catch (IOException e) {
        logger.error("Could not convert the given reader to a buffer", e);

        return null;
    }
}

From source file:com.bayontechnologies.bi.pentaho.plugin.openflashchart.OpenFlashChartComponent.java

/**
 * Flash Template String Replacement. It is the latest replacement.
 * @param flashFragment2 the flash template
 * @param id the id of the content item/*w  ww  .  j av  a2s  .  co  m*/
 * @param chartWidth
 * @param chartHeight
 * @param ofcURL
 * @return the working flash codes 
 */
public String replace(String flashFragment2, String id, Integer chartWidth, Integer chartHeight,
        String ofcURL) {
    StringBuffer buff = new StringBuffer(flashFragment2);
    //replace the {chart-width}
    String token = "{chart-width}";
    int index;
    replaceByToken(buff, "" + chartWidth, token);

    //replace the {chart-height}
    token = "{chart-height}";
    replaceByToken(buff, "" + chartHeight, token);

    //replace the {ofc-url}
    token = "{ofc-url}";
    replaceByToken(buff, ofcURL, token);

    //replace the {data}
    token = "{data}";
    index = buff.lastIndexOf(token);
    buff.replace(index, index + token.length(), getTmpContentURL(id));
    //replace the {data} again
    index = buff.lastIndexOf(token);
    if (index != -1) {
        buff.replace(index, index + token.length(), getTmpContentURL(id));

    }

    log.debug(" flash codes after replacing:" + buff.toString());
    return buff.toString();
}

From source file:fedora.server.access.dissemination.DisseminationService.java

/**
 * <p>//from   w w  w .j  a  v a2s.  c  om
 * The tempID that is used for datastream mediation consists of a <code>
 * Timestamp</code>
 * plus a counter appended to the end to insure uniqueness. This method is a
 * utility method used to extract the Timestamp portion from the tempID by
 * stripping off the arbitrary counter at the end of the string.
 * </p>
 * 
 * @param tempID
 *        The tempID to be extracted.
 * @return The extracted Timestamp value as a string.
 */
public String extractTimestamp(String tempID) {
    StringBuffer sb = new StringBuffer();
    sb.append(tempID);
    sb.replace(tempID.lastIndexOf(":"), tempID.length(), "");
    return sb.toString();
}