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:nl.sidn.pcap.parquet.AbstractParquetPacketWriter.java

public void open() {
    String server = Settings.getInstance().getServer().getFullname();
    String path = repoLocation + System.getProperty("file.separator") + server
            + System.getProperty("file.separator") + repoName;
    //remove any dots from the path, kitesdk does not support this
    //https://issues.cloudera.org/browse/KITE-673
    path = StringUtils.replace(path, ".", "_");

    LOGGER.info("Create new Parquet write with path: " + path);

    /* before opening, make sure there is no (old) .metadata folder in the output dir */
    String metadataLocation = path + System.getProperty("file.separator") + ".metadata";
    try {//from  w ww  . ja  v a  2s. co  m
        FileUtils.deleteDirectory(new File(metadataLocation));
    } catch (IOException e1) {
        throw new RuntimeException("Could not remove old .metadata directory -> " + metadataLocation);
    }

    /* create a partition for year, month and day.
     * The parquetwriter will create a directory structure with the distinct partition
     * values.
     */
    PartitionStrategy partitionStrategy = createPartitionStrategy();
    //creat a descriptor with the parquet output format and the correct partition strategy
    try {
        descriptor = new DatasetDescriptor.Builder().schemaUri("resource:" + schema).format(Formats.PARQUET)
                .partitionStrategy(partitionStrategy).build();
    } catch (Exception e) {
        throw new RuntimeException("Error while creating data descriptor", e);
    }
    //create a file dataset for the above descriptor
    Dataset<GenericRecord> dataset = Datasets.create("dataset:file:" + path, descriptor, GenericRecord.class);

    writer = dataset.newWriter();
}

From source file:nl.sidn.stats.MetricManager.java

private String createMetricName(String metric) {
    //replace dot in the server name with underscore otherwise graphite will assume nesting
    String cleanServer = StringUtils
            .trimToEmpty(StringUtils.replace(Settings.getInstance().getServer().getFullname(), ".", "_"));
    return graphitePrefix + "." + cleanServer + metric;
}

From source file:nl.strohalm.cyclos.utils.database.DatabaseCustomFieldHandler.java

/**
 * Appends the custom field values on a query. Should be invoked when
 * building the where part of the query/*  w  ww.  ja va 2 s. co  m*/
 *
 * @param hql The current HQL buffer
 * @param values The custom field values used to filter
 */
