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

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

Introduction

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

Prototype

public StrSubstitutor(StrLookup variableResolver) 

Source Link

Document

Creates a new instance and initializes it.

Usage

From source file:com.spotify.helios.testing.TemporaryJobBuilder.java

private void outputMessage(final TemporaryJob job) {
    for (String host : job.hosts()) {
        final StrSubstitutor subst = new StrSubstitutor(
                new ImmutableMap.Builder<String, Object>().put("host", host)
                        .put("name", job.job().getId().getName()).put("version", job.job().getId().getVersion())
                        .put("hash", job.job().getId().getHash()).put("job", job.job().toString())
                        .put("containerId", job.statuses().get(host).getContainerId()).build());
        log.info("{}", subst.replace(jobDeployedMessageFormat));
    }//from w ww  .j  a va 2  s. co  m
}

From source file:com.redhat.lightblue.rest.crud.AbstractCrudResource.java

private String buildSortTemplate(String s1) {
    String ss;/*from   w  w  w  .j a v a  2  s . com*/

    String[] split = s1.split(":");

    Map<String, String> map = new HashMap<>();
    map.put("field", split[0]);
    map.put("order", split[1].charAt(0) == 'd' ? "$desc" : "$asc");

    StrSubstitutor sub = new StrSubstitutor(map);

    ss = sub.replace(SORT_TMPL);
    return ss;
}

From source file:com.haulmont.cuba.testsupport.TestContainer.java

protected void initAppProperties() {
    final Properties properties = new Properties();

    List<String> locations = getAppPropertiesFiles();
    DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
    for (String location : locations) {
        Resource resource = resourceLoader.getResource(location);
        if (resource.exists()) {
            InputStream stream = null;
            try {
                stream = resource.getInputStream();
                properties.load(stream);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                IOUtils.closeQuietly(stream);
            }/*from w  ww .  j a  v  a  2 s  .c om*/
        } else {
            log.warn("Resource " + location + " not found, ignore it");
        }
    }

    StrSubstitutor substitutor = new StrSubstitutor(new StrLookup() {
        @Override
        public String lookup(String key) {
            String subst = properties.getProperty(key);
            return subst != null ? subst : System.getProperty(key);
        }
    });
    for (Object key : properties.keySet()) {
        String value = substitutor.replace(properties.getProperty((String) key));
        appProperties.put((String) key, value);
    }

    File dir;
    dir = new File(appProperties.get("cuba.confDir"));
    dir.mkdirs();
    dir = new File(appProperties.get("cuba.logDir"));
    dir.mkdirs();
    dir = new File(appProperties.get("cuba.tempDir"));
    dir.mkdirs();
    dir = new File(appProperties.get("cuba.dataDir"));
    dir.mkdirs();
}

From source file:com.adobe.acs.commons.wcm.impl.AemEnvironmentIndicatorFilter.java

@Activate
@SuppressWarnings("squid:S1149")
protected final void activate(ComponentContext ctx) {
    Dictionary<?, ?> config = ctx.getProperties();

    color = PropertiesUtil.toString(config.get(PROP_COLOR), "");
    cssOverride = PropertiesUtil.toString(config.get(PROP_CSS_OVERRIDE), "");
    innerHTML = PropertiesUtil.toString(config.get(PROP_INNER_HTML), "");
    innerHTML = new StrSubstitutor(StrLookup.systemPropertiesLookup()).replace(innerHTML);

    // Only write CSS variable if cssOverride or color is provided
    if (StringUtils.isNotBlank(cssOverride)) {
        css = cssOverride;//  w  ww.  j  a  v  a 2 s  .com
    } else if (StringUtils.isNotBlank(color)) {
        css = createCss(color);
    }

    titlePrefix = xss.encodeForJSString(PropertiesUtil.toString(config.get(PROP_TITLE_PREFIX), "").toString());

    if (StringUtils.isNotBlank(css) || StringUtils.isNotBlank(titlePrefix)) {
        Dictionary<String, String> filterProps = new Hashtable<String, String>();
        filterProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_FILTER_PATTERN, "/");
        filterProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT,
                "(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=*)");
        filterRegistration = ctx.getBundleContext().registerService(Filter.class.getName(), this, filterProps);
    }

    excludedWCMModes = PropertiesUtil.toStringArray(config.get(PROP_EXCLUDED_WCMMODES),
            DEFAULT_EXCLUDED_WCMMODES);
}

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
 *//*from www  . jav a 2 s. c  om*/
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.redhat.jenkins.plugins.ci.messaging.FedMsgMessagingWorker.java

@Override
public boolean sendMessage(Run<?, ?> build, TaskListener listener, MessageUtils.MESSAGE_TYPE type, String props,
        String content) {//from  w  w w  .  j a v  a 2  s. com
    ZMQ.Context context = ZMQ.context(1);
    ZMQ.Socket sock = context.socket(ZMQ.PUB);
    sock.setLinger(0);
    log.fine("pub address: " + provider.getPubAddr());
    sock.connect(provider.getPubAddr());
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    HashMap<String, Object> message = new HashMap<String, Object>();
    message.put("CI_NAME", build.getParent().getName());
    message.put("CI_TYPE", type.getMessage());
    if (!build.isBuilding()) {
        message.put("CI_STATUS", (build.getResult() == Result.SUCCESS ? "passed" : "failed"));
    }

    StrSubstitutor sub = null;
    try {
        sub = new StrSubstitutor(build.getEnvironment(listener));
        if (props != null && !props.trim().equals("")) {
            Properties p = new Properties();
            p.load(new StringReader(props));
            @SuppressWarnings("unchecked")
            Enumeration<String> e = (Enumeration<String>) p.propertyNames();
            while (e.hasMoreElements()) {
                String key = e.nextElement();
                message.put(key, sub.replace(p.getProperty(key)));
            }
        }

        message.put(MESSAGECONTENTFIELD, sub.replace(content));

        FedmsgMessage blob = new FedmsgMessage();
        blob.setMsg(message);
        blob.setTopic(getTopic());
        blob.setTimestamp((new java.util.Date()).getTime() / 1000);

        sock.sendMore(blob.getTopic());
        sock.send(blob.toJson().toString());
        log.fine(blob.toJson().toString());

    } catch (Exception e) {
        log.log(Level.SEVERE, "Unhandled exception: ", e);
        return false;
    } finally {
        sock.close();
        context.term();
    }

    return true;
}

