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.blazebit.security.impl.interceptor.ChangeInterceptor.java

/**
 * //from w  ww  . j av  a  2s . com
 */
@Override
public void onCollectionUpdate(Object collection, Serializable key) throws CallbackException {
    if (!EntityFeatures.isInterceptorActive()) {
        super.onCollectionUpdate(collection, key);
        return;
    }
    if (collection instanceof PersistentCollection) {
        PersistentCollection newValuesCollection = (PersistentCollection) collection;
        Object entity = newValuesCollection.getOwner();
        if (AnnotationUtils.findAnnotation(entity.getClass(), EntityResourceType.class) == null) {
            super.onCollectionUpdate(collection, key);
            return;
        }
        // copy new values and old values
        @SuppressWarnings({ "unchecked", "rawtypes" })
        Collection<?> newValues = new HashSet((Collection<?>) newValuesCollection.getValue());
        @SuppressWarnings({ "unchecked", "rawtypes" })
        Set<?> oldValues = new HashSet(((Map<?, ?>) newValuesCollection.getStoredSnapshot()).keySet());

        String fieldName = StringUtils.replace(newValuesCollection.getRole(), entity.getClass().getName() + ".",
                "");
        UserContext userContext = BeanProvider.getContextualReference(UserContext.class);
        ActionFactory actionFactory = BeanProvider.getContextualReference(ActionFactory.class);
        EntityResourceFactory resourceFactory = BeanProvider
                .getContextualReference(EntityResourceFactory.class);
        PermissionService permissionService = BeanProvider.getContextualReference(PermissionService.class);

        // find all objects that were added
        boolean isGrantedToAdd = true;
        boolean isGrantedToRemove = true;

        @SuppressWarnings({ "unchecked", "rawtypes" })
        Set<?> retained = new HashSet(oldValues);
        retained.retainAll(newValues);

        oldValues.removeAll(retained);
        // if there is a difference between oldValues and newValues
        if (!oldValues.isEmpty()) {
            // if something remained
            isGrantedToRemove = permissionService.isGranted(actionFactory.createAction(Action.REMOVE),
                    resourceFactory.createResource(entity, fieldName));
        }
        newValues.removeAll(retained);
        if (!newValues.isEmpty()) {
            isGrantedToAdd = permissionService.isGranted(actionFactory.createAction(Action.ADD),
                    resourceFactory.createResource(entity, fieldName));
        }

        if (!isGrantedToAdd) {
            throw new PermissionActionException("Element cannot be added to entity " + entity + "'s collection "
                    + fieldName + " by " + userContext.getUser());
        } else {
            if (!isGrantedToRemove) {
                throw new PermissionActionException("Element cannot be removed from entity " + entity
                        + "'s collection " + fieldName + " by " + userContext.getUser());
            } else {
                super.onCollectionUpdate(collection, key);
                return;
            }
        }
    } else {
        // not a persistent collection?
    }
}

From source file:com.mirth.connect.server.migration.Migrator.java

