Example usage for java.lang StringBuilder replace

List of usage examples for java.lang StringBuilder replace

Introduction

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

Prototype

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

Source Link

Usage

From source file:org.openbravo.advpaymentmngt.actionHandler.AddPaymentActionHandler.java

/**
 * @param allselection/*  ww  w.  j  a v  a  2 s . c  o m*/
 *          Selected Rows in Credit to use grid
 * @return a String with the concatenation of the selected rows ids
 */
private String getSelectedCreditLinesIds(JSONArray allselection) throws JSONException {
    StringBuilder sb = new StringBuilder();
    sb.append("(");
    for (int i = 0; i < allselection.length(); i++) {
        JSONObject selectedRow = allselection.getJSONObject(i);
        sb.append(selectedRow.getString("id") + ",");
    }
    sb.replace(sb.lastIndexOf(","), sb.lastIndexOf(",") + 1, ")");
    return sb.toString();
}

From source file:gov.nih.nci.ncicb.tcga.dcc.QCLiveTestDataGenerator.java

/**
 * Populates a local unit test database with specific disease test data for testing QCLive.
 * //from ww w.j a  v a  2  s .com
 * @param diseaseAbbr - a string representing the abbreviated disease name
 * @throws IOException if an error occurs while reading the SQL script file that contains the insert generation statements
 */
private void generateAndLoadDiseaseTestData(final String diseaseAbbr) throws IOException {

    logger.info("Loading disease specific test data for disease abbreviation '" + diseaseAbbr + "'...");

    // Get reference to SQL script file used to create the insert statements for disease test data
    final URL sqlScriptFileNameURL = new ClassPathResource(diseaseDevSQLInsertScriptFileName).getURL();

    // Generate the insert statements using the data source referenced by dieseaseDevJdbcTemplate and the SQL script above
    final List<String> insertsForDiseaseTestData = new ArrayList<String>();
    final List<String> sqlInsertGenStmts = getSQLStmtsToLowerCaseFromFile(sqlScriptFileNameURL);
    final String replaceFromString = "from ";
    final String fromStringReplacement = "from tcga" + diseaseAbbr + ".";
    for (String insertGenStmt : sqlInsertGenStmts) {
        // Modify the ending "from " string for each insert statement to specify the appropriate disease schema before executing a query
        StringBuilder diseaseInsertGenStmt = new StringBuilder(insertGenStmt);
        int fromStringIndex = insertGenStmt.lastIndexOf(replaceFromString);
        diseaseInsertGenStmt.replace(fromStringIndex, fromStringIndex + replaceFromString.length(),
                fromStringReplacement);
        insertsForDiseaseTestData
                .addAll(diseaseDevJdbcTemplate.queryForList(diseaseInsertGenStmt.toString(), String.class));
    }

    // Log the generated disease test data insert statements if debug is enabled
    if (logger.isDebugEnabled()) {
        logGenSQLStmtsToDebug("disease specific", insertsForDiseaseTestData);
    }

    // If the list of generated SQL statements is not empty execute the insert statements against the users local disease test
    // schema referenced by diseaseLocalJdbcTemplate, otherwise do nothing and log a warning statement
    if (insertsForDiseaseTestData.isEmpty())
        logger.warn("No insert statements were generated using SQL script file '" + sqlScriptFileNameURL + "'. "
                + "Disease specific test data will not be loaded.");
    else {
        diseaseLocalJdbcTemplate.batchUpdate(
                stripEndingSemicolonFromSQLStmts(insertsForDiseaseTestData).toArray(new String[] {}));
        logger.info("Disease specific test data loaded successfully.");
    }
}

From source file:net.duckling.ddl.web.controller.team.ConfigTeamController.java

private String getUIDString(String[] uids) {
    StringBuilder result = new StringBuilder();
    if (null != uids && uids.length > 0) {
        for (String uid : uids) {
            result.append(uid + ",");
        }/*from w  w  w.  j  a  va2s.  c om*/
        result.replace(result.lastIndexOf(","), result.length(), "");
    }
    return result.toString();
}

From source file:ru.gkpromtech.exhibition.db.Table.java

