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:com.aurel.track.lucene.search.listFields.AbstractListFieldSearcher.java

/**
 * Replaces the label for a field with the objectID value
 * @param analyzer //  w w  w.j  av  a 2s. c  o m
 * @param toBeProcessedString a part of the user entered query string
 * @param workItemFieldName the workItem field name (like CRM Contact)
 * @param luceneFieldName the name of the user entered lucene field (like Company from CRM Contact)
 * @param indexStart the index to start looking for fieldName 
 * @return
 */
protected String replaceExplicitFieldValue(Analyzer analyzer, String toBeProcessedString,
        String workItemFieldName, String luceneFieldName, Integer fieldID, Locale locale, int indexStart) {
    int indexFound = LuceneSearcher.fieldNameIndex(toBeProcessedString, workItemFieldName, indexStart);
    if (indexFound == -1) {
        return toBeProcessedString;
    }
    int beginReplaceIndex = indexFound + workItemFieldName.length() + 1;
    String originalFieldValue = LuceneSearcher.getFieldValue(toBeProcessedString.substring(beginReplaceIndex));
    if (originalFieldValue == null || "".equals(originalFieldValue)) {
        return toBeProcessedString;
    }
    String processedFieldValue = searchExplicitField(analyzer, luceneFieldName, originalFieldValue, fieldID,
            locale);
    if (processedFieldValue == null || "".equals(processedFieldValue)) {
        return toBeProcessedString;
    }
    StringBuffer original = new StringBuffer(toBeProcessedString);
    original.replace(indexFound, beginReplaceIndex + originalFieldValue.length(),
            workItemFieldName + LuceneSearcher.FIELD_NAME_VALUE_SEPARATOR + processedFieldValue);
    return replaceExplicitFieldValue(analyzer, original.toString(), workItemFieldName, luceneFieldName, fieldID,
            locale, beginReplaceIndex + processedFieldValue.length());
}

From source file:org.jlibrary.servlet.service.HTTPStreamingServlet.java

protected void debugMethodCall(String callMethodName, Class[] paramTypes) {

    StringBuffer logMessage = new StringBuffer("Calling method " + callMethodName + " with params [");
    for (Class c : paramTypes) {
        logMessage.append(c.getName());/*from ww  w  .j  a v  a  2s.co m*/
        logMessage.append(",");
    }
    logMessage.replace(logMessage.length() - 1, logMessage.length(), "]");
    logger.debug(logMessage.toString());
}

From source file:com.panet.imeta.core.row.ValueDataUtil.java

/**
 * Alternate faster version of string replace using a stringbuffer as input.
 * /*  w w  w  .  j a v  a  2s  .c  o  m*/
 * @param str The string where we want to replace in
 * @param code The code to search for
 * @param repl The replacement string for code
 */
public static void replaceBuffer(StringBuffer str, String code, String repl) {
    int clength = code.length();

    int i = str.length() - clength;

    while (i >= 0) {
        String look = str.substring(i, i + clength);
        if (look.equalsIgnoreCase(code)) // Look for a match!
        {
            str.replace(i, i + clength, repl);
        }
        i--;
    }
}

From source file:org.exoplatform.wiki.rendering.render.confluence.ConfluenceSyntaxEscapeHandler.java

private void replaceAll(StringBuffer accumulatedBuffer, String match, String replacement) {
    int pos = -replacement.length();
    while ((pos + replacement.length() < accumulatedBuffer.length())
            && ((pos = accumulatedBuffer.indexOf(match, pos + replacement.length())) != -1)) {
        accumulatedBuffer.replace(pos, pos + match.length(), replacement);
    }//from   w w  w.  ja  v  a2  s  .com
}

From source file:de.betterform.agent.web.servlet.XSLTServlet.java

