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.sshtools.daemon.authentication.AuthorizationFileVerification.java

private SshPublicKey getAuthorizedKey(String username, String algorithm, byte[] encoded) throws IOException {
    NativeAuthenticationProvider provider = NativeAuthenticationProvider.getInstance();

    String userHome = provider.getHomeDirectory(username); //, nativeSettings);

    if (userHome == null) {
        log.warn("There is no home directory for " + username + " is available");
    }//from   w  w w  . j  a v  a 2 s.c om

    // Replace '\' with '/' because when we use it in String.replaceAll
    // for some reason it removes them?
    if (userHome != null) {
        userHome = userHome.replace('\\', '/');
    }

    ServerConfiguration config = (ServerConfiguration) ConfigurationLoader
            .getConfiguration(ServerConfiguration.class);
    String authorizationFile;
    String userConfigDir = config.getUserConfigDirectory();

    // First replace any '\' with '/' (Becasue replaceAll removes them!)
    userConfigDir = userConfigDir.replace('\\', '/');

    // Replace any home directory tokens
    if ((userConfigDir.indexOf("%D") > -1) && (userHome == null)) {
        throw new IOException(
                "<UserConfigDirectory> requires home directory, but none available for " + username);
    }

    int idx = 0;

    while ((idx = userConfigDir.indexOf("%D", idx + 1)) > -1) {
        StringBuffer buf = new StringBuffer(userConfigDir);
        buf = buf.replace(idx, idx + 1, userHome);
        userConfigDir = buf.toString();
    }

    idx = 0;

    while ((idx = userConfigDir.indexOf("%U", idx + 1)) > -1) {
        StringBuffer buf = new StringBuffer(userConfigDir);
        buf = buf.replace(idx, idx + 1, username);
        userConfigDir = buf.toString();
    }

    // Replace the '/' with File.seperator and trim
    userConfigDir = userConfigDir.replace('/', File.separatorChar).trim();

    if (!userConfigDir.endsWith(File.separator)) {
        userConfigDir += File.separator;
    }

    authorizationFile = userConfigDir + config.getAuthorizationFile();

    // Load the authorization file
    File file = new File(authorizationFile);

    if (!file.exists()) {
        log.info("authorizationFile: " + authorizationFile + " does not exist.");
        throw new IOException("authorizationFile: " + authorizationFile + " does not exist.");
    }

    FileInputStream in = new FileInputStream(file);
    Authorization keys;

    try {
        keys = new Authorization(in);
    } catch (Exception e) {
        throw new AuthenticationProtocolException("Failed to load authorized keys file " + authorizationFile);
    }

    //      SshPublicKey key = SshPublicKeyFile.parse(encoded);
    Iterator it = keys.getAuthorizedKeys().iterator();

    SshKeyPair pair = SshKeyPairFactory.newInstance(algorithm);
    SshPublicKey authorizedKey = null;
    SshPublicKey key = pair.decodePublicKey(encoded);
    boolean valid = false;
    String keyfile;

    while (it.hasNext()) {
        keyfile = (String) it.next();

        // Look for the file in the user config dir first
        file = new File(userConfigDir + keyfile);

        // If it does not exist then look absolute
        if (!file.exists()) {
            file = new File(keyfile);
        }

        if (file.exists()) {
            // Try to open the public key in the default file format
            // otherwise attempt the supported key formats
            SshPublicKeyFile pkf = SshPublicKeyFile.parse(file);
            authorizedKey = pkf.toPublicKey();

            if (authorizedKey.equals(key)) {
                return authorizedKey;
            }
        } else {
            log.info("Failed attempt to load key file " + keyfile);
        }
    }

    throw new IOException("");
}

From source file:com.emc.plants.service.impl.ReportGeneratorBean.java

/** 
 * Run the report to get the top zip codes for a range of dates.
 *
 * @param startdate Start of date range.
 * @param enddate End of date range./*www . jav  a  2s  .  c  o  m*/
 * @param quantity Number of items to return in report.
 * @param reportFormat - Report format information.
 * @return Report containing results.
 */