public void appendConditions(final StringBuilder hql, final Map<String, Object> namedParameters,
        final Collection<? extends CustomFieldValue> values) {
    if (values == null || values.isEmpty()) {
        return;
    }
    for (final CustomFieldValue fieldValue : values) {
        CustomField field = fieldValue.getField();
        if (field == null) {
            continue;
        }
        field = fetchDao.fetch(field);
        String value = fieldValue.getValue();
        // Remove any manually entered '%'
        value = StringUtils.trimToNull(StringUtils.replace(value, "%", ""));
        if (value == null) {
            continue;
        }
        final String alias = alias(field);
        final String fieldParam = "field_" + alias;
        final String valueParam = "value_" + alias;

        hql.append(" and ").append(alias).append(".field = :").append(fieldParam);
        namedParameters.put(fieldParam, field);

        if (LoggedUser.hasUser() && !LoggedUser.isAdministrator()) {
            if (field.getNature() == CustomField.Nature.MEMBER) {
                // Exclude hidden fields
                hql.append(" and ").append(alias).append(".hidden <> true");
            }
        }
        // Check the field type
        switch (field.getType()) {
        case STRING:
            if (StringUtils.isNotEmpty(field.getPattern())) {
                // Remove the mask and consider the value as matching exactly
                value = StringHelper.removeMask(field.getPattern(), value, false);
                hql.append(" and ").append(alias).append(".stringValue like :").append(valueParam);
                namedParameters.put(valueParam, value);
            } else {
                // Use a like expression
                hql.append(" and ").append(alias).append(".stringValue like :").append(valueParam);
                namedParameters.put(valueParam, StringUtils.trimToEmpty(value) + "%");
            }
            break;
        case BOOLEAN:
            if (Boolean.parseBoolean(value)) {
                hql.append(" and ").append(alias).append(".stringValue = :" + valueParam);
            } else {
                hql.append(" and ").append(alias).append(".stringValue <> :" + valueParam);
            }
            namedParameters.put(valueParam, "true");
            break;
        case ENUMERATED:
            boolean byName = true;
            if (StringUtils.containsOnly(value, "0123456789,")) {
                // Try by id
                try {
                    final Collection<CustomFieldPossibleValue> possibleValues = new ArrayList<CustomFieldPossibleValue>();
                    final String[] possibleValueIds = StringUtils.split(value, ',');
                    for (final String idAsString : possibleValueIds) {
                        final CustomFieldPossibleValue possibleValue = customFieldPossibleValueDao
                                .load(Long.valueOf(idAsString));
                        if (!possibleValue.getField().equals(field)) {
                            throw new Exception();
                        }
                        possibleValues.add(possibleValue);
                    }
                    byName = false;
                    hql.append(" and ").append(alias).append(".possibleValue in (:").append(valueParam)
                            .append(')');
                    namedParameters.put(valueParam, possibleValues);
                } catch (final Exception e) {
                    // Possible value not found by id - next try by name
                }
            }
            if (byName) {
                hql.append(" and ").append(alias).append(".possibleValue.value = :").append(valueParam);
                namedParameters.put(valueParam, value);
            }
            break;
        case MEMBER:
            Long memberId = null;
            if (fieldValue.getMemberValue() != null) {
                memberId = fieldValue.getMemberValue().getId();
            } else {
                memberId = IdConverter.instance().valueOf(value);
            }
            if (memberId != null) {
                hql.append(" and ").append(alias).append(".memberValue.id = :").append(valueParam);
                namedParameters.put(valueParam, memberId);
            }
            break;
        default:
            hql.append(" and ").append(alias).append(".stringValue = :").append(valueParam);
            namedParameters.put(valueParam, value);
            break;
        }
    }
}

From source file:nl.strohalm.cyclos.utils.database.DatabaseCustomFieldHandler.java

/**
 * Appends the inner joins for each custom field. Should be invoked when
 * building the from part of the query./*from  w  w  w .j  ava  2  s.c  o  m*/
 *
 * @param hql The current HQL buffer
 * @param fieldValuesPath The path on the query for the custom fields value
 * collection
 * @param values The custom field values used to filter
 */
public void appendJoins(final StringBuilder hql, final String fieldValuesPath,
        final Collection<? extends CustomFieldValue> values) {
    if (values == null || values.isEmpty()) {
        return;
    }
    for (final CustomFieldValue fieldValue : values) {
        CustomField field = fieldValue.getField();
        if (field == null) {
            continue;
        }
        String value = fieldValue.getValue();
        // Remove any manually entered '%'
        value = StringUtils.trimToNull(StringUtils.replace(value, "%", ""));
        if (value == null) {
            continue;
        }
        field = fetchDao.fetch(field);
        hql.append(" inner join ").append(fieldValuesPath).append(' ').append(alias(field));
    }
}

From source file:nl.strohalm.cyclos.utils.database.DatabaseHelper.java

private static void doAddLike(final StringBuilder hql, final Map<String, Object> namedParameters,
        final String path, String value, final boolean rightOnly) {
    value = StringUtils.trimToNull(value);
    if (value == null) {
        return;/*  w w w.j  a  v a 2  s .c o m*/
    }
    // Remove any manually entered '%'
    value = StringUtils.trimToNull(StringUtils.replace(value, "%", ""));
    if (value == null) {
        return;
    }
    // Assuming the default database collation is case insensitive, we don't need to perform case transformations
    if (rightOnly) {
        value += "%";
    } else {
        value = "%" + value + "%";
    }
    addParameterToQueryOperator(hql, namedParameters, path, "like", value);
}

