Example usage for org.apache.commons.lang StringUtils replace

List of usage examples for org.apache.commons.lang StringUtils replace

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils replace.

Prototype

public static String replace(String text, String searchString, String replacement) 

Source Link

Document

Replaces all occurrences of a String within another String.

Usage

From source file:gsn.storage.SQLUtils.java

/**
 * Table renaming, note that the renameMapping should be a tree map. This
 * method gets a sql query and changes the table names using the mappings
 * provided in the second argument.<br>
 * // w w  w. j ava2 s  . c om
 * @param query
 * @param renameMapping
 * @return
 */
public static StringBuilder newRewrite(CharSequence query, TreeMap<CharSequence, CharSequence> renameMapping) {
    // Selecting strings between pair of "" : (\"[^\"]*\")
    // Selecting tableID.tableName or tableID.* : (\\w+(\\.(\w+)|\\*))
    // The combined pattern is : (\"[^\"]*\")|(\\w+\\.((\\w+)|\\*))
    Pattern pattern = Pattern.compile("(\"[^\"]*\")|((\\w+)(\\.((\\w+)|\\*)))", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(query);
    StringBuffer result = new StringBuffer();
    if (!(renameMapping.comparator() instanceof CaseInsensitiveComparator))
        throw new RuntimeException("Query rename needs case insensitive treemap.");
    while (matcher.find()) {
        if (matcher.group(2) == null)
            continue;
        String tableName = matcher.group(3);
        CharSequence replacement = renameMapping.get(tableName);
        // $4 means that the 4th group of the match should be appended to the
        // string (the forth group contains the field name).
        if (replacement != null)
            matcher.appendReplacement(result, new StringBuilder(replacement).append("$4").toString());
    }
    String toReturn = matcher.appendTail(result).toString().toLowerCase();

    //TODO " from " has to use regular expressions because now from is separated through space which is not always the case, for instance if the user uses \t(tab) for separating "from" from the rest of the query, then we get exception. The same issue with other sql keywords in this method.

    int indexOfFrom = toReturn.indexOf(" from ") >= 0 ? toReturn.indexOf(" from ") + " from ".length() : 0;
    int indexOfWhere = (toReturn.lastIndexOf(" where ") > 0 ? (toReturn.lastIndexOf(" where "))
            : toReturn.length());
    String selection = toReturn.substring(indexOfFrom, indexOfWhere);
    Pattern fromClausePattern = Pattern.compile("\\s*(\\w+)\\s*", Pattern.CASE_INSENSITIVE);
    Matcher fromClauseMather = fromClausePattern.matcher(selection);
    result = new StringBuffer();
    while (fromClauseMather.find()) {
        if (fromClauseMather.group(1) == null)
            continue;
        String tableName = fromClauseMather.group(1);
        CharSequence replacement = renameMapping.get(tableName);
        if (replacement != null)
            fromClauseMather.appendReplacement(result, replacement.toString() + " ");
    }
    String cleanFromClause = fromClauseMather.appendTail(result).toString();
    String finalResult = StringUtils.replace(toReturn, selection, cleanFromClause);
    return new StringBuilder(finalResult);
}

From source file:com.alibaba.otter.canal.extend.communication.CanalCommmunicationClient.java

public void setManagerAddress(String managerAddress) {
    String server = StringUtils.replace(managerAddress, ";", ",");
    String[] servers = StringUtils.split(server, ',');
    this.managerAddress = Arrays.asList(servers);
    this.index = RandomUtils.nextInt(this.managerAddress.size()); // ??
}

From source file:com.dianping.lion.service.impl.DefaultConfigValueResolver.java

@Override
public String resolve(String configval, int envId) {
    if (configval == null) {
        return null;
    }/*from   w ww .j av a2 s  .  c o  m*/
    if (configval.contains(ServiceConstants.REF_CONFIG_PREFIX)) {
        try {
            Matcher matcher = ServiceConstants.REF_EXPR_PATTERN.matcher(configval);
            boolean referenceFound = false;
            StringBuffer buffer = new StringBuffer(configval.length() * 2);
            while (matcher.find()) {
                referenceFound = true;
                String refkey = matcher.group(1);
                Config refconfig = configService.findConfigByKey(refkey);
                if (refconfig == null) {
                    logger.warn("Referenced config[" + refkey + "] not found.");
                    return null;
                }
                ConfigInstance refinstance = configService.findInstance(refconfig.getId(), envId,
                        ConfigInstance.NO_CONTEXT);
                if (refinstance == null) {
                    logger.warn("Referenced config[" + refkey + "] with env[" + envId + "] not found.");
                    return null;
                }
                String refval = refinstance.getValue();
                if (refval == null) {
                    logger.warn("Reference null-valued config[" + refkey + "] with env[" + envId + "].");
                    return null;
                }
                String refparams = matcher.group(3);
                if (StringUtils.isNotBlank(refparams)) {
                    String[] paramList = StringUtils.split(refparams, "&");
                    for (String paramstr : paramList) {
                        String[] paramentry = StringUtils.split(paramstr, "=");
                        refval = StringUtils.replace(refval, "${" + paramentry[0] + "}", paramentry[1]);
                    }
                }
                matcher.appendReplacement(buffer, Matcher.quoteReplacement(refval));
            }
            if (referenceFound) {
                matcher.appendTail(buffer);
                return buffer.toString();
            }
        } catch (RuntimeException e) {
            logger.error("Resolve referenced config expression[" + configval + "] failed.", e);
            throw e;
        }
    }
    return configval;
}

From source file:com.voa.weixin.task.UpdateFileTask.java

@Override
public void generateUrl() {
    this.url = StringUtils.replace(url, "ACCESS_TOKEN", Carp.token);
    this.url = StringUtils.replace(url, "TYPE", this.type);
}

From source file:edu.ku.brc.specify.rstools.SpAnalysis.java

public void checkAgents(final TableWriter tblWriter) {
    tblWriter.append("<H3>Agents</H3>");
    tblWriter.startTable();//from  w w w .  j a va  2  s.  c  om
    tblWriter.append(
            "<TR><TH>AgentID</TH><TH>LastName</TH><TH>FirstName</TH><TH>MiddleInitial</TH><TH>Ids</TH></TR>");

    Statement stmt = null;
    Statement stmt2 = null;
    try {
        Integer cnt = BasicSQLUtils.getCount(
                "SELECT (COUNT(LOWER(nm)) - COUNT(DISTINCT LOWER(nm))) AS DIF  FROM (SELECT CONCAT(LN,FN,MI) NM FROM(select IFNULL(LastName, '') LN, IFNULL(FirstName, '') FN, IFNULL(MiddleInitial, '') MI from agent) T1) T2");
        if (cnt != null && cnt > 0) {
            String sql = "SELECT AgentID, LOWER(nm) C1 FROM (SELECT AgentID, CONCAT(LN,FN,MI) NM FROM (select AgentID, IFNULL(LastName, '') LN, IFNULL(FirstName, '') FN, IFNULL(MiddleInitial, '') MI from agent) T1) T2 ";

            Vector<Integer> extraIds = new Vector<Integer>();

            Connection conn = DBConnection.getInstance().getConnection();
            stmt = conn.createStatement();
            stmt2 = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql + "  ORDER BY AgentID");
            while (rs.next()) {
                int id = rs.getInt(1);
                String str = rs.getString(2);

                extraIds.clear();

                str = StringUtils.replace(str, "'", "''");
                String sql2 = sql + " WHERE LOWER(nm) = '" + str + "' AND AgentID > " + id
                        + "  ORDER BY AgentID";

                //System.err.println(sql2);

                int dupCnt = 0;
                ResultSet rs2 = stmt2.executeQuery(sql2);
                while (rs2.next()) {
                    extraIds.add(rs2.getInt(1));
                    dupCnt++;
                }
                rs2.close();

                if (dupCnt > 0) {
                    String s = "SELECT AgentID, LastName, FirstName, MiddleInitial FROM agent WHERE AgentID = "
                            + id;
                    Vector<Object[]> rows = BasicSQLUtils.query(s);
                    Object[] row = rows.get(0);
                    tblWriter.append("<TR><TD>" + row[0] + "</TD><TD>" + row[1] + "</TD><TD>" + row[2]
                            + "</TD><TD>" + row[3] + "</TD><TD>");
                    for (int i = 0; i < extraIds.size(); i++) {
                        if (i > 0)
                            tblWriter.log(", ");
                        tblWriter.append(extraIds.get(i).toString());
                    }
                    tblWriter.append("</TD></TR>");
                }
            }
            rs.close();
        }

    } catch (Exception ex) {
        ex.printStackTrace();

    } finally {
        try {
            if (stmt != null) {
                stmt.close();
            }
            if (stmt2 != null) {
                stmt2.close();
            }
        } catch (Exception ex) {
        }
    }

    tblWriter.endTable();
}

