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:org.pentaho.di.core.row.ValueDataUtil.java

/**
 * Alternate faster version of string replace using a stringbuffer as input.
 *
 * @param str//from  www . ja  v a  2  s .  com
 *          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:de.citec.csra.allocation.vis.MovingChart.java

/**
 * Creates a sample chart.//w  w  w. ja v a 2 s  .c  o  m
 *
 * @param dataset the dataset.
 *
 * @return A sample chart.
 */
private JFreeChart createChart(final XYDataset dataset) {
    final JFreeChart result = ChartFactory.createTimeSeriesChart(null, "Time", "Resource", dataset, false, true,
            false);

    final XYPlot plot = result.getXYPlot();

    plot.addDomainMarker(this.marker);
    plot.setBackgroundPaint(new Color(0xf8f8ed));
    plot.setDomainGridlinesVisible(true);
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.lightGray);

    ValueAxis xaxis = plot.getDomainAxis();
    xaxis.setAutoRange(true);
    xaxis.setTickLabelsVisible(false);
    //Domain axis would show data of 60 seconds for a time
    xaxis.setFixedAutoRange(this.past + this.future); // 60 seconds
    xaxis.setVerticalTickLabels(true);
    ValueAxis yaxis = plot.getRangeAxis();
    yaxis.setAutoRangeMinimumSize(1.8);
    yaxis.setAutoRange(true);

    NumberAxis range = (NumberAxis) plot.getRangeAxis();
    range.setTickUnit(new NumberTickUnit(1));
    range.setNumberFormatOverride(new NumberFormat() {
        @Override
        public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) {
            return format((long) number, toAppendTo, pos);
        }

        private String getID(long number) {
            return values.entrySet().stream().filter(e -> e.equals(number)).findFirst().get().getKey();
        }

        @Override
        public StringBuffer format(long number, StringBuffer ap, FieldPosition pos) {
            String id = "N/A";
            if (number == 0) {
                id = "(Time)";
            }
            if (values.containsValue(number)) {
                for (Map.Entry<String, Long> entry : values.entrySet()) {
                    if (entry.getValue() == number) {
                        id = entry.getKey();
                        break;
                    }
                }
            }
            id = id.replaceFirst("/$", "");
            ap.append(id);
            if (id.length() > 32) {
                ap.replace(15, ap.length() - 15, "..");
            }
            return ap;
        }

        @Override
        public Number parse(String source, ParsePosition parsePosition) {
            return null;
        }
    });

    //      this.chart.getXYPlot().getRenderer(1).set
    //      XYLineAndShapeRenderer r = (XYLineAndShapeRenderer) this.chart.getXYPlot().getRendererForDataset(dataset);
    return result;
}

From source file:com.isecpartners.gizmo.HttpRequest.java

private void setContentEncodings(StringBuffer contents) {
    if (contents.toString().toUpperCase().indexOf(ACCEPT_ENCODING) != -1) {
        int valStart = contents.toString().toUpperCase().indexOf(ACCEPT_ENCODING) + ACCEPT_ENCODING.length()
                + 2;/*from  w ww  . j  ava 2 s .co  m*/
        int valEnd = contents.indexOf("\r\n", valStart);
        contents.replace(valStart, valEnd, "gzip, deflate");
    }
}

From source file:org.kuali.kra.protocol.protocol.funding.ProtocolFundingSourceServiceImplBase.java

@Override
public String updateLookupParameter(String parameter, String boClassName, String fieldConversions) {
    StringBuffer fullParameterBuffer = new StringBuffer(parameter);
    int start = fullParameterBuffer.indexOf(KRADConstants.METHOD_TO_CALL_BOPARM_LEFT_DEL)
            + KRADConstants.METHOD_TO_CALL_BOPARM_LEFT_DEL.length();
    int end = fullParameterBuffer.indexOf(KRADConstants.METHOD_TO_CALL_BOPARM_RIGHT_DEL);
    fullParameterBuffer.replace(start, end, boClassName);

    start = fullParameterBuffer.indexOf(KRADConstants.METHOD_TO_CALL_PARM1_LEFT_DEL)
            + KRADConstants.METHOD_TO_CALL_PARM1_LEFT_DEL.length();
    end = fullParameterBuffer.indexOf(KRADConstants.METHOD_TO_CALL_PARM1_RIGHT_DEL);
    fullParameterBuffer.replace(start, end, fieldConversions);

    return fullParameterBuffer.toString();
}

