Example usage for org.apache.commons.lang.text StrSubstitutor replace

List of usage examples for org.apache.commons.lang.text StrSubstitutor replace

Introduction

In this page you can find the example usage for org.apache.commons.lang.text StrSubstitutor replace.

Prototype

public String replace(Object source) 

Source Link

Document

Replaces all the occurrences of variables in the given source object with their matching values from the resolver.

Usage

From source file:com.thinkbiganalytics.feedmgr.nifi.PropertyExpressionResolver.java

/**
 * Replace any property in the str  ${var} with the respective value in the map of vars
 *///from  ww  w .j  a  v a2s  .c om
public String resolveVariables(String str, Map<String, String> vars) {
    StrSubstitutor ss = new StrSubstitutor(vars);
    return ss.replace(str);
}

From source file:com.thinkbiganalytics.feedmgr.nifi.PropertyExpressionResolver.java

public String replaceAll(String str, String replacement) {
    if (str != null) {
        StrLookup lookup = new StrLookup() {
            @Override//from   www .ja  va  2s  .c om
            public String lookup(String key) {
                return replacement;
            }
        };
        StrSubstitutor ss = new StrSubstitutor(lookup);
        return ss.replace(str);
    }
    return null;
}

From source file:com.appdynamics.monitors.azure.statsCollector.AzureServiceBusStatsCollector.java

private Map<String, String> getStatsFromAzure(Azure azure, String namespaceName, Map<String, String> valueMap,
        String resourceName, String resourceType) throws IOException {
    StrSubstitutor strSubstitutor = new StrSubstitutor(valueMap);
    String statsUrlString = strSubstitutor.replace(STAT_URL);
    URL statsUrl = new URL(statsUrlString);

    InputStream is = processGetRequest(statsUrl, azure.getKeyStoreLocation(), azure.getKeyStorePassword());

    XStream xstream = new XStream();
    xstream.ignoreUnknownElements();//  w  w w.ja  va  2 s.co m
    xstream.processAnnotations(MetricValueSetCollection.class);
    xstream.processAnnotations(MetricValueSet.class);
    xstream.processAnnotations(MetricValue.class);
    MetricValueSetCollection metricValueSetCollection = (MetricValueSetCollection) xstream.fromXML(is);

    return extractMetrics(metricValueSetCollection, namespaceName, resourceType, resourceName);
}

From source file:com.clank.launcher.launch.Runner.java

/**
 * Add arguments for the application./*from  w w w.j a  v  a2 s . co  m*/
 *
 * @throws JsonProcessingException on error
 */
private void addJarArgs() throws JsonProcessingException {
    List<String> args = builder.getArgs();

    String[] rawArgs = versionManifest.getMinecraftArguments().split(" +");
    StrSubstitutor substitutor = new StrSubstitutor(getCommandSubstitutions());
    for (String arg : rawArgs) {
        args.add(substitutor.replace(arg));
    }
}

From source file:com.appdynamics.monitors.azure.statsCollector.AzureServiceBusStatsCollector.java

private Set<String> getResourceNames(String namespaceName, Configuration config, String resourceType)
        throws MalformedURLException {
    Map<String, String> valueMap = new HashMap<String, String>();
    Azure azure = config.getAzure();//w w  w.ja  v  a 2 s  .c o m
    valueMap.put("SubscriptionId", azure.getSubscriptionId());
    valueMap.put("NameSpace", namespaceName);
    valueMap.put("ResourceType", resourceType);
    StrSubstitutor strSubstitutor = new StrSubstitutor(valueMap);
    String resourceNamesUrlString = strSubstitutor.replace(RESOURCE_NAMES_URL);
    URL resourceNamesUrl = new URL(resourceNamesUrlString);
    InputStream inputStream = processGetRequest(resourceNamesUrl, azure.getKeyStoreLocation(),
            azure.getKeyStorePassword());

    XStream xstream = new XStream();
    xstream.ignoreUnknownElements();
    xstream.processAnnotations(Feed.class);
    xstream.processAnnotations(Entry.class);
    Feed feed = (Feed) xstream.fromXML(inputStream);

    Set<String> topicNames = new HashSet<String>();
    List<Entry> entries = feed.getEntries();
    if (entries != null && !entries.isEmpty()) {
        for (Entry entry : entries) {
            topicNames.add(entry.getTitle());
        }
    }
    return topicNames;
}

