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

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

Introduction

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

Prototype

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

Source Link

Document

Replaces all occurrences of a String within another String.

A null reference passed to this method is a no-op.

 StringUtils.replace(null, *, *)        = null StringUtils.replace("", *, *)          = "" StringUtils.replace("any", null, *)    = "any" StringUtils.replace("any", *, null)    = "any" StringUtils.replace("any", "", *)      = "any" StringUtils.replace("aba", "a", null)  = "aba" StringUtils.replace("aba", "a", "")    = "b" StringUtils.replace("aba", "a", "z")   = "zbz" 

Usage

From source file:com.google.dart.java2dart.SyntaxTranslatorTest.java

void printFormattedSource() {
    translate();/*from  w ww  . j a  va2 s. c  o m*/
    String source = toFormattedSource(dartUnit);
    String[] lines = StringUtils.split(source, '\n');
    for (int i = 0; i < lines.length; i++) {
        String line = lines[i];
        System.out.print("\"");
        line = StringUtils.replace(line, "\"", "\\\"");
        System.out.print(line);
        if (i != lines.length - 1) {
            System.out.println("\",");
        } else {
            System.out.println("\"");
        }
    }
}

From source file:at.bitfire.davdroid.resource.LocalAddressBook.java

protected static String xNameToLabel(String xname) {
    // "X-MY_PROPERTY"
    // 1. ensure lower case -> "x-my_property"
    // 2. remove x- from beginning -> "my_property"
    // 3. replace "_" by " " -> "my property"
    // 4. capitalize -> "My Property"
    String lowerCase = StringUtils.lowerCase(xname, Locale.US),
            withoutPrefix = StringUtils.removeStart(lowerCase, "x-"),
            withSpaces = StringUtils.replace(withoutPrefix, "_", " ");
    return StringUtils.capitalize(withSpaces);
}

From source file:com.google.dart.java2dart.SyntaxTranslator.java

@Override
public boolean visit(org.eclipse.jdt.core.dom.Javadoc node) {
    StringBuilder buffer = new StringBuilder();
    {/*from   w  w w.j  a v  a2  s. c  o  m*/
        buffer.append("/**");
        for (Object javaTag : node.tags()) {
            String javaTagString = javaTag.toString();
            String dartDocString = StringUtils.replace(javaTagString, "[", "\\[");
            ;
            dartDocString = StringUtils.replace(dartDocString, "]", "\\]");
            ;
            // TODO(scheglov) improve JavaDoc translation
            //        String dartDocString = escapeDartDoc(javaTagString);
            buffer.append(dartDocString);
        }
        buffer.append("\n */\n");
    }
    StringToken commentToken = new StringToken(TokenType.STRING, buffer.toString(), 0);
    return done(Comment.createDocumentationComment(new Token[] { commentToken }));
}

From source file:com.moviejukebox.model.Movie.java

/**
 * Set the movie plot.//from  w  ww  .j  av  a 2 s.c om
 *
 * Will replace non-standard quotes and "&amp;" as needed
 *
 * @param plot
 * @param source
 * @param trimToLength
 */
public void setPlot(String plot, String source, boolean trimToLength) {
    if (StringTools.isValidString(plot)) {
        String tmpPlot = StringUtils.replace(StringTools.replaceQuotes(plot), "&amp;", "&");
        if (trimToLength) {
            tmpPlot = StringTools.trimToLength(tmpPlot, MAX_LENGTH_PLOT);
        }

        if (!tmpPlot.equalsIgnoreCase(this.plot)) {
            setDirty(DirtyFlag.INFO);
            this.plot = tmpPlot;
        }
        setOverrideSource(OverrideFlag.PLOT, source);
    }
}

From source file:com.moviejukebox.model.Movie.java

/**
 * Set the movie outline.//from www .j av a  2s.co  m
 *
 * Will replace non-standard quotes and "&amp;" as needed
 *
 * @param outline
 * @param source
 * @param trimToLength
 */