From source file:org.kuali.kra.irb.protocol.funding.ProtocolFundingSourceServiceImpl.java

/**
 * {@inheritDoc}/*from  ww  w  .j a v a2s. co m*/
 * @see org.kuali.kra.irb.protocol.funding.ProtocolFundingSourceService#updateLookupParameter(java.lang.String, java.lang.String, java.lang.String)
 */
public String updateLookupParameter(String parameter, String boClassName, String fieldConversions) {
    StringBuffer fullParameterBuffer = new StringBuffer(parameter);
    int start = fullParameterBuffer.indexOf(KNSConstants.METHOD_TO_CALL_BOPARM_LEFT_DEL)
            + KNSConstants.METHOD_TO_CALL_BOPARM_LEFT_DEL.length();
    int end = fullParameterBuffer.indexOf(KNSConstants.METHOD_TO_CALL_BOPARM_RIGHT_DEL);
    fullParameterBuffer.replace(start, end, boClassName);

    start = fullParameterBuffer.indexOf(KNSConstants.METHOD_TO_CALL_PARM1_LEFT_DEL)
            + KNSConstants.METHOD_TO_CALL_PARM1_LEFT_DEL.length();
    end = fullParameterBuffer.indexOf(KNSConstants.METHOD_TO_CALL_PARM1_RIGHT_DEL);
    fullParameterBuffer.replace(start, end, fieldConversions);

    return fullParameterBuffer.toString();
}

From source file:org.squale.squalix.tools.clearcase.configuration.ClearCaseConfiguration.java

/**
 * Cette mthode est appele dans le cas d'un audit de jalon pour mettre en minuscules une partie prcise (le nom de
 * la branche) de la commande.<br />
 * Typiquement, elle modifie la chane de la faon suivante : <br />
 * /*  w w  w.j a  v a  2  s  . c  o  m*/
 * <pre>
 * /usr/atria/bin/Perl -S /DINB/outils/gcl/script/mkview.pl -application 
 * {APP_NAME} -vob /vobs/tonus_intranet -consultation TONUS_INTRANET_V1_2_ACT 
 * -vws /app/SQUALE/clearcase/cc_storage/views/
 * TONUS_INTRANET_V1_2_ACT_mon_application_mon_projet_squale.vws 
 * -login mon_application_mon_projet_squale -snap -dir 
 * /app/SQUALE/&lt;b&gt;TONUS_INTRANET_V1_2_ACT&lt;/b&gt;_mon_application_mon_projet_squale
 * </pre>
 * 
 * <br />
 * en <br />
 * 
 * <pre>
 * /usr/atria/bin/Perl -S /DINB/outils/gcl/script/mkview.pl -application 
 * {APP_NAME} -vob /vobs/tonus_intranet -consultation TONUS_INTRANET_V1_2_ACT 
 * -vws /app/SQUALE/clearcase/cc_storage/views/
 * TONUS_INTRANET_V1_2_ACT_mon_application_mon_projet_squale.vws 
 * -login mon_application_mon_projet_squale -snap -dir 
 * /app/SQUALE/&lt;b&gt;tonus_intranet_v1_2_act&lt;/b&gt;_mon_application_mon_projet_squale
 * </pre>
 * 
 * @param pCommand commande  modifier.
 * @return la commande modifie.
 */
private String lowerBranchName(String pCommand) {
    StringBuffer buf = new StringBuffer(pCommand);

    /*
     * on cherche la position du caractre situ juste aprs le dernier sparateur UNIX ("/") de la chane.
     */
    int pos = buf.lastIndexOf(ClearCaseConfiguration.UNIX_SEPARATOR) + 1;

    /* longueur de la chaine. */
    int length = buf.length();

    /* on met en minuscules la chaine comprise entre "pos" et "length". */
    buf.replace(pos, length, buf.substring(pos, length).toLowerCase());

    return buf.toString();
}

From source file:org.chiba.xml.xforms.xpath.ExtensionFunctionsHelper.java

/**
 * Returns a date parsed from a date/dateTime string formatted accorings to
 * ISO 8601 rules./*from  w  ww.  j a  va  2s.  c o  m*/
 *
 * @param date the formatted date/dateTime string.
 * @return the parsed date.
 * @throws ParseException if the date/dateTime string could not be parsed.
 */