From source file:com.thinkbiganalytics.feedmgr.nifi.PropertyExpressionResolver.java

/**
 * Resolve the str with values from the supplied {@code properties} This will recursively fill out the str looking back at the properties to get the correct value. NOTE the property values will be
 * overwritten if replacement is found!//from  w  ww . ja v a 2  s .  c o m
 */
public ResolvedVariables resolveVariables(String str, List<NifiProperty> properties) {
    ResolvedVariables variables = new ResolvedVariables(str);

    StrLookup resolver = new StrLookup() {
        @Override
        public String lookup(String key) {
            Optional<NifiProperty> optional = properties.stream().filter(prop -> key.equals(prop.getKey()))
                    .findFirst();
            if (optional.isPresent()) {
                NifiProperty property = optional.get();
                String value = StringUtils.isNotBlank(property.getValue()) ? property.getValue().trim() : "";
                variables.getResolvedVariables().put(property.getKey(), value);
                return value;
            } else {
                return null;
            }
        }
    };

    StrSubstitutor ss = new StrSubstitutor(resolver);
    variables.setResolvedString(ss.replace(str));

    Map<String, String> map = variables.getResolvedVariables();
    Map<String, String> vars = map.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, entry -> ss.replace(entry.getValue())));
    variables.getResolvedVariables().putAll(vars);

    return variables;
}

From source file:com.haulmont.cuba.core.sys.AppProperties.java

private String handleInterpolation(String value) {
    StrSubstitutor substitutor = new StrSubstitutor(new StrLookup() {
        @Override/*from w w w  .  j a v  a2  s . co  m*/
        public String lookup(String key) {
            String property = getSystemOrAppProperty(key);
            return property != null ? property : System.getProperty(key);
        }
    });
    return substitutor.replace(value);
}

From source file:com.facebook.presto.accumulo.tools.PaginationTask.java

/**
 * Queries the temporary table for the rows of data from [min, max)
 *
 * @param min Minimum value of the offset to be retrieved, inclusive
 * @param max Maximum value of the offset to be retrieved, exclusive
 * @return ResultSet of the rows between the given offset
 * @throws SQLException If an error occurs issuing the query
 *///ww  w  . jav a 2 s  .  c o m
public ResultSet getRows(long min, long max) throws SQLException {
    Map<String, Object> queryProps = new HashMap<>();
    queryProps.put(SUBQUERY_COLUMNS, StringUtils.join(columns, ','));
    queryProps.put(TMP_TABLE, tmpTableName);
    queryProps.put(MIN, min);
    queryProps.put(MAX, max);

    StrSubstitutor sub = new StrSubstitutor(queryProps);
    String prevQuery = sub.replace(selectQueryTemplate);

    LOG.info(format("Executing %s", prevQuery));
    return conn.createStatement().executeQuery(prevQuery);
}

From source file:com.thinkbiganalytics.feedmgr.nifi.PropertyExpressionResolver.java

/**
 * Resolves the variables in the value of the specified property.
 *
 * @param property the property/*from   w w  w  .j  a v  a  2 s . com*/
 * @param metadata the feed
 * @return the result of the transformation
 */
