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:org.biokoframework.system.repository.sql.MySQLConnector.java

@Inject
public MySQLConnector(@Named("dbUrl") String dbUrl, @Named("dbName") String dbName,
        @Named("dbUser") String dbUser, @Named("dbPassword") String dbPassword,
        @Named("dbPort") String dbPort) {

    dbUrl = StringUtils.replace(dbUrl, "${dbName}", dbName);
    dbUrl = StringUtils.replace(dbUrl, "${dbUser}", dbUser);
    dbUrl = StringUtils.replace(dbUrl, "${dbPassword}", dbPassword);
    fUrl = StringUtils.replace(dbUrl, "${dbPort}", dbPort);

    loadDriver();/* w  ww  .jav  a  2 s.c  o m*/
}

From source file:org.blocks4j.reconf.client.config.update.ConfigurationUpdater.java

private void setUpdaterName() {
    setName(StringUtils.replace(methodCfg.getMethod().toString(), "public abstract ", "") + "_"
            + getUpdaterType() + "_updater"
            + StringUtils.replace(new Object().toString(), "java.lang.Object", ""));
}

From source file:org.blocks4j.reconf.client.constructors.SimpleConstructor.java

public Object construct(MethodData data) throws Throwable {
    Class<?> returnClass = (Class<?>) data.getReturnType();

    String trimmed = StringUtils.defaultString(StringUtils.trim(data.getValue()));
    if (!trimmed.startsWith("'") || !trimmed.endsWith("'")) {
        throw new RuntimeException(msg.format("error.invalid.string", data.getValue(), data.getMethod()));
    }/*from ww  w  .ja  v  a 2  s. c  om*/

    String wholeValue = StringUtils.substring(trimmed, 1, trimmed.length() - 1);

    if (String.class.equals(returnClass)) {
        return wholeValue;
    }

    if (null == data.getValue()) {
        return null;
    }

    if (Object.class.equals(returnClass)) {
        returnClass = String.class;
    }

    if (char.class.equals(data.getReturnType()) || Character.class.equals(data.getReturnType())) {
        if (StringUtils.length(wholeValue) == 1) {
            return CharUtils.toChar(wholeValue);
        }
        return CharUtils.toChar(StringUtils.replace(wholeValue, " ", ""));
    }

    if (primitiveBoxing.containsKey(returnClass)) {
        if (StringUtils.isBlank(wholeValue)) {
            return null;
        }
        Method parser = primitiveBoxing.get(returnClass).getMethod(
                "parse" + StringUtils.capitalize(returnClass.getSimpleName()), new Class<?>[] { String.class });
        return parser.invoke(primitiveBoxing.get(returnClass), new Object[] { StringUtils.trim(wholeValue) });
    }

    Method valueOf = null;
    try {
        valueOf = returnClass.getMethod("valueOf", new Class<?>[] { String.class });
    } catch (NoSuchMethodException ignored) {
    }

    if (valueOf == null) {
        try {

            valueOf = returnClass.getMethod("valueOf", new Class<?>[] { Object.class });
        } catch (NoSuchMethodException ignored) {
        }
    }

    if (null != valueOf) {
        if (StringUtils.isEmpty(wholeValue)) {
            return null;
        }
        return valueOf.invoke(data.getReturnType(), new Object[] { StringUtils.trim(wholeValue) });
    }

    Constructor<?> constructor = null;

    try {
        constructor = returnClass.getConstructor(String.class);
        constructor.setAccessible(true);

    } catch (NoSuchMethodException ignored) {
        throw new IllegalStateException(
                msg.format("error.string.constructor", returnClass.getSimpleName(), data.getMethod()));
    }

    try {
        return constructor.newInstance(wholeValue);

    } catch (Exception e) {
        if (e.getCause() != null && e.getCause() instanceof NumberFormatException) {
            return constructor.newInstance(StringUtils.trim(wholeValue));
        }
        throw e;
    }
}

From source file:org.blocks4j.reconf.client.elements.ConfigurationItemElement.java

@Override
public String toString() {
    ToStringBuilder result = new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("method",
            StringUtils.replace(getMethod().toString(), "public abstract ", ""));
    addToString(result, "product", getProduct());
    addToString(result, "component", getComponent());
    result.append("value", getValue());
    return result.toString();
}

From source file:org.blocks4j.reconf.client.factory.ConfigurationRepositoryElementFactory.java

private void validate(ConfigurationRepositoryElement arg) {
    if (arg == null) {
        throw new ReConfInitializationError(msg.get("error.internal"));
    }//from ww w.ja v a 2 s .  c om

    Map<String, String> violations = ConfigurationRepositoryElementValidator.validate(arg);
    if (MapUtils.isEmpty(violations)) {
        return;
    }

    List<String> errors = new ArrayList<String>();
    int i = 1;
    for (Entry<String, String> violation : violations.entrySet()) {
        errors.add(i++ + " - " + violation.getValue() + " @ "
                + StringUtils.replace(arg.getInterfaceClass().toString(), "interface ", "") + "."
                + violation.getKey());
    }

    if (configuration.isDebug()) {
        LoggerHolder.getLog().error(msg.format("error.factory", LineSeparator.value(),
                StringUtils.join(errors, LineSeparator.value())) + LineSeparator.value());
    } else {
        throw new ReConfInitializationError(msg.format("error.factory", LineSeparator.value(),
                StringUtils.join(errors, LineSeparator.value())) + LineSeparator.value());
    }
}

From source file:org.castor.core.util.StringUtil.java

/**
 * Replaces all occurences of a pattern within a String.
 * /*from   ww  w .j ava  2 s  .c o  m*/
 * @param source The source string.
 * @param toReplace The character to replace.
 * @param replacement The replacement.
 * @return The new String with characters replaced.
 */