public static Date parseISODate(String date) throws ParseException {
    String pattern;
    StringBuffer buffer = new StringBuffer(date);

    switch (buffer.length()) {
    case 4:
        // Year: yyyy (eg 1997)
        pattern = "yyyy";
        break;
    case 7:
        // Year and month: yyyy-MM (eg 1997-07)
        pattern = "yyyy-MM";
        break;
    case 10:
        // Complete date: yyyy-MM-dd (eg 1997-07-16)
        pattern = "yyyy-MM-dd";
        break;
    default:
        // Complete date plus hours and minutes: yyyy-MM-ddTHH:mmTZD (eg 1997-07-16T19:20+01:00)
        // Complete date plus hours, minutes and seconds: yyyy-MM-ddTHH:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
        // Complete date plus hours, minutes, seconds and a decimal fraction of a second: yyyy-MM-ddTHH:mm:ss.STZD (eg 1997-07-16T19:20:30.45+01:00)
        pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";

        if (buffer.length() == 16) {
            // add seconds
            buffer.append(":00");
        }
        if (buffer.length() > 16 && buffer.charAt(16) != ':') {
            // insert seconds
            buffer.insert(16, ":00");
        }
        if (buffer.length() == 19) {
            // add milliseconds
            buffer.append(".000");
        }
        if (buffer.length() > 19 && buffer.charAt(19) != '.') {
            // insert milliseconds
            buffer.insert(19, ".000");
        }
        if (buffer.length() == 23) {
            // append timzeone
            buffer.append("+0000");
        }
        if (buffer.length() == 24 && buffer.charAt(23) == 'Z') {
            // replace 'Z' with '+0000'
            buffer.replace(23, 24, "+0000");
        }
        if (buffer.length() == 29 && buffer.charAt(26) == ':') {
            // delete '.' from 'HH:mm'
            buffer.deleteCharAt(26);
        }
    }

    // always set time zone on formatter
    SimpleDateFormat format = new SimpleDateFormat(pattern);
    final String dateFromBuffer = buffer.toString();
    if (dateFromBuffer.length() > 10) {
        format.setTimeZone(TimeZone.getTimeZone("GMT" + dateFromBuffer.substring(23)));
    }
    if (!format.format(format.parse(dateFromBuffer)).equals(dateFromBuffer)) {
        throw new ParseException("Not a valid ISO date", 0);
    }
    format.setTimeZone(TimeZone.getTimeZone("UTC"));

    return format.parse(buffer.toString());
}

From source file:com.netspective.sparx.util.xml.XmlSource.java

public void replaceNodeValue(Node node, String findStr, String replStr) {
    String srcStr = node.getNodeValue();
    if (srcStr == null || findStr == null || replStr == null)
        return;/*from   w  ww .  ja v  a  2 s  .c  o  m*/

    int findLoc = srcStr.indexOf(findStr);
    if (findLoc >= 0) {
        StringBuffer sb = new StringBuffer(srcStr);
        sb.replace(findLoc, findLoc + findStr.length(), replStr);
        node.setNodeValue(sb.toString());
    }
}

From source file:org.opencms.workplace.tools.git.CmsGitCheckin.java

/** Returns the command to run by the shell to normally run the checkin script.
 * @return the command to run by the shell to normally run the checkin script.
 *//*from w w  w  . ja v a  2  s .  c o  m*/
