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

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

Introduction

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

Prototype

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

Source Link

Document

Replaces a String with another String inside a larger String, once.

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

 StringUtils.replaceOnce(null, *, *)        = null StringUtils.replaceOnce("", *, *)          = "" StringUtils.replaceOnce("any", null, *)    = "any" StringUtils.replaceOnce("any", *, null)    = "any" StringUtils.replaceOnce("any", "", *)      = "any" StringUtils.replaceOnce("aba", "a", null)  = "aba" StringUtils.replaceOnce("aba", "a", "")    = "ba" StringUtils.replaceOnce("aba", "a", "z")   = "zba" 

Usage

From source file:com.google.api.codegen.util.TypeName.java

/** Renders the short name of this type given its pattern. */
public String getNickname() {
    if (pattern == null) {
        return topLevelAlias.getNickname();
    }//from   ww w.ja  v  a 2 s.  c  o m
    String result = StringUtils.replaceOnce(pattern, "%s", topLevelAlias.getNickname());
    for (TypeName innerTypeName : innerTypeNames) {
        result = StringUtils.replaceOnce(result, "%i", innerTypeName.getNickname());
    }
    return result;
}

From source file:ch.icclab.cyclops.persistence.orm.InstanceORM.java

/**
 * Apply time stamp to rule definition/*w  w  w .  j a  v a2 s  .c  o  m*/
 * @return string
 */
private String applyTimeStampToRuleDefinition(String rule, String timeStamp) {
    String name = RegexParser.getNameFromRule(rule);
    String formatted = String.format("%s (%s)", name, timeStamp);

    return StringUtils.replaceOnce(rule, name, formatted);
}

From source file:com.oltpbenchmark.benchmarks.wikirest.procedures.GetPageAnonymousRest.java

public Article run(Builder builder, boolean forSelect, String userIp, int pageNamespace, String pageTitle)
        throws UserAbortException, SQLException, JSONException {
    int param = 1;

    this.builder = builder;

    String selectPage = selectPageWithVariables;

    selectPage = StringUtils.replaceOnce(selectPage, SQL_VARIABLE, Integer.toString(pageNamespace));
    selectPage = StringUtils.replaceOnce(selectPage, SQL_VARIABLE, pageTitle);

    ClientResponse response = getClient().post(ClientResponse.class, selectPage);
    if (response.getClientResponseStatus() != com.sun.jersey.api.client.ClientResponse.Status.OK) {
        throw new SQLException("Query " + selectPage + " encountered an error ");
    }/*w w  w .j a  v  a  2 s.  c  om*/

    JSONArray jsonArray = response.getEntity(JSONArray.class);
    response.close();

    if (jsonArray.length() == 0) {
        String msg = String.format("Invalid Page: Namespace:%d / Title:--%s--", pageNamespace, pageTitle);
        throw new UserAbortException(msg);
    }
    int pageId = jsonArray.getJSONObject(0).optInt("page_id");

    // selectPageRestriction
    String selectPageRestriction = selectPageRestrictionWithVariables;

    selectPageRestriction = StringUtils.replaceOnce(selectPageRestriction, SQL_VARIABLE,
            Integer.toString(pageId));

    response = getClient().post(ClientResponse.class, selectPageRestriction);
    if (response.getClientResponseStatus() != com.sun.jersey.api.client.ClientResponse.Status.OK) {
        throw new SQLException("Query " + selectPageRestriction + " encountered an error ");
    }

    jsonArray = response.getEntity(JSONArray.class);
    response.close();

    if (jsonArray.length() == 0 || !jsonArray.getJSONObject(0).has("pr_page")) {
        String msg = String.format("Invalid Page: ID:%d ", pageId);
        throw new UserAbortException(msg);
    }

    // selectIP Block
    String selectIpBlocks = selectIpBlocksWithVariables;

    selectIpBlocks = StringUtils.replaceOnce(selectIpBlocks, SQL_VARIABLE, userIp);

    response = getClient().post(ClientResponse.class, selectIpBlocks);
    if (response.getClientResponseStatus() != com.sun.jersey.api.client.ClientResponse.Status.OK) {
        throw new SQLException("Query " + selectIpBlocks + " encountered an error ");
    }

    jsonArray = response.getEntity(JSONArray.class);
    response.close();

    if (jsonArray.length() == 0 || !jsonArray.getJSONObject(0).has("ipb_id")) {
        String msg = String.format("Invalid IP Block: Ip:%d ", userIp);
        throw new UserAbortException(msg);
    }

    // selectPageRevision
    String selectPageRevision = selectPageRevisionWithVariables;

    selectPageRevision = StringUtils.replaceOnce(selectPageRevision, SQL_VARIABLE, Integer.toString(pageId));
    selectPageRevision = StringUtils.replaceOnce(selectPageRevision, SQL_VARIABLE, Integer.toString(pageId));

    response = getClient().post(ClientResponse.class, selectPageRevision);
    if (response.getClientResponseStatus() != com.sun.jersey.api.client.ClientResponse.Status.OK) {
        throw new SQLException("Query " + selectPageRevision + " encountered an error ");
    }

    jsonArray = response.getEntity(JSONArray.class);
    response.close();

    if (jsonArray.length() == 0) {
        String msg = String.format("Invalid Page: Namespace:%d / Title:--%s-- / PageId:%d", pageNamespace,
                pageTitle, pageId);
        throw new UserAbortException(msg);
    }
    int revisionId = jsonArray.getJSONObject(0).optInt("rev_id");
    int textId = jsonArray.getJSONObject(0).optInt("rev_text_id");
    ;

    // NOTE: the following is our variation of wikipedia... the original did
    // not contain old_page column!
    // sql =
    // "SELECT old_text,old_flags FROM `text` WHERE old_id = '"+textId+"'
    // AND old_page = '"+pageId+"' LIMIT 1";
    // For now we run the original one, which works on the data we have

    String selectText = selectTextWithVariables;

    selectText = StringUtils.replaceOnce(selectText, SQL_VARIABLE, Integer.toString(textId));

    response = getClient().post(ClientResponse.class, selectText);
    if (response.getClientResponseStatus() != com.sun.jersey.api.client.ClientResponse.Status.OK) {
        throw new SQLException("Query " + selectText + " encountered an error ");
    }

    jsonArray = response.getEntity(JSONArray.class);
    response.close();

    if (jsonArray.length() == 0) {
        String msg = "No such text: " + textId + " for page_id:" + pageId + " page_namespace: " + pageNamespace
                + " page_title:" + pageTitle;
        throw new UserAbortException(msg);
    }

    Article a = null;
    if (!forSelect)
        a = new Article(userIp, pageId, jsonArray.getJSONObject(0).optString("old_text"), textId, revisionId);
    return a;
}