public void setOutline(String outline, String source, boolean trimToLength) {
    if (StringTools.isValidString(outline)) {
        String tmpOutline = StringUtils.replace(StringTools.replaceQuotes(outline), "&amp;", "&");
        if (trimToLength) {
            tmpOutline = StringTools.trimToLength(tmpOutline, MAX_LENGTH_OUTLINE);
        }

        if (!tmpOutline.equalsIgnoreCase(this.outline)) {
            setDirty(DirtyFlag.INFO);
            this.outline = tmpOutline;
        }
        setOverrideSource(OverrideFlag.OUTLINE, source);
    }
}

From source file:io.cloudex.cloud.impl.google.GoogleCloudServiceImpl.java

/**
 * Creates an asynchronous Query Job for a particular query on a dataset
 *
 * @param querySql  the actual query string
 * @param table the table details// ww  w  . j  a  v a 2 s. c om
 * @return a reference to the inserted query job
 * @throws IOException
 */
@Override
public String startBigDataQuery(String querySql, BigDataTable table) throws IOException {

    log.debug("Inserting Query Job: " + querySql);

    Job job = new Job();
    JobConfiguration config = new JobConfiguration();
    JobConfigurationQuery queryConfig = new JobConfigurationQuery();
    config.setQuery(queryConfig);

    job.setConfiguration(config);
    queryConfig.setQuery(querySql);

    // if a table is provided then set the large results to true and supply
    // a temp table
    if (table != null) {
        String[] names = this.getTableAndDatasetNames(table.getName());
        String insId = StringUtils.replace(instanceId, "-", "_");
        String tempTable = names[1] + '_' + insId + '_' + System.currentTimeMillis();

        TableReference tableRef = (new TableReference()).setProjectId(this.projectId).setDatasetId(names[0])
                .setTableId(tempTable);

        queryConfig.setAllowLargeResults(true);
        queryConfig.setDestinationTable(tableRef);
    }

    com.google.api.services.bigquery.Bigquery.Jobs.Insert insert = this.getBigquery().jobs().insert(projectId,
            job);

    insert.setProjectId(projectId);
    insert.setOauthToken(this.getOAuthToken());
    // TODO java.net.SocketTimeoutException: Read timed out
    JobReference jobRef = insert.execute().getJobReference();

    log.debug("Job ID of Query Job is: " + jobRef.getJobId());

    return jobRef.getJobId();
}

From source file:com.sonicle.webtop.core.app.ServiceManager.java