private StringBuffer generateError(String error) throws IOException, XFormsConfigException {

    String path = WebFactory.getRealPath("forms/incubator/editor", getServletContext());
    File f = new File(path, "callerror.html");
    FileInputStream fs = new FileInputStream(f);
    BufferedInputStream bis = new BufferedInputStream(fs);
    int numBytes = bis.available();
    byte b[] = new byte[numBytes];
    // read the template into a StringBuffer (via a byte array)
    bis.read(b);/*  w w w .j a va 2s  .co m*/
    StringBuffer buf = new StringBuffer();
    buf.append(b);
    int start = buf.indexOf(errorTemplate);
    int end = start + errorTemplate.length();
    // replace placeholder with errormessage
    // (will automatically adjust to take longer or shorter data into account)
    buf.replace(start, end, error);
    return buf;
}

From source file:org.exoplatform.wiki.rendering.render.confluence.ConfluenceSyntaxEscapeHandler.java

private void escapeURI(StringBuffer accumulatedBuffer, String match) {
    int pos = accumulatedBuffer.indexOf(match);
    if (pos > -1 && accumulatedBuffer.length() > pos + match.length()
            && accumulatedBuffer.charAt(pos + match.length()) > 32) {
        // Escape the ":" symbol
        accumulatedBuffer.replace(pos + match.length() - 1, pos + match.length(), "~:");
    }/*from   w  ww  .j  a  va2  s.  c o  m*/
}

From source file:gov.va.isaac.gui.listview.operations.FindAndReplace.java

/**
 * @see gov.va.isaac.gui.listview.operations.Operation#createTask()
 *//*from   w  w w. ja  va  2  s .  c o m*/