public <F extends Entity, S extends Entity> List<Pair<F, S>> selectLinked(Class<F> f, Class<S> s,
        String selection, String[] selectionArgs, String orderBy)
        throws InvalidClassException, IllegalAccessException, InstantiationException {

    if (mFks.length != 2)
        throw new InvalidClassException("Entity " + mEntityClass.getName() + " is not a link");

    List<Pair<F, S>> result = new ArrayList<>();
    FkInfo fk1;// ww w .j av a  2 s  .c  o  m
    FkInfo fk2;

    if (mFks[0].entityClass.equals(f) && mFks[1].entityClass.equals(s)) {
        fk1 = mFks[0];
        fk2 = mFks[1];
    } else if (mFks[1].entityClass.equals(f) && mFks[0].entityClass.equals(s)) {
        //     ?   ?? ?
        fk1 = mFks[1];
        fk2 = mFks[0];
    } else {
        throw new InvalidClassException("Invalid classes passed as arguments");
    }

    Table<F> table1 = ((DbHelper) mSqlHelper).getTableFor(f);
    Table<S> table2 = ((DbHelper) mSqlHelper).getTableFor(s);

    StringBuilder query = new StringBuilder();
    for (String column : table1.mColumns) {
        query.append(",f.").append(column);
    }
    for (String column : table2.mColumns)
        query.append(",s.").append(column);
    query.replace(0, 1, "SELECT ");

    query.append("\nFROM ").append(mTableName).append(" t\nJOIN ").append(table1.mTableName).append(" f ON f.")
            .append(fk1.fkName).append(" = t.").append(fk1.fieldName).append("\nJOIN ")
            .append(table2.mTableName).append(" s ON s.").append(fk2.fkName).append(" = t.")
            .append(fk2.fieldName);
    if (selection != null)
        query.append("\nWHERE ").append(selection);
    if (orderBy != null)
        query.append("\nORDER BY ").append(orderBy);

    String queryString = query.toString();
    if (BuildConfig.DEBUG)
        Log.d("PP", queryString);

    SQLiteDatabase db = mSqlHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery(queryString, selectionArgs);

    //noinspection TryFinallyCanBeTryWithResources
    try {
        while (cursor.moveToNext()) {
            F entity1 = f.newInstance();
            S entity2 = s.newInstance();
            for (int i = 0; i < table1.mFields.length; ++i)
                fillFieldValue(table1.mType[i], table1.mFields[i], entity1, cursor, i);
            for (int i = 0; i < table2.mFields.length; ++i)
                fillFieldValue(table2.mType[i], table2.mFields[i], entity2, cursor, table1.mFields.length + i);
            result.add(new Pair<>(entity1, entity2));
        }
    } finally {
        cursor.close();
        db.close();
    }

    return result;
}

From source file:org.wso2.carbon.governance.registry.extensions.executors.ServiceVersionExecutor.java

private void updateSchemaRelativePaths(String targetEnvironment, String currentEnvironment,
        StringBuilder resourceContent, Map.Entry<String, String> newPathMappingsEntry) {
    try {//  w w  w.j  a v a2  s  .c o  m
        OMElement contentElement = AXIOMUtil.stringToOM(resourceContent.toString());
        updateRelativePath(targetEnvironment, currentEnvironment, contentElement, newPathMappingsEntry);
        resourceContent.replace(0, resourceContent.length(), contentElement.toString());
    } catch (XMLStreamException e) {
        log.error(e);
    }
}

From source file:org.orcid.persistence.dao.impl.OrcidOauth2TokenDetailDaoImpl.java

@Override
@Transactional//from  w w  w . j a  v  a 2s.  co m
@ExcludeFromProfileLastModifiedUpdate
public void removeByAuthenticationKeyOrTokenValueOrRefreshTokenValue(String authenticationKey,
        String tokenValue, String refreshTokenValue) {
    String or = " or ";
    Map<String, String> queryParams = new HashMap<String, String>();

    StringBuilder queryString = new StringBuilder("delete from OrcidOauth2TokenDetail where (");
    if (StringUtils.isNotBlank(authenticationKey)) {
        queryString.append("authenticationKey = :authenticationKey" + or);
        queryParams.put("authenticationKey", authenticationKey);
    }
    if (StringUtils.isNotBlank(tokenValue)) {
        queryString.append("tokenValue = :tokenValue" + or);
        queryParams.put("tokenValue", tokenValue);
    }
    if (StringUtils.isNotBlank(refreshTokenValue)) {
        queryString.append("refreshTokenValue = :refreshTokenValue" + or);
        queryParams.put("refreshTokenValue", refreshTokenValue);
    }

    if (!queryParams.isEmpty()) {
        queryString.replace(queryString.length() - or.length(), queryString.length(), ")");
        Query query = entityManager.createQuery(queryString.toString());
        for (String key : queryParams.keySet()) {
            query.setParameter(key, queryParams.get(key));
        }
        int i = query.executeUpdate();
        LOGGER.debug(i + " tokens deleted as a result of the parameters {}", queryParams);
    } else {
        LOGGER.info("Attempted to delete tokens with no parameters");
    }

}