private boolean upgradeServiceDb(ServiceDescriptor desc, ArrayList<SqlUpgradeScript> scripts, String upgradeTag,
        boolean autoUpdate) {
    ConnectionManager conMgr = wta.getConnectionManager();
    UpgradeStatementDAO upgdao = UpgradeStatementDAO.getInstance();
    boolean requireAdmin = false;
    Connection con = null;//w  w  w . j av  a 2 s  .c o  m

    try {
        if (!scripts.isEmpty()) {
            String serviceId = desc.getManifest().getId();

            // Transforms each statement into a specific object
            List<OUpgradeStatement> stmts = new ArrayList<>();
            short sequence = 0;
            for (SqlUpgradeScript script : scripts) {
                // Extracts and inserts statements
                ArrayList<BaseScriptLine> scriptStatements = script.getStatements();
                String targetDataSource = null;
                logger.trace("Script {}: found {} statement/s", script.getFileName(), scriptStatements.size());
                for (BaseScriptLine statement : scriptStatements) {
                    sequence++;
                    String stmtType, stmtDs;
                    if (statement instanceof AnnotationLine) {
                        stmtDs = null;
                        stmtType = OUpgradeStatement.STATEMENT_TYPE_ANNOTATION;
                        if (statement instanceof DataSourceAnnotationLine) {
                            targetDataSource = ((DataSourceAnnotationLine) statement).getTargetDataSource();
                        }
                    } else if (statement instanceof SqlLine) {
                        stmtDs = targetDataSource;
                        stmtType = OUpgradeStatement.STATEMENT_TYPE_SQL;
                    } else {
                        stmtDs = null;
                        stmtType = OUpgradeStatement.STATEMENT_TYPE_COMMENT;
                    }
                    stmts.add(new OUpgradeStatement(upgradeTag, serviceId, sequence, script.getFileName(),
                            stmtDs, stmtType, statement.getText()));
                }
            }

            // Inserts extracted statements into a dedicated table
            con = conMgr.getConnection();
            Integer maxId = upgdao.maxId(con);
            int count = upgdao.batchInsert(con, stmts);
            if (count != sequence)
                throw new WTException("Statements insertion not fully completed [total: {0}, inserted: {1}]",
                        sequence, count);

            // Reads all inserted statements (NB: id needs to be refreshed because it comes from a db sequence)
            stmts = upgdao.selectFromIdByTagService(con, maxId == null ? -1 : maxId, upgradeTag, serviceId);
            if (stmts.isEmpty()) {
                logger.debug("DB upgrade is not necessary [{}]", serviceId);
            } else {
                if (!autoUpdate) { // Manual
                    requireAdmin = true;

                } else { // Auto: Runs statements...
                    HashMap<String, Connection> conCache = new HashMap<>();
                    try {
                        logger.debug("Executing upgrade statements [{}, {}]", serviceId, stmts.size());
                        boolean ignoreErrors = false;
                        for (OUpgradeStatement stmt : stmts) {

                            if (stmt.getStatementType().equals(OUpgradeStatement.STATEMENT_TYPE_ANNOTATION)) {
                                if (RequireAdminAnnotationLine.matches(stmt.getStatementBody())) {
                                    logger.trace("[{}, {}]: {}", stmt.getServiceId(), stmt.getSequenceNo(),
                                            stmt.getStatementBody());
                                    requireAdmin = true;
                                    break; // Stops iteration!
                                } else if (IgnoreErrorsAnnotationLine.matches(stmt.getStatementBody())) {
                                    ignoreErrors = true; // Sets value! (for next sql statement)
                                }

                            } else if (stmt.getStatementType().equals(OUpgradeStatement.STATEMENT_TYPE_SQL)) {
                                final String sds = stmt.getStatementDataSource();
                                if (StringUtils.isBlank(sds))
                                    throw new WTException("Statement does not provide a DataSource [{0}]",
                                            stmt.getUpgradeStatementId());
                                if (!conCache.containsKey(sds)) {
                                    conCache.put(sds, getUpgradeStatementConnection(conMgr, stmt));
                                }
                                boolean ret = executeUpgradeStatement(conCache.get(sds), stmt, ignoreErrors);
                                try {
                                    upgdao.update(con, stmt);
                                } catch (DAOException ex) {
                                    throw new WTException("Unable to update statement status!", ex);
                                }
                                if (!ret) { // In case of errors...
                                    requireAdmin = true;
                                    break; // Stops iteration!
                                }
                                ignoreErrors = false; // Resets value!

                            } else {
                                logger.trace("[{}, {}]: !!! {}", stmt.getServiceId(), stmt.getSequenceNo(),
                                        StringUtils.replace(stmt.getStatementBody(), "\n", " "));
                            }
                        }
                    } finally {
                        if (!conCache.isEmpty()) {
                            logger.trace("Closing connections [{}]", conCache.size());
                            Iterator<Entry<String, Connection>> it = conCache.entrySet().iterator();
                            while (it.hasNext()) {
                                final Entry<String, Connection> entry = it.next();
                                DbUtils.closeQuietly(entry.getValue());
                                it.remove();
                            }
                        }
                    }
                }
            }
        }
    } catch (Throwable t) {
        requireAdmin = true;
        logger.error("Error handling upgrade script", t);
    } finally {
        DbUtils.closeQuietly(con);
        return requireAdmin;
    }
}

From source file:cx.fbn.nevernote.gui.BrowserWindow.java