From source file:net.sf.groovyMonkey.actions.CreateGroovyMonkeyExamplesAction.java

public void run(final IAction action) {
    final IWorkspace workspace = getWorkspace();
    final IProject project = workspace.getRoot().getProject(SCRIPTS_PROJECT);
    try {// www.ja v a2  s.co m
        final List<URL> examples = getExampleScripts(getDefault().getBundle());
        if (!project.exists())
            project.create(null);
        project.open(null);

        String errors = "";
        for (final URL example : examples) {
            try {
                final String filePath = example.getFile();
                final String[] words = filePath.split("/");
                final String fileName = words[words.length - 1];
                final IFolder folder = project.getFolder("/" + MONKEY_DIR);
                if (!folder.exists())
                    folder.create(IResource.NONE, true, null);
                final InputStream input = example.openStream();
                try {
                    final IFile file = folder.getFile(fileName);
                    final String contents = StringUtils.replace(IOUtils.toString(input), "\r\n", "\n");
                    file.create(new ByteArrayInputStream(contents.getBytes()), false, null);
                } finally {
                    closeQuietly(input);
                }
            } catch (final CoreException x) {
                errors += x.toString() + "\n";
            } catch (final IOException x) {
                errors += x.toString() + "\n";
            }
        }
        if (errors.length() > 0)
            openInformation(window.getShell(), "Groovy Monkey",
                    "Errors creating the Examples project: " + errors);
    } catch (final CoreException x) {
        openInformation(window.getShell(), "Groovy Monkey",
                "Unable to create the Examples project due to " + x);
    }
}