protected List<String> readStatements(String scriptResourceName, Map<String, Object> replacements)
        throws IOException {
    List<String> script = new ArrayList<String>();
    Scanner scanner = null;//from w  w w  .  ja  v a2 s.  c o m

    if (scriptResourceName.charAt(0) != '/' && defaultScriptPath != null) {
        scriptResourceName = defaultScriptPath + "/" + scriptResourceName;
    }

    try {
        scanner = new Scanner(IOUtils.toString(ResourceUtil.getResourceStream(getClass(), scriptResourceName)));

        while (scanner.hasNextLine()) {
            StringBuilder stringBuilder = new StringBuilder();
            boolean blankLine = false;

            while (scanner.hasNextLine() && !blankLine) {
                String temp = scanner.nextLine();

                if (temp.trim().length() > 0) {
                    stringBuilder.append(temp + " ");
                } else {
                    blankLine = true;
                }
            }

            // Trim ending semicolons so Oracle doesn't throw
            // "java.sql.SQLException: ORA-00911: invalid character"
            String statementString = StringUtils.removeEnd(stringBuilder.toString().trim(), ";");

            if (statementString.length() > 0) {
                if (replacements != null && !replacements.isEmpty()) {
                    for (String key : replacements.keySet()) {
                        statementString = StringUtils.replace(statementString, "${" + key + "}",
                                replacements.get(key).toString());
                    }
                }

                script.add(statementString);
            }
        }

        return script;
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
}

From source file:io.wcm.maven.plugins.i18n.SlingI18nMap.java

/**
 * Creates a valid node name. Replaces all chars not in a-z, A-Z and 0-9 or '_', '.' with '-'.
 * @param value String to be labelized.//from  w  ww  .  ja  v a  2s . c  o  m
 * @return The labelized string.
 */
private static String validName(String value) {

    // replace some special chars first
    String text = value;
    text = StringUtils.replace(text, "", "ae");
    text = StringUtils.replace(text, "", "oe");
    text = StringUtils.replace(text, "", "ue");
    text = StringUtils.replace(text, "", "ss");

    // replace all invalid chars
    StringBuilder sb = new StringBuilder(text);
    for (int i = 0; i < sb.length(); i++) {
        char ch = sb.charAt(i);
        if (!((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || (ch == '_')
                || (ch == '.'))) {
            ch = '-';
            sb.setCharAt(i, ch);
        }
    }
    return sb.toString();
}

From source file:io.wcm.maven.plugins.contentpackage.AbstractContentPackageMojo.java

protected final String getCrxPackageManagerUrl() {
    String serviceUrl = this.serviceURL;
    // convert "legacy interface URL" with service.jsp to new CRX interface (since CRX 2.1)
    serviceUrl = StringUtils.replace(serviceUrl, "/crx/packmgr/service.jsp", "/crx/packmgr/service");
    // remove /.json suffix if present
    serviceUrl = StringUtils.removeEnd(serviceUrl, "/.json");
    return serviceUrl;
}

From source file:com.enhype.photo.FlickrService.java

public void getOwnerInfoFlickr(List<String> userIds) {

    Map<String, String> userNames = new HashMap<String, String>();

    for (String user_id : userIds) {
        WebResource resource = Client.create().resource(RunConfig.FLICKR_SERVICE_ENDPOINT)
                .path("services/rest/").queryParam("method", peopleInfoMethod).queryParam("api_key", key)
                .queryParam("format", "json").queryParam("nojsoncallback", "1").queryParam("user_id", user_id);

        ClientResponse response = null;/*  ww  w  .  j  a v  a  2 s  .  com*/

        try {

            response = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);

        } catch (Exception e) {
            logger.error("Unable to connection to entity linking service", e);
        }

        if (response.getStatus() >= 300) {
            logger.error(
                    String.format("GET [%s], status code [%d]", resource.toString(), response.getStatus()));
            throw new UniformInterfaceException("Status code indicates request not expected", response);
        }

        String responseStr = response.getEntity(String.class);

        logger.info(responseStr);

        if (response != null)
            response.close();

        JSONObject person = (JSONObject) JSONObject.fromObject(responseStr).get("person");

        String username = "", realname = "";

        if (person.containsKey("username"))
            username = ((JSONObject) person.get("username")).getString("_content");
        if (person.containsKey("realname"))
            realname = ((JSONObject) person.get("realname")).getString("_content");

        if (realname.length() > 0)
            userNames.put(user_id, realname);
        else
            userNames.put(user_id, username);

    }

    for (String user_id : userNames.keySet()) {

        String updateDBStr = "update pictures set photoby='"
                + StringUtils.replace(userNames.get(user_id), "'", "''") + "' where img_owner='" + user_id
                + "' ; ";

        db.execUpdate(updateDBStr);

    }

}

From source file:com.sonicle.webtop.core.versioning.SqlUpgradeScript.java

private void readFile(InputStreamReader readable, boolean flatNewLines) throws IOException {
    this.statements = new ArrayList<>();
    StringBuilder sb = null, sbsql = null;
    String lines[] = null;/*w w  w.  j a va  2 s. c om*/

    Scanner s = new Scanner(readable);
    s.useDelimiter("(;( )?(\r)?\n)");
    //s.useDelimiter("(;( )?(\r)?\n)|(--\n)");
    while (s.hasNext()) {
        String block = s.next();
        block = StringUtils.replace(block, "\r", "");
        if (!StringUtils.isEmpty(block)) {
            // Remove remaining ; at the end of the block (only if this block is the last one)
            if (!s.hasNext() && StringUtils.endsWith(block, ";"))
                block = StringUtils.left(block, block.length() - 1);

            sb = new StringBuilder();
            sbsql = new StringBuilder();
            lines = StringUtils.split(block, "\n");
            for (String line : lines) {
                if (AnnotationLine.matches(line)) {
                    if (DataSourceAnnotationLine.matches(line)) {
                        statements.add(new DataSourceAnnotationLine(line));
                    } else if (IgnoreErrorsAnnotationLine.matches(line)) {
                        statements.add(new IgnoreErrorsAnnotationLine(line));
                    } else if (RequireAdminAnnotationLine.matches(line)) {
                        statements.add(new RequireAdminAnnotationLine(line));
                    } else {
                        throw new IOException("Bad line: " + line);
                    }
                } else if (CommentLine.matches(line)) {
                    sb.append(line);
                    sb.append("\n");
                } else {
                    sbsql.append(StringUtils.trim(line));
                    sbsql.append(" ");
                    if (!flatNewLines)
                        sbsql.append("\n");
                }
            }
            if (sb.length() > 0)
                statements.add(new CommentLine(StringUtils.removeEnd(sb.toString(), "\n")));
            if (sbsql.length() > 0)
                statements.add(new SqlLine(StringUtils.removeEnd(sbsql.toString(), "\n")));
        }
    }
}

From source file:de.ks.file.FileStore.java

public String replaceFileStoreDir(String description) {
    String replacement = "file://" + getFileStoreDir();
    if (!replacement.endsWith(File.separator)) {
        replacement = replacement + File.separator;
    }//from  w ww .  j a va2  s .  c  o m
    String newDescription = StringUtils.replace(description, FileReference.FILESTORE_VAR, replacement);
    return newDescription;
}

From source file:com.mingo.query.util.QueryUtils.java

/**
 * Replace parameters in query.//from w  w w .  j a va 2 s.c o  m
 *
 * @param query      query
 * @param parameters parameters
 * @return prepared query
 */
public static String replaceQueryParameters(String query, Map<String, Object> parameters) {
    if (StringUtils.isNotBlank(query) && MapUtils.isNotEmpty(parameters)) {
        for (Map.Entry<String, Object> parameter : parameters.entrySet()) {
            if (StringUtils.isNotEmpty(parameter.getKey())) {
                if (isParameterEmpty(parameter.getValue())) {
                    query = StringUtils.replace(query, PARAMETER_PREFIX + parameter.getKey(),
                            StringUtils.EMPTY);
                } else {
                    String replacement = createReplacement(parameter.getKey(), parameter.getValue());
                    query = StringUtils.replace(query, replacement, getParameterAsString(parameter.getValue()));
                }
            }
        }
    }
    return removeParameters(query);
}

From source file:com.snowstore.mercury.core.metric.SystemPublicMetrics.java

/**
 * Turn GC names like 'PS Scavenge' or 'PS MarkSweep' into something that is
 * more metrics friendly.//from w  w  w . j av a 2  s.  com
 */
private String beautifyGcName(String name) {
    return StringUtils.replace(name, " ", "_").toLowerCase();
}

From source file:de.micromata.genome.gwiki.page.search.expr.SearchExpressionContentSearcher.java

public String reworkRawTextForPreview(String str) {
    str = StringUtils.replace(str, "\n", "<br/>\n");
    return str;
}