From source file:com.google.api.codegen.util.TypeName.java

/**
 * Renders the short name of this type given its pattern, and adds any necessary nicknames to the
 * given type table.//from   ww w. ja v  a2  s. c o m
 */
public String getAndSaveNicknameIn(TypeTable typeTable) {
    String topLevelNickname = typeTable.getAndSaveNicknameFor(topLevelAlias);
    if (pattern == null) {
        return topLevelNickname;
    }
    String result = StringUtils.replaceOnce(pattern, "%s", topLevelNickname);
    for (TypeName innerTypeName : innerTypeNames) {
        result = StringUtils.replaceOnce(result, "%i", innerTypeName.getAndSaveNicknameIn(typeTable));
    }
    return result;
}

From source file:com.gargoylesoftware.htmlunit.javascript.regexp.HtmlUnitRegExpProxy.java

private Object doAction(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args,
        final int actionType) {
    // in a first time just improve replacement with a String (not a function)
    if (RA_REPLACE == actionType && args.length == 2 && (args[1] instanceof String)) {
        final String thisString = Context.toString(thisObj);
        String replacement = (String) args[1];
        final Object arg0 = args[0];
        if (arg0 instanceof String) {
            replacement = REPLACE_PATTERN.matcher(replacement).replaceAll("\\$");
            // arg0 should *not* be interpreted as a RegExp
            return StringUtils.replaceOnce(thisString, (String) arg0, replacement);
        } else if (arg0 instanceof NativeRegExp) {
            try {
                final NativeRegExp regexp = (NativeRegExp) arg0;
                final RegExpData reData = new RegExpData(regexp);
                final String regex = reData.getJavaPattern();
                final int flags = reData.getJavaFlags();
                final Pattern pattern = Pattern.compile(regex, flags);
                final Matcher matcher = pattern.matcher(thisString);
                return doReplacement(thisString, replacement, matcher, reData.hasFlag('g'));
            } catch (final PatternSyntaxException e) {
                LOG.warn(e.getMessage(), e);
            }/*from  w  ww.j  a va  2  s .  c  om*/
        }
    } else if (RA_MATCH == actionType || RA_SEARCH == actionType) {
        if (args.length == 0) {
            return null;
        }
        final Object arg0 = args[0];
        final String thisString = Context.toString(thisObj);
        final RegExpData reData;
        if (arg0 instanceof NativeRegExp) {
            reData = new RegExpData((NativeRegExp) arg0);
        } else {
            reData = new RegExpData(Context.toString(arg0));
        }

        final Pattern pattern = Pattern.compile(reData.getJavaPattern(), reData.getJavaFlags());
        final Matcher matcher = pattern.matcher(thisString);

        final boolean found = matcher.find();
        if (RA_SEARCH == actionType) {
            if (found) {
                setProperties(matcher, thisString, matcher.start(), matcher.end());
                return matcher.start();
            }
            return -1;
        }

        if (!found) {
            return null;
        }
        final int index = matcher.start(0);
        final List<Object> groups = new ArrayList<>();
        if (reData.hasFlag('g')) { // has flag g
            groups.add(matcher.group(0));
            setProperties(matcher, thisString, matcher.start(0), matcher.end(0));

            while (matcher.find()) {
                groups.add(matcher.group(0));
                setProperties(matcher, thisString, matcher.start(0), matcher.end(0));
            }
        } else {
            for (int i = 0; i <= matcher.groupCount(); i++) {
                Object group = matcher.group(i);
                if (group == null) {
                    group = Context.getUndefinedValue();
                }
                groups.add(group);
            }

            setProperties(matcher, thisString, matcher.start(), matcher.end());
        }
        final Scriptable response = cx.newArray(scope, groups.toArray());
        // the additional properties (cf ECMA script reference 15.10.6.2 13)
        response.put("index", response, Integer.valueOf(index));
        response.put("input", response, thisString);
        return response;
    }

    return wrappedAction(cx, scope, thisObj, args, actionType);
}