From source file:net.acesinc.nifi.processors.security.ConvertSecurityMarkingAndAttrListIntoJson.java

public String getBuiltRegexForClassification(FlowAttrSecurityConfig secConfig) {
    final ComponentLog logger = getLogger();
    String dlm = secConfig.getDelim();
    StringBuilder regexPrefixForClass = new StringBuilder();
    regexPrefixForClass.append("(");
    for (String abbrev : secConfig.getAbbreviatedLevelsCanReceive()) {
        regexPrefixForClass.append(abbrev);
        regexPrefixForClass.append("|");
    }//  w w  w . j  a  v a  2 s .c  o m
    for (String classPart : secConfig.getLevelsCanReceive()) {
        regexPrefixForClass.append(classPart);
        regexPrefixForClass.append("|");
    }
    //this is awkward, but does the trick
    int lastIndexOfPipe = regexPrefixForClass.lastIndexOf("|");
    regexPrefixForClass = regexPrefixForClass.replace(lastIndexOfPipe, regexPrefixForClass.length(), "");
    regexPrefixForClass.append(")");
    String regexSuffixForClass = "[A-Za-z" + dlm + "]+";
    regexPrefixForClass.append(regexSuffixForClass);
    String regexForClass = regexPrefixForClass.toString();
    logger.debug("built regex for classification part:=" + regexForClass);
    return regexForClass;
}

From source file:info.mikaelsvensson.devtools.sitesearch.SiteSearchPlugin.java

private boolean modifyStringBuilder(final StringBuilder sb, final Pattern insertionPointPattern,
        final ModifyAction modifyAction, final String text) {
    Matcher matcher = insertionPointPattern.matcher(sb);
    if (matcher.find()) {
        switch (modifyAction) {
        case APPEND:
            sb.insert(matcher.end(), text);
            return true;
        case PREPEND:
            sb.insert(matcher.start(), text);
            return true;
        case REPLACE:
            sb.replace(matcher.start(), matcher.end(), text);
            return true;
        }//w  w w .java2  s .  c  o  m
    }
    return false;
}

From source file:uk.co.tfd.sm.memory.ehcache.CacheManagerServiceImpl.java

private InputStream processConfig(InputStream in, Map<String, Object> properties) throws IOException {
    if (in == null) {
        return null;
    }//from   www. ja va  2s  .  c o  m
    StringBuilder config = new StringBuilder(IOUtils.toString(in, "UTF-8"));
    in.close();
    int pos = 0;
    for (;;) {
        int start = config.indexOf("${", pos);
        if (start < 0) {
            break;
        }
        int end = config.indexOf("}", start);
        if (end < 0) {
            throw new IllegalArgumentException("Config file malformed, unterminated variable "
                    + config.substring(start, Math.min(start + 10, config.length())));
        }
        String key = config.substring(start + 2, end);
        if (properties.containsKey(key)) {
            String replacement = (String) properties.get(key);
            config.replace(start, end + 1, replacement);
            pos = start + replacement.length();
        } else {
            throw new IllegalArgumentException("Missing replacement property " + key);
        }
    }
    return new ByteArrayInputStream(config.toString().getBytes("UTF-8"));

}

From source file:com.dockdocker.monitoring.RequestHandler.java

/**
 * Retrieve list of containers with full container information
 * @return list with container information
 *//*from   w  ww .  ja  v  a2 s . c om*/
public String getContainerList() {
    // Get base container list
    LogHandler.submitLogEntry("GetContainerList called, retrieving base container list");
    JSONArray containerListBase = getBaseContainerList();

    // Prepare stringbuilder
    StringBuilder containerListFull = new StringBuilder();

    // Append array start
    containerListFull.append("[");

    // For every container in the base list
    LogHandler.submitLogEntry("Retrieving specific container information for every container in base list");
    for (int i = 0; i < containerListBase.length(); i++) {
        // Get container
        JSONObject container = containerListBase.getJSONObject(i);

        // Retrieve id
        String id = container.getString("Id");

        // Retrieve status
        String status = container.getString("Status");

        // Retrieve full data of the specific container
        String containerInfo = retrieveContainerInfo(id);

        // Append container info
        containerListFull.append(containerInfo);

        // Append status from JSONobject container
        containerListFull.replace(containerListFull.length() - 1, containerListFull.length(),
                ",\"Status\":\"" + status + "\"}");

        // If not last
        if (containerListBase.length() - 1 != i) {
            // Append comma
            containerListFull.append(",");
        }
    }
    // Close JSON array
    containerListFull.append("]");

    // Return result
    LogHandler.submitLogEntry("Request getContainerList finished, returning result");
    return containerListFull.toString();
}