From source file:com.virtualparadigm.packman.processor.JPackageManager.java

public static boolean configure(File tempDir, File localConfigurationFile) {
    logger.info("PackageManager::configure()");
    boolean status = true;
    if (tempDir != null && localConfigurationFile != null) {
        Configuration configuration = null;
        try {//from   ww  w .j  av a 2s  . c o  m
            configuration = new PropertiesConfiguration(localConfigurationFile);
        } catch (ConfigurationException ce) {
            //dont want to error out completely if config file is not loaded
            ce.printStackTrace();
        }

        if (configuration != null && !configuration.isEmpty()) {
            Map<String, String> substitutionContext = JPackageManager.createSubstitutionContext(configuration);
            StrSubstitutor strSubstitutor = new StrSubstitutor(substitutionContext);
            String templateContent = null;
            long lastModified;

            Collection<File> patchFiles = FileUtils.listFiles(
                    new File(tempDir.getAbsolutePath() + "/" + JPackageManager.PATCH_DIR_NAME + "/"
                            + JPackageManager.PATCH_FILES_DIR_NAME),
                    TEMPLATE_SUFFIX_FILE_FILTER, DirectoryFileFilter.DIRECTORY);

            if (patchFiles != null) {
                for (File pfile : patchFiles) {
                    logger.debug("  processing patch fileset file: " + pfile.getAbsolutePath());
                    try {
                        lastModified = pfile.lastModified();
                        templateContent = FileUtils.readFileToString(pfile);
                        templateContent = strSubstitutor.replace(templateContent);
                        FileUtils.writeStringToFile(pfile, templateContent);
                        pfile.setLastModified(lastModified);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            Collection<File> scriptFiles = FileUtils.listFiles(
                    new File(tempDir.getAbsolutePath() + "/" + JPackageManager.AUTORUN_DIR_NAME),
                    TEMPLATE_SUFFIX_FILE_FILTER, DirectoryFileFilter.DIRECTORY);

            if (scriptFiles != null) {
                for (File scriptfile : scriptFiles) {
                    logger.debug("  processing script file: " + scriptfile.getAbsolutePath());
                    try {
                        lastModified = scriptfile.lastModified();
                        templateContent = FileUtils.readFileToString(scriptfile);
                        templateContent = strSubstitutor.replace(templateContent);
                        FileUtils.writeStringToFile(scriptfile, templateContent);
                        scriptfile.setLastModified(lastModified);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    return status;
}

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 ww .  j a  v  a2  s . c om
 * @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.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java

@Override
public boolean sendMessage(Run<?, ?> build, TaskListener listener, MessageUtils.MESSAGE_TYPE type, String props,
        String content) {/* w w w  .j  a v a  2 s  . co  m*/
    Connection connection = null;
    Session session = null;
    MessageProducer publisher = null;

    try {
        String ltopic = getTopic();
        if (provider.getAuthenticationMethod() != null && ltopic != null && provider.getBroker() != null) {
            ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory();
            connection = connectionFactory.createConnection();
            connection.start();

            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createTopic(ltopic);
            publisher = session.createProducer(destination);

            TextMessage message;
            message = session.createTextMessage("");
            message.setJMSType(JSON_TYPE);

            message.setStringProperty("CI_NAME", build.getParent().getName());
            message.setStringProperty("CI_TYPE", type.getMessage());
            if (!build.isBuilding()) {
                message.setStringProperty("CI_STATUS",
                        (build.getResult() == Result.SUCCESS ? "passed" : "failed"));
            }

            StrSubstitutor sub = new StrSubstitutor(build.getEnvironment(listener));

            if (props != null && !props.trim().equals("")) {
                Properties p = new Properties();
                p.load(new StringReader(props));
                @SuppressWarnings("unchecked")
                Enumeration<String> e = (Enumeration<String>) p.propertyNames();
                while (e.hasMoreElements()) {
                    String key = e.nextElement();
                    message.setStringProperty(key, sub.replace(p.getProperty(key)));
                }
            }

            message.setText(sub.replace(content));

            publisher.send(message);
            log.info("Sent " + type.toString() + " message for job '" + build.getParent().getName()
                    + "' to topic '" + ltopic + "':\n" + formatMessage(message));
        } else {
            log.severe("One or more of the following is invalid (null): user, password, topic, broker.");
            return false;
        }

    } catch (Exception e) {
        log.log(Level.SEVERE, "Unhandled exception in perform.", e);
    } finally {
        if (publisher != null) {
            try {
                publisher.close();
            } catch (JMSException e) {
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
            }
        }
    }
    return true;
}

From source file:com.spotify.helios.testing.TemporaryJob.java

private void outputDeployedMessage(final String host, final String containerId) {
    final StrSubstitutor subst = new StrSubstitutor(new ImmutableMap.Builder<String, Object>().put("host", host)
            .put("name", job.getId().getName()).put("version", job.getId().getVersion())
            .put("hash", job.getId().getHash()).put("job", job.toString()).put("image", job.getImage())
            .put("containerId", containerId).build());
    log.info("{}", subst.replace(jobDeployedMessageFormat));
}