@Override
public CustomTask<OperationResult> createTask() {
    return new CustomTask<OperationResult>(FindAndReplace.this) {
        private Matcher matcher;

        @Override
        protected OperationResult call() throws Exception {
            double i = 0;
            successCons.clear();
            Set<SimpleDisplayConcept> modifiedConcepts = new HashSet<SimpleDisplayConcept>();
            for (SimpleDisplayConcept c : conceptList_) {
                if (cancelRequested_) {
                    return new OperationResult(FindAndReplace.this.getTitle(), cancelRequested_);
                }

                String newTxt = null;
                Set<String> successMatches = new HashSet<>();

                updateProgress(i, conceptList_.size());
                updateMessage("Processing " + c.getDescription());

                // For each concept, filter the descriptions to be changed based on user selected DescType
                ConceptVersionBI con = OTFUtility.getConceptVersion(c.getNid());
                Set<DescriptionVersionBI<?>> descsToChange = getDescsToChange(con);

                for (DescriptionVersionBI<?> desc : descsToChange) {
                    // First see if text is found in desc before moving onward
                    if (frc_.isRegExp() && hasRegExpMatch(desc) || !frc_.isRegExp() && hasGenericMatch(desc)) {

                        // Now check if language is selected, that it exists in language refset
                        if (frc_.getLanguageRefset().getNid() == 0
                                || !desc.getAnnotationsActive(OTFUtility.getViewCoordinate(),
                                        frc_.getLanguageRefset().getNid()).isEmpty()) {

                            // Replace Text
                            if (frc_.isRegExp()) {
                                newTxt = replaceRegExp();
                            } else {
                                newTxt = replaceGeneric(desc);
                            }

                            DescriptionType descType = getDescType(con, desc);
                            successMatches.add("    --> '" + desc.getText() + "' changed to '" + newTxt
                                    + "' ..... of type: " + descType);
                            updateDescription(desc, newTxt);
                        }
                    }
                }
                if (successMatches.size() > 0) {
                    modifiedConcepts.add(c);
                    successCons.put(c.getDescription() + " --- " + con.getPrimordialUuid().toString(),
                            successMatches);
                }

                updateProgress(++i, conceptList_.size());
            }

            return new OperationResult(FindAndReplace.this.getTitle(), modifiedConcepts, getMsgBuffer());
        }

        private boolean hasRegExpMatch(DescriptionVersionBI<?> desc) {
            Pattern pattern = Pattern.compile(frc_.getSearchText());

            matcher = pattern.matcher(desc.getText());

            if (matcher.find()) {
                return true;
            } else {
                return false;
            }
        }

        private String replaceRegExp() {
            // Replace all occurrences of pattern in input
            return matcher.replaceAll(frc_.getReplaceText());
        }

        private String replaceGeneric(DescriptionVersionBI<?> desc) {
            String txt = desc.getText();

            if (frc_.isCaseSens()) {
                while (txt.contains(frc_.getSearchText())) {
                    txt = txt.replace(frc_.getSearchText(), frc_.getReplaceText());
                }
            } else {
                int startIdx = StringUtils.indexOfIgnoreCase(txt, frc_.getSearchText());
                int endIdx = startIdx + frc_.getSearchText().length();

                while (startIdx >= 0) {
                    StringBuffer buf = new StringBuffer(txt);
                    buf.replace(startIdx, endIdx, frc_.getReplaceText());
                    txt = buf.toString();

                    startIdx = StringUtils.indexOfIgnoreCase(txt, frc_.getSearchText());
                }
            }

            return txt;
        }

        private boolean hasGenericMatch(DescriptionVersionBI<?> desc) {
            String txt = desc.getText();

            if (frc_.isCaseSens()) {
                if (!txt.contains(frc_.getSearchText())) {
                    return false;
                }
            } else {
                if (!StringUtils.containsIgnoreCase(txt, frc_.getSearchText())) {
                    return false;
                }
            }

            return true;
        }

        private void updateDescription(DescriptionVersionBI<?> desc, String newTxt)
                throws IOException, InvalidCAB, ContradictionException {
            DescriptionCAB dcab = desc.makeBlueprint(OTFUtility.getViewCoordinate(), IdDirective.PRESERVE,
                    RefexDirective.INCLUDE);
            dcab.setText(newTxt);
            DescriptionChronicleBI dcbi = OTFUtility.getBuilder().constructIfNotCurrent(dcab);
            ExtendedAppContext.getDataStore()
                    .addUncommitted(ExtendedAppContext.getDataStore().getConceptForNid(dcbi.getConceptNid()));
        }

        private Set<DescriptionVersionBI<?>> getDescsToChange(ConceptVersionBI con) {
            Set<DescriptionVersionBI<?>> descsToChange = new HashSet<>();

            try {
                for (DescriptionVersionBI<?> desc : con.getDescriptionsActive()) {

                    if (frc_.getSelectedDescTypes().contains(DescriptionType.FSN)
                            && con.getFullySpecifiedDescription().getNid() == desc.getNid()) {
                        descsToChange.add(desc);
                    } else if (frc_.getSelectedDescTypes().contains(DescriptionType.PT)
                            && con.getPreferredDescription().getNid() == desc.getNid()) {
                        descsToChange.add(desc);
                    } else if (frc_.getSelectedDescTypes().contains(DescriptionType.SYNONYM)
                            && con.getFullySpecifiedDescription().getNid() != desc.getNid()
                            && con.getPreferredDescription().getNid() != desc.getNid()) {
                        descsToChange.add(desc);
                    }
                }
            } catch (IOException | ContradictionException e) {
                // TODO (artf231875) Auto-generated catch block
                e.printStackTrace();
            }

            return descsToChange;
        }

        private DescriptionType getDescType(ConceptVersionBI con, DescriptionVersionBI<?> desc)
                throws IOException, ContradictionException {
            // TODO (artf231875) Auto-generated method stub
            if (con.getFullySpecifiedDescription().getNid() == desc.getNid()) {
                return DescriptionType.FSN;
            } else if (con.getPreferredDescription().getNid() == desc.getNid()) {
                return DescriptionType.PT;
            } else {
                return DescriptionType.SYNONYM;
            }
        }
    };
}

From source file:org.displaytag.model.Column.java

/**
 * Calculates the cell content, cropping or linking the value as needed.
 * /*from   ww  w.  j a  v a2s.  c  o m*/
 * @return String
 * @throws ObjectLookupException for errors in bean property lookup
 * @throws DecoratorException if a column decorator is used and an exception is thrown during value decoration
 */