@SuppressWarnings("unchecked")
public Report getTopSellingZipsForDates(java.util.Date startdate, java.util.Date enddate, int quantity,
        ReportFormat reportFormat) {
    Report report = null;
    Connection conn = null;
    ResultSet results = null;
    PreparedStatement sqlStatement = null;
    try {
        // Establish connection to datasource.
        String orderInfoTableName = "ORDER1";

        DataSource ds = (DataSource) Util.getInitialContext().lookup("jdbc/PlantsByWebSphereDataSource");
        conn = ds.getConnection();

        // Set sort order of ascending or descending.
        String sortOrder;
        if (reportFormat.isAscending())
            sortOrder = "ASC";
        else
            sortOrder = "DESC";

        // Set up where by clause.
        String startDateString = Long.toString(startdate.getTime());
        if (startDateString.length() < 14) {
            StringBuffer sb = new StringBuffer(Util.ZERO_14);
            sb.replace((14 - startDateString.length()), 14, startDateString);
            startDateString = sb.toString();
        }
        String endDateString = Long.toString(enddate.getTime());
        if (endDateString.length() < 14) {
            StringBuffer sb = new StringBuffer(Util.ZERO_14);
            sb.replace((14 - endDateString.length()), 14, endDateString);
            endDateString = sb.toString();
        }
        String whereString = " WHERE sellDate BETWEEN '" + startDateString + "' AND '" + endDateString + "' ";

        // Create SQL statement.
        String sqlString = "SELECT billZip, SUM(profit) AS PROFITS FROM " + orderInfoTableName + whereString
                + " GROUP BY billZip ORDER BY PROFITS " + sortOrder + ", billZip";

        Util.debug("sqlstring=" + sqlString + "=");
        sqlStatement = conn.prepareStatement(sqlString);
        results = sqlStatement.executeQuery();
        int i;

        // Initialize vectors to store data in.
        Vector[] vecs = new Vector[2];
        for (i = 0; i < vecs.length; i++) {
            vecs[i] = new Vector();
        }

        // Sift thru results.
        int count = 0;
        while ((results.next()) && (count < quantity)) {
            count++;
            i = 1;
            vecs[0].addElement(results.getString(i++));
            vecs[1].addElement(new Float(results.getFloat(i++)));
        }

        // Create report.
        report = new Report();
        report.setReportFieldByRow(Report.ORDER_BILLZIP, vecs[0]);
        report.setReportFieldByRow(Report.PROFITS, vecs[1]);
    } catch (NamingException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally { // Clean up.
        try {
            if (results != null)
                results.close();
        } catch (Exception ignore) {
        }

        try {
            if (sqlStatement != null)
                sqlStatement.close();
        } catch (Exception ignore) {
        }

        // Close Connection.
        try {
            if (conn != null)
                conn.close();
        } catch (Exception ignore) {
        }
    }

    return report;
}

From source file:com.emc.plants.service.impl.ReportGeneratorBean.java

/** 
 * Run the report to get the top selling items for a range of dates.
 *
 * @param startdate Start of date range.
 * @param enddate End of date range.//from  w w  w  .  jav a2 s.co m
 * @param quantity Number of items to return in report.
 * @param reportFormat - Report format information.
 * @return Report containing results.
 */
@SuppressWarnings("unchecked")
public Report getTopSellersForDates(java.util.Date startdate, java.util.Date enddate, int quantity,
        ReportFormat reportFormat) {
    Report report = null;
    Connection conn = null;
    ResultSet results = null;
    PreparedStatement sqlStatement = null;
    try {
        // Establish connection to datasource.
        String orderItemsTableName = "ORDERITEM";
        DataSource ds = (DataSource) Util.getInitialContext().lookup("jdbc/PlantsByWebSphereDataSource");
        conn = ds.getConnection();

        // Set sort order of ascending or descending.
        String sortOrder;
        if (reportFormat.isAscending())
            sortOrder = "ASC";
        else
            sortOrder = "DESC";

        // Set up where by clause.
        String startDateString = Long.toString(startdate.getTime());
        if (startDateString.length() < 14) {
            StringBuffer sb = new StringBuffer(Util.ZERO_14);
            sb.replace((14 - startDateString.length()), 14, startDateString);
            startDateString = sb.toString();
        }
        String endDateString = Long.toString(enddate.getTime());
        if (endDateString.length() < 14) {
            StringBuffer sb = new StringBuffer(Util.ZERO_14);
            sb.replace((14 - endDateString.length()), 14, endDateString);
            endDateString = sb.toString();
        }
        String whereString = " WHERE sellDate BETWEEN '" + startDateString + "' AND '" + endDateString + "' ";

        // Create SQL statement.
        String sqlString = "SELECT inventoryID, name, category,"
                + " SUM(quantity * (price - cost)) as PROFIT FROM " + orderItemsTableName + whereString
                + " GROUP BY inventoryID, name, category ORDER BY PROFIT " + sortOrder + ", name";

        Util.debug("sqlstring=" + sqlString);

        sqlStatement = conn.prepareStatement(sqlString);
        results = sqlStatement.executeQuery();
        int i;

        // Initialize vectors to store data in.
        Vector[] vecs = new Vector[4];
        for (i = 0; i < vecs.length; i++) {
            vecs[i] = new Vector();
        }

        // Sift thru results.
        int count = 0;
        while ((results.next()) && (count < quantity)) {
            count++;
            i = 1;
            vecs[0].addElement(results.getString(i++));
            vecs[1].addElement(results.getString(i++));
            vecs[2].addElement(new Integer(results.getInt(i++)));
            vecs[3].addElement(new Float(results.getFloat(i++)));
        }

        // Create report.
        report = new Report();
        report.setReportFieldByRow(Report.ORDER_INVENTORY_ID, vecs[0]);
        report.setReportFieldByRow(Report.ORDER_INVENTORY_NAME, vecs[1]);
        report.setReportFieldByRow(Report.ORDER_INVENTORY_CATEGORY, vecs[2]);
        report.setReportFieldByRow(Report.PROFITS, vecs[3]);
    }

    catch (Exception e) {
        Util.debug("exception in ReportGeneratorBean:getTopSellersForDates.  " + e);
        e.printStackTrace();
    } finally { // Clean up.
        try {
            if (results != null)
                results.close();
        } catch (Exception ignore) {
        }

        try {
            if (sqlStatement != null)
                sqlStatement.close();
        } catch (Exception ignore) {
        }

        // Close Connection.
        try {
            if (conn != null)
                conn.close();
        } catch (Exception ignore) {
        }
    }

    return report;
}

From source file:gov.nih.nci.nbia.basket.DynamicJNLPGenerator.java

private void replaceProperties(StringBuffer propXmlBuilder, StringBuffer jnlpBuilder) {
    if (jnlpBuilder.toString().indexOf("$$properties") < 0) {
        return;//  w w w  .  ja va2  s  .c  o  m
    }

    int start = jnlpBuilder.toString().indexOf("$$properties");
    int length = "$$properties".length();

    jnlpBuilder.replace(start, start + length, propXmlBuilder.toString());
}

From source file:org.dknight.app.UnmanagedAMLauncher.java

/**
 *///from  w w  w.  j  a  v a  2  s .co  m
public UnmanagedAMLauncher(Configuration conf) throws Exception {
    // Set up RPC
    this.conf = conf;
    String classUrl = this.getClass().getResource("/").getPath();
    StringBuffer confStrBuilder = new StringBuffer(classUrl);
    int targetnIdx = confStrBuilder.indexOf("classes");
    confStrBuilder = confStrBuilder.replace(targetnIdx, confStrBuilder.length(), "test-classes/yarn-conf.xml");

    this.conf.addResource(new Path(confStrBuilder.toString()));
}

From source file:com.stephenduncanjr.easymock.matcher.BeanProperty.java

/**
 * @see org.easymock.IArgumentMatcher#appendTo(java.lang.StringBuffer)
 *//*from   w ww  . j  a  v  a  2  s  .  c  o  m*/
public void appendTo(final StringBuffer buffer) {
    buffer.append("propertyEq(");

    for (final Entry<String, ?> entry : this.expectedProperties.entrySet()) {
        buffer.append(entry.getKey());
        buffer.append("=");
        buffer.append(entry.getValue());
        buffer.append(", ");
    }

    buffer.replace(buffer.length() - 2, buffer.length(), ")");
}

From source file:org.bibsonomy.model.util.BibTexUtils.java

/** Adds the given field at the end of the given BibTeX entry by placing
 * it before the last brace. /*from  ww w  .  jav  a2  s.  co  m*/
 * 
 * @param bibtex - the BibTeX entry
 * @param fieldName - the name of the field
 * @param fieldValue - the value of the field
 */
public static void addField(final StringBuffer bibtex, final String fieldName, final String fieldValue) {
    /*
     * ignore empty bibtex and empty field values
     */
    if (bibtex == null || fieldValue == null || fieldValue.trim().equals(""))
        return;

    /*
     * remove last comma if there is one (before closing last curly bracket)
     */
    final String bib = bibtex.toString().trim();
    final Matcher m = LAST_COMMA_PATTERN.matcher(bib);

    if (m.matches()) {
        final int _lastIndex = bib.lastIndexOf(",");
        bibtex.replace(_lastIndex, _lastIndex + 1, "");
    }

    final int lastIndexOf = bibtex.lastIndexOf("}");
    if (lastIndexOf > 0) {
        bibtex.replace(lastIndexOf, bibtex.length(), "," + fieldName + " = {" + fieldValue + "}\n}");
    }
}

From source file:org.latticesoft.util.common.StringUtil.java

/**
 * Replaces the key string with the new value inside the source.
 * Similar to above methods except for the string buffer input
 * instead of string input.//from ww w. ja  v  a 2 s.c  om
 * @param source the source string buffer
 * @param key the string to be replaced
 * @param value the new string to replace the key string
 * @return the final result after replacement
 */
public static String replace(StringBuffer source, String key, String value, boolean all) {
    int count = 0;
    int index = source.toString().indexOf(key, count);
    while (index >= 0) {
        source.replace(index, index + key.length(), value);
        count = index + value.length();
        if (count > 0 && !all)
            break;
        index = source.toString().indexOf(key, count);

        if (log.isDebugEnabled()) {
            log.debug("Index:" + index);
            log.debug("String:" + source.toString());
        }
    }
    return source.toString();
}

From source file:net.sf.zekr.common.util.VelocityUtils.java

public String items2JsArray(int pageNum) {
    IPagingData pagingData = ApplicationConfig.getInstance().getQuranPaging().getDefault();
    IQuranPage quranPage = pagingData.getQuranPage(pageNum);
    IQuranLocation fromLoc = quranPage.getFrom();
    IQuranLocation toLoc = quranPage.getTo();
    StringBuffer buf = new StringBuffer("[");
    while (fromLoc != null && fromLoc.compareTo(toLoc) <= 0) {
        buf.append('\'').append(fromLoc.toString()).append('\'').append(", ");
        fromLoc = fromLoc.getNext();// w w  w . j a  va  2 s.  com
    }
    if (buf.length() > 1) {
        buf.replace(buf.length() - 2, buf.length(), "]");
    }
    return buf.toString();
}

From source file:org.apache.cocoon.HtmlUnitTestCase.java

/**
 * Copy file from webapp source to deployment area filtering content
 * to replace parameter by value./*ww  w  . ja  v  a 2 s  .  co  m*/
 * The source and deployment directories are defined by the properties
 * htmlunit.test.source-dir and htmlunit.test.deploy-dir.
 *
 * This method is most useful for testing the automatic reloading of
 * changed files.
 */
protected void copyWebappFile(String filename, String param, String value) throws Exception {
    String srcdir = System.getProperty("htmlunit.test.source-dir");
    String dstdir = System.getProperty("htmlunit.test.deploy-dir");
    File srcfile = new File(srcdir + "/" + filename);
    File dstfile = new File(dstdir + "/" + filename);

    final String encoding = "ISO-8859-1";
    StringBuffer content = new StringBuffer(FileUtils.readFileToString(srcfile, encoding));

    int index = content.indexOf(param);
    while (index != -1) {
        content.replace(index, index + param.length(), value);
        index = content.indexOf(param, index + 1);
    }

    FileUtils.writeStringToFile(dstfile, content.toString(), encoding);

    // Leave server some time to realize that file has changed.

    Thread.sleep(1000);
}