From source file:nl.vpro.jcr.criteria.query.criterion.SimpleExpression.java

@Override
public String toXPathString(Criteria criteria) throws JCRQueryException {
    StringBuilder fragment = new StringBuilder();
    fragment.append(" (");

    if (value instanceof String) {
        fragment.append(propertyName).append(getOp());
        // Generally, if you enclose values in single quotes, you just need to replace any literal single quote
        // character with '' (two consecutive single quote characters).
        String escValue = StringUtils.replace((String) value, "'", "''");
        fragment.append("'").append(escValue).append("') ");
    } else if (value instanceof Number) {
        fragment.append(propertyName).append(getOp());
        fragment.append(value).append(") ");
    } else if (value instanceof Character) {
        fragment.append(propertyName).append(getOp());
        fragment.append("'").append(Character.toString((Character) value)).append("') ");
    } else if (value instanceof Boolean) {
        if ((Boolean) value) {
            fragment.append(propertyName).append(getOp());
            fragment.append(value).append(") ");
        } else {//from   w  ww.ja v  a2s  .  c om
            // false should also match a missing boolean property
            fragment.append("(");
            fragment.append(propertyName).append(getOp());

            fragment.append(value).append(") or not(").append(propertyName).append(" ))");
        }
    } else if (value instanceof Calendar) {
        fragment.append(propertyName).append(getOp());
        Calendar cal = (Calendar) value;

        fragment.append(XS_DATETIME_FUNCTION + "('").append(XPathTextUtils.toXsdDate(cal)).append("')) ");
    } else if (value != null) {
        fragment.append(propertyName).append(getOp());
        // just use the toString() of the given object
        fragment.append("'").append(value).append("') ");
    }
    log.debug("xpathString is {} ", fragment);
    return fragment.toString();
}

From source file:oi.thekraken.grok.api.Grok.java

/**
 * Compile the {@code Grok} pattern to named regex pattern.
 *
 * @param pattern : Grok pattern (ex: %{IP})
 * @throws GrokException//  w w  w  .  j a va  2  s  . co  m
 */
public void compile(String pattern) throws GrokException {

    if (StringUtils.isBlank(pattern)) {
        throw new GrokException("{pattern} should not be empty or null");
    }

    namedRegex = pattern;
    originalGrokPattern = pattern;
    int index = 0;
    /** flag for infinite recurtion */
    int iterationLeft = 1000;
    Boolean continueIteration = true;

    // Replace %{foo} with the regex (mostly groupname regex)
    // and then compile the regex
    while (continueIteration) {
        continueIteration = false;
        if (iterationLeft <= 0) {
            throw new GrokException("Deep recursion pattern compilation of " + originalGrokPattern);
        }
        iterationLeft--;

        Matcher m = GrokUtils.GROK_PATTERN.matcher(namedRegex);
        // Match %{Foo:bar} -> pattern name and subname
        // Match %{Foo=regex} -> add new regex definition
        if (m.find()) {
            continueIteration = true;
            Map<String, String> group = m.namedGroups();
            if (group.get("definition") != null) {
                try {
                    addPattern(group.get("pattern"), group.get("definition"));
                    group.put("name", group.get("name") + "=" + group.get("definition"));
                } catch (GrokException e) {
                    // Log the exeception
                }
            }
            namedRegexCollection.put("name" + index,
                    (group.get("subname") != null ? group.get("subname") : group.get("name")));
            namedRegex = StringUtils.replace(namedRegex, "%{" + group.get("name") + "}",
                    "(?<name" + index + ">" + grokPatternDefinition.get(group.get("pattern")) + ")");
            // System.out.println(_expanded_pattern);
            index++;
        }
    }

    if (namedRegex.isEmpty()) {
        throw new GrokException("Pattern not fount");
    }
    // Compile the regex
    compiledNamedRegex = Pattern.compile(namedRegex);
}