public String createChoppedAndLinkedValue() throws ObjectLookupException, DecoratorException {

    String fullValue = ObjectUtils.toString(this.getValue(true));
    String choppedValue;

    // are we supposed to set up a link to the data being displayed in this column?
    if (this.header.getAutoLink()) {
        fullValue = AutolinkColumnDecorator.INSTANCE.decorate(fullValue);
    }

    // trim the string if a maxLength or maxWords is defined
    if (this.header.getMaxLength() > 0) {
        choppedValue = HtmlTagUtil.abbreviateHtmlString(fullValue, this.header.getMaxLength(), false);
    } else if (this.header.getMaxWords() > 0) {
        choppedValue = HtmlTagUtil.abbreviateHtmlString(fullValue, this.header.getMaxWords(), true);
    } else {
        choppedValue = fullValue;
    }

    // chopped content? add the full content to the column "title" attribute
    if (choppedValue.length() < fullValue.length()) {
        // clone the attribute map, don't want to add title to all the columns
        this.htmlAttributes = (HtmlAttributeMap) this.htmlAttributes.clone();
        // add title
        this.htmlAttributes.put(TagConstants.ATTRIBUTE_TITLE, HtmlTagUtil.stripHTMLTags(fullValue));
    }

    if (this.header.getHref() != null) {
        // generates the href for the link
        Href colHref = this.getColumnHref(fullValue);
        Anchor anchor = new Anchor(colHref, choppedValue);
        choppedValue = anchor.toString();

        // SIGESP verifica se hrefType = replace
        if (this.header.getHrefType() != null && this.header.getHrefType().equals("replace")) {

            String strTmp = choppedValue;

            Object valor = LookupUtil.getBeanProperty(this.row.getObject(), this.header.getParamProperty());
            String strValor = "";
            if (valor == null) {
                strValor = "NULL";
            } else {
                // Tratar aspas simples (retorno do javascript)
                strValor = Conversao.substituirExpressaoString(valor.toString(), "'", "\\u0027");
            }

            int intPosicao = -1;

            StringBuffer stbNovaString = new StringBuffer(strTmp);

            while ((intPosicao = stbNovaString.indexOf(this.header.getParamName())) >= 0) {
                stbNovaString.replace(intPosicao, intPosicao + this.header.getParamName().length(),
                        strValor.toString());
            }

            int intPosicaoIgual = stbNovaString.indexOf(strValor.toString() + "=");

            if (intPosicaoIgual != -1) {
                stbNovaString.replace(intPosicaoIgual - 1,
                        intPosicaoIgual - 1 + stbNovaString.substring(intPosicaoIgual - 1).indexOf(">") - 1,
                        ";");
                // stbNovaString.replace(stbNovaString.indexOf(valor.toString() + "=" + valor.toString()) - 1,
                // stbNovaString.substring(stbNovaString.indexOf(valor.toString() + "=" + valor.toString()) -
                // 1).indexOf(">"), ";");
            } else {
                throw new RuntimeException("Os parmetros informados na display-tag esto incorretos");
            }

            choppedValue = stbNovaString.toString();
        }
    }

    return choppedValue;
}

From source file:com.blocks.framework.utils.date.StringUtil.java

/**
  * SQLIn??: (x,y,z)  ('x','y','z')//from   www  .j  a  v  a2s. c  o m
  * 
  * @param conditions
  *            String[]
  * @param isString
  *            boolean
  * @return String
  */
 public static final String getQryCondtion(String[] conditions, boolean isString) {
     if (conditions == null || conditions.length <= 0) {
         return null;
     }
     StringBuffer cond = new StringBuffer("(");
     for (int i = 0; i < conditions.length; i++) {
         if (isString) {
             cond.append("'").append(conditions[i]).append("'");
         } else {
             cond.append(conditions[i]);
         }
         cond.append(",");
     }
     cond.replace(cond.length() - 1, cond.length(), ")");

     return cond.toString();
 }

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

private StringBuffer replaceByToken(StringBuffer buff, String value, String token) {

    int index = buff.indexOf(token);
    buff.replace(index, index + token.length(), value);
    if (buff.indexOf(token) != -1) {
        //loop replaceByToken again until there is no token at all.
        return replaceByToken(buff, value, token);
    }/*from  w  w  w .ja v  a 2 s .  c  o m*/
    return buff;
}