private ResolveResult resolveVariables(@Nonnull final NifiProperty property,
        @Nonnull final FeedMetadata metadata) {
    // Filter blank values
    final String value = property.getValue();
    if (StringUtils.isBlank(value)) {
        return new ResolveResult(false, false);
    }

    final boolean[] hasConfig = { false };
    final boolean[] isModified = { false };

    StrLookup resolver = new StrLookup() {
        @Override
        public String lookup(String variable) {
            // Resolve configuration variables
            final String configValue = getConfigurationPropertyValue(property, variable);
            if (configValue != null && property.getValue() != null
                    && !property.getValue().equalsIgnoreCase(configValue)) {
                hasConfig[0] = true;
                isModified[0] = true;
                //if this is the first time we found the config var, set the template value correctly
                if (!property.isContainsConfigurationVariables()) {
                    property.setTemplateValue(property.getValue());
                    property.setContainsConfigurationVariables(true);
                }
                return configValue;

            }

            // Resolve metadata variables
            try {
                final String metadataValue = getMetadataPropertyValue(metadata, variable);
                if (metadataValue != null) {
                    isModified[0] = true;
                    return metadataValue;
                }
            } catch (Exception e) {
                log.error("Unable to resolve variable: " + variable, e);
            }

            return null;
        }
    };
    StrSubstitutor ss = new StrSubstitutor(resolver);
    ss.setEnableSubstitutionInVariables(true);
    //escape
    String val = StringUtils.trim(ss.replace(value));
    //fix
    property.setValue(val);

    return new ResolveResult(hasConfig[0], isModified[0]);
}

From source file:com.facebook.presto.accumulo.tools.PaginationTask.java

public int runQuery() throws SQLException {
    int numErrors = 0;
    numErrors += checkParam(config, "config");
    numErrors += checkParam(host, "host");
    numErrors += checkParam(port, "port");
    numErrors += checkParam(query, "query");
    numErrors += checkParam(columns, "columns");

    if (numErrors > 0) {
        return 1;
    }//from   w  ww  .j  a  v  a  2s  . c  om

    // Clean up any previously run queries in the event the user did not call it explicitly
    cleanup();

    // Open JDBC connection
    String dbUrl = String.format("%s%s:%d/%s", SCHEME, host, port, CATALOG);
    Properties jdbcProps = new Properties();
    jdbcProps.setProperty("user", "root");
    conn = (PrestoConnection) DriverManager.getConnection(dbUrl, jdbcProps);
    conn.setCatalog(CATALOG);
    setSessionProperties(conn);

    // Randomly generate a table name as a local variable
    String tmpTable = "accumulo.pagination.tmp_" + UUID.randomUUID().toString().replaceAll("\\W", "");

    // Build the column mapping based on
    StringBuilder columnMapping = new StringBuilder();
    for (String col : columns) {
        columnMapping.append(col).append(":f:").append(UUID.randomUUID().toString().substring(0, 8))
                .append(',');
    }
    columnMapping.deleteCharAt(columnMapping.length() - 1);

    StringBuilder queryWithGroupBy = new StringBuilder("SELECT 0 AS groupby, ");
    queryWithGroupBy.append(query.substring(query.indexOf("SELECT ") + 7));

    // Substitute the parameters to generate the create table query
    Map<String, String> queryProps = new HashMap<>();
    queryProps.put(TMP_TABLE, tmpTable);
    queryProps.put(TMP_COLUMN_MAPPING, columnMapping.toString());
    queryProps.put(SUBQUERY_COLUMNS, StringUtils.join(columns, ','));
    queryProps.put(USER_QUERY, queryWithGroupBy.toString());

    // Execute the create table query
    StrSubstitutor sub = new StrSubstitutor(queryProps);
    String createTableQuery = sub.replace(createTableTemplate);
    LOG.info(format("Executing query to create temporary table:\n%s", createTableQuery));
    Statement stmt = conn.createStatement();
    stmt.execute(createTableQuery);

    // Execute the query to get the max offset i.e. number of rows from the user query
    stmt = conn.createStatement();
    ResultSet results = stmt.executeQuery("SELECT MAX(offset) FROM " + tmpTable);
    results.next();
    maxOffset = results.getLong(1);
    LOG.info(format("Query has %d results", maxOffset));

    // Set the temp table name now that we have made it through the gauntlet
    this.tmpTableName = tmpTable;
    return 0;
}