From source file:org.alfresco.po.share.admin.VisibilityDropDown.java

/**
 * Select a new visibility drop down value.
 * /* w  w w  .  j a v  a 2  s. co m*/
 * @param visibility the visibility
 */
public void selectValue(SiteVisibility visibility) {
    // Click the control to open the menu
    control.click();

    // Compose the selector for the drop down menu
    String menuSelector = StringUtils.replace(MENU_ELEMENT_SELECTOR_TEMPLATE, "?", this.menuId);

    // Find the menu
    WebElement menu = this.driver.findElement(By.cssSelector(menuSelector));

    // If the menu is not null and is displayed and is enabled
    if (PageUtils.usableElement(menu)) {

        // Within the menu element find the MENU_ROWS
        List<WebElement> menuRows = menu.findElements(MENU_ROWS);

        // Iterate over the menuRows and click the item that matches the required visibility
        for (WebElement menuRow : menuRows) {
            if (visibility.getDisplayValue()
                    .equals(StringUtils.trim(menuRow.findElement(MENU_LABEL).getText()))) {
                menuRow.click();
                this.value = visibility;
                break;
            }
        }
    }
}

From source file:org.alfresco.po.share.DocListPaginator.java

/**
 * Go to the first page of results.//  w ww  . j  a  va2 s  .  c o  m
 * 
 * @return the html page
 */
public HtmlPage gotoFirstResultsPage() {
    // If we're on page 1 return
    if (getPageNumber() == 1) {
        return getCurrentPage();
    } else {
        try {
            // Click the page selector to open the drop down menu
            pageSelector.click();

            // Compose the selector for the drop down menu
            String menuId = this.pageSelector.getAttribute("id") + MENU_ELEMENT_SUFFIX;
            String menuSelector = StringUtils.replace(MENU_ELEMENT_SELECTOR_TEMPLATE, "?", menuId);

            // Find the menu
            WebElement menu = this.driver.findElement(By.cssSelector(menuSelector));

            // If the menu is not null and is displayed and is enabled
            if (PageUtils.usableElement(menu)) {
                // Within the menu select the first page
                WebElement firstPage = menu.findElement(FIRST_MENU_ROW);

                // First page found - click it
                if (PageUtils.usableElement(firstPage)) {
                    firstPage.click();
                }
            }
        } catch (NoSuchElementException nse) {
        } catch (TimeoutException te) {
        }

    }

    // Return the resolved page
    return getCurrentPage();
}

From source file:org.alfresco.po.share.SelectList.java

/**
 * Select a new select list down value.//from  w  w w  .  j a  va 2  s  .  co m
 * 
 * @param value the value
 * @param selectExactMatch true if list item with exact matching text is required
 * @return true if the specified value is selected, else false
 */
public boolean selectValue(String value, boolean selectExactMatch) {
    // Click the control to open the menu
    control.click();

    // Compose the selector for the drop down menu
    String menuSelector = StringUtils.replace(MENU_ELEMENT_SELECTOR_TEMPLATE, "?", this.menuId);

    // Find the menu
    WebElement menu = this.driver.findElement(By.cssSelector(menuSelector));

    // If the menu is not null and is displayed and is enabled
    if (PageUtils.usableElement(menu)) {

        // Within the menu element find the MENU_ROWS
        List<WebElement> menuRows = menu.findElements(MENU_ROWS);

        // Iterate over the menuRows and click the item that matches the required visibility
        for (WebElement menuRow : menuRows) {
            String listItem = StringUtils.trim(menuRow.findElement(MENU_LABEL).getText());
            LOGGER.debug("List Item Value: " + listItem);
            if (value.equals(listItem)) {
                menuRow.click();
                this.value = value;
                return true;
            }

            if (!selectExactMatch) {
                if (listItem != null) {
                    if (listItem.startsWith(value)) {
                        menuRow.click();
                        this.value = value;
                        return true;
                    }
                }
            }
        }
    }

    return false;
}