From source file:eionet.cr.dao.virtuoso.helpers.VirtuosoTagSearchHelper.java

/**
 * Returns sorted query for tagged data search.
 *
 * @param inParams/*www.  j a  va2 s  . c  o m*/
 * @return
 */
@Override
protected String getOrderedQuery(List<Object> inParams) {

    StringBuilder strBuilder = initQueryStringBuilder();
    strBuilder.append("select distinct ?s where {").append(getWhereContents()).append("} order by ");

    // In SPARQL the sort order is placed before the sort predicate
    if (sortOrder != null) {
        strBuilder.append(sortOrder);
    }

    // If sorting is done by either rdfs:label or rdf:type, and a particular subject doesn't have
    // those predicates, then the last part of subject URI must be used instead.
    if (Predicates.RDFS_LABEL.equals(sortPredicate)) {
        strBuilder.append(
                "(bif:either( bif:isnull(?sortObject) , (bif:lcase(bif:subseq (bif:replace (?s, '/', '#'), ")
                .append("bif:strrchr (bif:replace (?s, '/', '#'), '#')+1))) , bif:lcase(?sortObject)))");
    } else if (Predicates.RDF_TYPE.equals(sortPredicate)) {
        // Replace all / with # and then get the string after last #
        strBuilder
                .append("(bif:lcase(bif:subseq (bif:replace (?sortObject, '/', '#'), bif:strrchr (bif:replace ")
                .append("(?sortObject, '/', '#'), '#')+1)))");
        // sort by date
    } else {
        strBuilder.append("(bif:lcase(?sortObject))");
    }

    return StringUtils.replace(strBuilder.toString(), "?sortObject", "?" + SORT_OBJECT_VALUE_VARIABLE);
}

From source file:eionet.cr.dao.readers.NewSourcesReaderWriter.java

@Override
public void readRow(BindingSet bindingSet) throws ResultSetReaderException {

    String sourceUrl = getFirstBindingStringValue(bindingSet);
    if (!StringUtils.isBlank(sourceUrl)) {

        // Replace spaces from url
        sourceUrl = StringUtils.replace(sourceUrl.trim(), " ", "%20");

        sourceCount++;/*  w  w  w .j  a v  a  2  s  .c  o m*/
        try {
            getPreparedStatement().setString(1, sourceUrl);
            getPreparedStatement().setLong(2, Hashes.spoHash(sourceUrl));
            getPreparedStatement().addBatch();
            currentBatchSize++;

            if (currentBatchSize == BATCH_LIMIT) {

                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Inserting " + currentBatchSize + " sources");
                }

                getPreparedStatement().executeBatch();
                getPreparedStatement().clearParameters();
                currentBatchSize = 0;

                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace(sourceCount + " sources inserted so far");
                }
            }

        } catch (SQLException e) {
            throw new ResultSetReaderException(e.getMessage(), e);
        }
    }
}

From source file:com.thoughtworks.go.buildsession.ExecCommandExecutor.java

private CommandLine createCommandLine(String cmd) {
    CommandLine commandLine;// w w  w  .j av a2s .co m
    if (SystemUtil.isWindows()) {
        commandLine = CommandLine.createCommandLine("cmd");
        commandLine.withArg("/c");
        commandLine.withArg(StringUtils.replace(cmd, "/", "\\"));
    } else {
        commandLine = CommandLine.createCommandLine(cmd);
    }
    return commandLine;
}

From source file:edu.ku.brc.specify.toycode.mexconabio.MexConvToSQLNew.java

private String fixName(final String nameArg) {
    String name = nameArg.toLowerCase();
    StringBuilder nm = new StringBuilder();
    for (int i = 0; i < name.length(); i++) {
        char c = name.charAt(i);
        if (c != ':' && c <= 'z') {
            nm.append(c);//from   ww w. j  a  v  a  2s .com
        }
    }
    return StringUtils.replace(nm.toString().trim(), " ", "_");
}