public static String replaceAll(final String source, final String toReplace, final String replacement) {
    // if (source == null) {
    // return null;
    // }
    // String returnValue = source;
    // int idx = source.lastIndexOf(toReplace);
    // if (idx != -1) {
    // StringBuffer ret = new StringBuffer(source);
    // ret.replace(idx, idx + toReplace.length(), replacement);
    // while ((idx = source.lastIndexOf(toReplace, idx - 1)) != -1) {
    // ret.replace(idx, idx + toReplace.length(), replacement);
    // }
    // returnValue = ret.toString();
    // }
    // return returnValue;
    return StringUtils.replace(source, toReplace, replacement);
}

From source file:org.craftercms.engine.navigation.impl.DefaultItemConverter.java

protected String getNavigationLabel(SiteItem siteItem) {
    String navLabel = siteItem.getItem().queryDescriptorValue(navLabelXPath);
    if (StringUtils.isEmpty(navLabel)) {
        navLabel = siteItem.getItem().queryDescriptorValue(internalNameXPath);
        if (StringUtils.isEmpty(navLabel)) {
            navLabel = FilenameUtils.removeExtension(siteItem.getStoreName());
            navLabel = StringUtils.replace(navLabel, "-", " ");
            navLabel = StringUtils.capitalize(navLabel);
        }// w  ww.  j a va2 s . c  o  m
    }

    return navLabel;
}

From source file:org.cyk.ui.web.api.WebNavigationManager.java

public String url(String id, Object[] parameters, Boolean actionOutcome, Boolean partial, Boolean pretty) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    StringBuilder url = new StringBuilder();

    NavigationCase navigationCase = ((ConfigurableNavigationHandler) facesContext.getApplication()
            .getNavigationHandler()).getNavigationCase(facesContext, null, id);
    //System.out.println(id+" / "+navigationCase);
    if (navigationCase == null) {
        log.severe("No Navigation Case found for " + id);
        return url(OUTCOME_NOT_FOUND, new Object[] { "oc", id }, Boolean.FALSE, Boolean.FALSE);
    }// w  w  w  .j  av a 2 s.  c  om
    String s = navigationCase.getToViewId(facesContext);
    if (Boolean.TRUE.equals(actionOutcome))
        url.append(s);
    else
        url.append(StringUtils.replace(s, FILE_STATIC_EXTENSION, FILE_PROCESSING_EXTENSION));

    if (Boolean.TRUE.equals(actionOutcome))
        navigationHelper.addParameter(url, QUERY_PARAMETER_FACES_REDIRECT_NAME, navigationCase.isRedirect());
    if (parameters != null && parameters.length > 0) {
        for (int i = 0; i < parameters.length - 1; i = i + 2)
            if (parameters[i + 1] == null)
                ;
            else
                navigationHelper.addParameter(url, /*(String)*/ parameters[i], parameters[i + 1]);
    }
    if (Boolean.TRUE.equals(partial))
        ;
    else {
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
                .getRequest();

        //FacesContext.getCurrentInstance().getExternalContext().encodeResourceURL() will trigger rewriting  

        //int countContextPath = StringUtils.countMatches(url, request.getContextPath());
        url = new StringBuilder(StringUtils.removeStartIgnoreCase(//TODO might not work always
                FacesContext.getCurrentInstance().getExternalContext().encodeResourceURL(url.toString()),
                request.getContextPath()));
        //if(StringUtils.countMatches(url, request.getContextPath())>countContextPath)

        url.insert(0, request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath());
    }

    return url.toString();
}

From source file:org.cyk.ui.web.api.WebNavigationManager.java

public String getPath(String outcome, Boolean actionOutcome, Boolean partial) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    StringBuilder path = new StringBuilder();
    NavigationCase navigationCase = ((ConfigurableNavigationHandler) facesContext.getApplication()
            .getNavigationHandler()).getNavigationCase(facesContext, null, outcome);
    if (navigationCase == null) {
        log.severe("No Navigation Case found for " + outcome);
        return url(OUTCOME_NOT_FOUND, new Object[] { "oc", outcome }, Boolean.FALSE, Boolean.FALSE);
    }//  w w  w.  j  av a  2 s . c o m
    String s = navigationCase.getToViewId(facesContext);
    if (Boolean.TRUE.equals(actionOutcome))
        path.append(s);
    else
        path.append(StringUtils.replace(s, FILE_STATIC_EXTENSION, FILE_PROCESSING_EXTENSION));

    if (Boolean.TRUE.equals(partial))
        ;
    else {
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
                .getRequest();
        path = new StringBuilder(StringUtils.removeStartIgnoreCase(//TODO might not work always
                FacesContext.getCurrentInstance().getExternalContext().encodeResourceURL(path.toString()),
                request.getContextPath()));
        path.insert(0, request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath());
    }

    return path.toString();
}

From source file:org.dashbuilder.dataprovider.backend.sql.JDBCUtils.java

public static String changeCaseExcludeQuotes(String s, boolean upper) {

    List<String> keepList = new ArrayList<String>();
    for (int i = 0; i < QUOTES.length; i++) {
        String quote = QUOTES[i];
        String[] words = StringUtils.substringsBetween(s, quote, quote);
        if (words != null) {
            keepList.addAll(Arrays.asList(words));
        }// w w  w . j  a v  a  2 s .c  o  m
    }

    String tmpStr = upper ? s.toUpperCase() : s.toLowerCase();
    for (String word : keepList) {
        String tmpWord = upper ? word.toUpperCase() : word.toLowerCase();
        tmpStr = StringUtils.replace(tmpStr, tmpWord, word);
    }
    return tmpStr;
}