From source file:de.dennishoersch.web.jsf.resources.stylesheet.ImportInliner.java

private String replaceImports(String line, Pattern withUrl) throws IOException {
    String result = line;/*from  ww w .ja va2 s . c  o m*/
    Matcher matcher = withUrl.matcher(line);
    while (matcher.find()) {
        String importTag = matcher.group(1);
        String importedStylesheet = inlineImport(importTag);
        if (importedStylesheet != null) {
            result = StringUtils.replaceOnce(result, matcher.group(), importedStylesheet);
        }
    }
    return result;
}

From source file:com.avast.server.hdfsshell.ui.ShellPromptProvider.java

private String getShortCwd() {
    String currentDir = contextCommands.getCurrentDir();
    if (currentDir.startsWith("/user/")) {
        final String userHome = "/user/" + this.getWhoami();//call getWhoami later
        if (currentDir.startsWith(userHome)) {
            currentDir = StringUtils.replaceOnce(currentDir, userHome, "~");
        }//from ww  w  .  j a  va2 s .co m
    }
    return currentDir;
}

From source file:de.dennishoersch.web.css.images.ImagesInliner.java

private String inlineIfNeccessary(String line) throws IOException {
    String result = line;// w  ww.  j  ava 2s  . c om
    Matcher matcher = _URL.matcher(line);
    while (matcher.find()) {
        String url = matcher.group(1);
        String inlined = inlineUrl(url.replace("'", "").replace("\"", ""));
        if (inlined != null) {
            inlined = "url(data:" + inlined + ")";
            result = StringUtils.replaceOnce(result, matcher.group(), inlined);
        }
    }
    return result;
}

From source file:com.nuvolect.deepdive.util.OmniUtil.java

/**
 * Get a Omni style relative path given a volume ID and an absolute path.
 * @param volumeId//www .  j  a v  a 2  s .  c o m
 * @param absolutePath
 * @return relative Omni path.
 */
public static String getShortPath(String volumeId, String absolutePath) {

    String root = Omni.getRoot(volumeId);
    String absPath = (absolutePath + "/").replace("//", "/");
    return StringUtils.replaceOnce(absPath, root, "/");
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlInput2Test.java

private void testClickEventSequence(final String input, final boolean onClickRetFalse) throws Exception {
    final String events = " onmousedown=\"log('mousedown')\" onmouseup=\"log('mouseup')\" "
            + "onfocus=\"log('onfocus')\" onchange=\"log('onchange')\" " + "onclick=\"log('onclick')\"";
    String tag = StringUtils.replaceOnce(input, ">", events + ">");
    if (onClickRetFalse) {
        tag = StringUtils.replaceOnce(tag, "onclick')", "onclick');return false;");
    }/* w w  w  . java2 s  .c o  m*/

    final String html = "<html><head>\n" + "<script>\n" + "  function log(x) {\n"
            + "    document.getElementById('log_').value += x + '; ';\n" + "  }\n" + "</script>\n"

            + "</head>\n<body>\n" + "<form>\n" + "  <textarea id='log_' rows='4' cols='50'></textarea>\n" + tag
            + "\n" + "  <input type='text' id='next'>\n" + "</form>\n"

            + "</body></html>";

    final List<String> alerts = new LinkedList<>();

    final WebDriver driver = loadPage2(html);
    final WebElement log = driver.findElement(By.id("log_"));

    driver.findElement(By.id(TEST_ID)).click();
    alerts.add(log.getAttribute("value").trim());

    log.clear();
    driver.findElement(By.id("next")).click();

    alerts.add(log.getAttribute("value").trim());
    assertEquals(getExpectedAlerts(), alerts);
}