private String checkinScriptCommand() {

    String exportModules = "";
    if ((m_modulesToExport != null) && !m_modulesToExport.isEmpty()) {
        StringBuffer exportModulesParam = new StringBuffer();
        for (String moduleName : m_modulesToExport) {
            exportModulesParam.append(" ").append(moduleName);
        }
        exportModulesParam.replace(0, 1, " \"");
        exportModulesParam.append("\" ");
        exportModules = " --modules " + exportModulesParam.toString();

    }
    String commitMessage = "";
    if (m_commitMessage != null) {
        commitMessage = " -msg \"" + m_commitMessage.replace("\"", "\\\"") + "\"";
    }
    String gitUserName = "";
    if (m_gitUserName != null) {
        if (m_gitUserName.trim().isEmpty()) {
            gitUserName = " --ignore-default-git-user-name";
        } else {
            gitUserName = " --git-user-name \"" + m_gitUserName + "\"";
        }
    }
    String gitUserEmail = "";
    if (m_gitUserEmail != null) {
        if (m_gitUserEmail.trim().isEmpty()) {
            gitUserEmail = " --ignore-default-git-user-email";
        } else {
            gitUserEmail = " --git-user-email \"" + m_gitUserEmail + "\"";
        }
    }
    String autoPullBefore = "";
    if (m_autoPullBefore != null) {
        autoPullBefore = m_autoPullBefore.booleanValue() ? " --pull-before " : " --no-pull-before";
    }
    String autoPullAfter = "";
    if (m_autoPullAfter != null) {
        autoPullAfter = m_autoPullAfter.booleanValue() ? " --pull-after " : " --no-pull-after";
    }
    String autoPush = "";
    if (m_autoPush != null) {
        autoPush = m_autoPush.booleanValue() ? " --push " : " --no-push";
    }
    String exportFolder = " --export-folder \"" + m_currentConfiguration.getModuleExportPath() + "\"";
    String exportMode = " --export-mode " + m_currentConfiguration.getExportMode();
    String excludeLibs = "";
    if (m_excludeLibs != null) {
        excludeLibs = m_excludeLibs.booleanValue() ? " --exclude-libs" : " --no-exclude-libs";
    }
    String commitMode = "";
    if (m_commitMode != null) {
        commitMode = m_commitMode.booleanValue() ? " --commit" : " --no-commit";
    }
    String ignoreUncleanMode = "";
    if (m_ignoreUnclean != null) {
        ignoreUncleanMode = m_ignoreUnclean.booleanValue() ? " --ignore-unclean" : " --no-ignore-unclean";
    }
    String copyAndUnzip = "";
    if (m_copyAndUnzip != null) {
        copyAndUnzip = m_copyAndUnzip.booleanValue() ? " --copy-and-unzip" : " --no-copy-and-unzip";
    }

    String configFilePath = m_currentConfiguration.getFilePath();

    return "\"" + DEFAULT_SCRIPT_FILE + "\"" + exportModules + commitMessage + gitUserName + gitUserEmail
            + autoPullBefore + autoPullAfter + autoPush + exportFolder + exportMode + excludeLibs + commitMode
            + ignoreUncleanMode + copyAndUnzip + " \"" + configFilePath + "\"";
}

From source file:org.photovault.swingui.ExportSelectedAction.java

/**
 Returns a proper filename in a numbered sequence. Examples:
 <table>/*w w  w  .j  a v  a  2 s  . c  o  m*/
 <tr>
 <td>pattern</td>
 <td>example file names</td>
 </tr>
 <tr>
 <td>photo.jpg</td>
 <td>photo1.jpg, photo2.jpg</td>
 </tr>
 <tr>
 <td>photo_$n.jpg</td>
 <td>photo_1.jpg, photo_2.jpg, ..., photo_10000.jpg, ...</td>
 </tr>
 <tr>
 <td>photo_$4n.jpg</td>
 <td>photo_0001.jpg, photo_0002.jpg, ..., photo_10000.jpg, ...</td>
 </tr>
 </table>
 */

String getSequenceFnameFormat(String seqBase) {
    seqBase = seqBase.replaceAll("%", "%%");
    StringBuffer formatStrBuf = new StringBuffer(seqBase);
    Pattern seqNumPattern = Pattern.compile("\\$(\\d*)n");
    Matcher m = seqNumPattern.matcher(seqBase);
    if (m.find()) {
        int start = m.start();
        int end = m.end();

        //Check padding
        String padStr = m.group(1);
        /*
         Check for case in which padStr contains only zeros since format()
         throws exception for format string like %00d.
         */
        if (padStr.matches("^0*$")) {
            padStr = "1";
        }
        if (padStr.length() > 0) {
            padStr = "0" + padStr;
        }
        String seqNumFormat = "%1$" + padStr + "d";
        formatStrBuf.replace(start, end, seqNumFormat);
    } else {
        // No format template found, add number just before extension
        Pattern extPattern = Pattern.compile("\\.[^\\.]+$");
        int seqNumPos = seqBase.length();
        Matcher extMatcher = extPattern.matcher(seqBase);
        if (extMatcher.find()) {
            seqNumPos = extMatcher.start();
        }
        formatStrBuf.insert(seqNumPos, "%d");
    }
    return formatStrBuf.toString();
}