public void insertLink() {
    logger.log(logger.EXTREME, "Inserting link");
    String text = browser.selectedText();
    if (text.trim().equalsIgnoreCase(""))
        return;//from w  w w  .ja va  2 s .c o m

    InsertLinkDialog dialog = new InsertLinkDialog(insertHyperlink);
    if (currentHyperlink != null && currentHyperlink != "") {
        dialog.setUrl(currentHyperlink);
    }
    dialog.exec();
    if (!dialog.okPressed()) {
        logger.log(logger.EXTREME, "Insert link canceled");
        return;
    }

    // Take care of inserting new links
    if (insertHyperlink) {
        String selectedText = browser.selectedText();
        if (dialog.getUrl().trim().equals(""))
            return;
        logger.log(logger.EXTREME, "Inserting link on text " + selectedText);
        logger.log(logger.EXTREME, "URL Link " + dialog.getUrl().trim());
        String dUrl = StringUtils.replace(dialog.getUrl().trim(), "'", "\\'");
        String url = "<a href=\"" + dUrl + "\" title=" + dUrl + " >" + selectedText + "</a>";
        String script = "document.execCommand('insertHtml', false, '" + url + "');";
        browser.page().mainFrame().evaluateJavaScript(script);
        return;
    }

    // Edit existing links
    String js = new String("function getCursorPos() {" + "var cursorPos;" + "if (window.getSelection) {"
            + "   var selObj = window.getSelection();" + "   var selRange = selObj.getRangeAt(0);"
            + "   var workingNode = window.getSelection().anchorNode.parentNode;"
            + "   while(workingNode != null) { "
            + "      if (workingNode.nodeName.toLowerCase()=='a') workingNode.setAttribute('href','"
            + dialog.getUrl() + "');" + "      workingNode = workingNode.parentNode;" + "   }" + "}"
            + "} getCursorPos();");
    browser.page().mainFrame().evaluateJavaScript(js);

    if (!dialog.getUrl().trim().equals("")) {
        contentChanged();
        return;
    }

    // Remove URL
    js = new String("function getCursorPos() {" + "var cursorPos;" + "if (window.getSelection) {"
            + "   var selObj = window.getSelection();" + "   var selRange = selObj.getRangeAt(0);"
            + "   var workingNode = window.getSelection().anchorNode.parentNode;"
            + "   while(workingNode != null) { " + "      if (workingNode.nodeName.toLowerCase()=='a') { "
            + "         workingNode.removeAttribute('href');" + "         workingNode.removeAttribute('title');"
            + "         var text = document.createTextNode(workingNode.innerText);"
            + "         workingNode.parentNode.insertBefore(text, workingNode);"
            + "         workingNode.parentNode.removeChild(workingNode);" + "      }"
            + "      workingNode = workingNode.parentNode;" + "   }" + "}" + "} getCursorPos();");
    browser.page().mainFrame().evaluateJavaScript(js);

    contentChanged();

}

From source file:cx.fbn.nevernote.gui.BrowserWindow.java

public void editLatex(String guid) {
    logger.log(logger.EXTREME, "Inserting latex");
    String text = browser.selectedText();
    if (text.trim().equalsIgnoreCase("\n") || text.trim().equalsIgnoreCase("")) {
        InsertLatexImage dialog = new InsertLatexImage();
        if (guid != null) {
            String formula = conn.getNoteTable().noteResourceTable.getNoteSourceUrl(guid)
                    .replace("http://latex.codecogs.com/gif.latex?", "");
            dialog.setFormula(formula);//from w w w  .  j a va2  s  .  c o m
        }
        dialog.exec();
        if (!dialog.okPressed()) {
            logger.log(logger.EXTREME, "Edit LaTex canceled");
            return;
        }
        text = dialog.getFormula().trim();
    }
    blockApplication.emit(this);
    logger.log(logger.EXTREME, "Inserting LaTeX formula:" + text);
    latexGuid = guid;
    text = StringUtils.replace(text, "'", "\\'");
    String url = "http://latex.codecogs.com/gif.latex?" + text;
    logger.log(logger.EXTREME, "Sending request to codecogs --> " + url);
    QNetworkAccessManager manager = new QNetworkAccessManager(this);
    manager.finished.connect(this, "insertLatexImageReady(QNetworkReply)");
    unblockTime = new GregorianCalendar().getTimeInMillis() + 5000;
    awaitingHttpResponse = true;
    manager.get(new QNetworkRequest(new QUrl(url)));
}

From source file:com.google.dart.java2dart.SyntaxTranslator.java

@Override
public boolean visit(org.eclipse.jdt.core.dom.StringLiteral node) {
    String tokenValue = node.getEscapedValue();
    tokenValue = StringUtils.replace(tokenValue, "$", "\\$");
    SimpleStringLiteral literal = new SimpleStringLiteral(token(TokenType.STRING, tokenValue),
            node.getLiteralValue());/*from  w  w  w. ja va2  s. com*/
    context.putNodeTypeBinding(literal, node.resolveTypeBinding());
    return done(literal);
}