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.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));
}

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  w w .ja va 2s . com*/
        } 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.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));
    }/* w  w w  .  j a va2 s .co m*/
}

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 {//  w  ww . j  a va 2 s .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.googlecode.jatl.MarkupBuilder.java

private String expand(String text) {
    StrSubstitutor s = new StrSubstitutor(bindings);
    return s.replace(text);
}

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

public static boolean configureCommons(File tempDir, Configuration configuration) {
    logger.info("PackageManager::configure()");
    boolean status = true;
    if (tempDir != null && configuration != null && !configuration.isEmpty()) {

        Map<String, String> substitutionContext = JPackageManagerOld.createSubstitutionContext(configuration);
        StrSubstitutor strSubstitutor = new StrSubstitutor(substitutionContext);
        String templateContent = null;
        long lastModified;

        Collection<File> patchFiles = FileUtils.listFiles(
                new File(tempDir.getAbsolutePath() + "/" + JPackageManagerOld.PATCH_DIR_NAME + "/"
                        + JPackageManagerOld.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();
                }/*  www.j  a va  2  s. c o  m*/
            }
        }

        Collection<File> scriptFiles = FileUtils.listFiles(
                new File(tempDir.getAbsolutePath() + "/" + JPackageManagerOld.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.freedomotic.plugins.devices.push.Push.java

@Override
protected void onEvent(EventTemplate e) {
    try {/*ww w.  j  a  v a 2s.c  o  m*/
        MessageEvent event = (MessageEvent) e;
        int t = tupleMap.get(event.getDefaultDestination());

        URIBuilder ub = new URIBuilder()
                .setScheme(configuration.getTuples().getStringProperty(t, "scheme", "http"))
                .setHost(configuration.getTuples().getStringProperty(t, "host", "localhost"))
                .setPort(configuration.getTuples().getIntProperty(t, "port",
                        configuration.getTuples().getStringProperty(t, "scheme", "http")
                                .equalsIgnoreCase("https") ? 443 : 80))
                .setPath(configuration.getTuples().getStringProperty(t, "path", "/"));

        // prepare substitution tokens
        HashMap<String, String> valuesMap = new HashMap<>();
        Iterator<Statement> it = event.getPayload().iterator();
        while (it.hasNext()) {
            Statement s = it.next();
            if (s.getOperand().equalsIgnoreCase(Statement.EQUALS)) {
                valuesMap.put(s.getAttribute(), s.getValue());
            }
        }
        StrSubstitutor sub = new StrSubstitutor(valuesMap);

        // add extra parameters
        for (String key : configuration.getTuples().getTuple(t).keySet()) {
            if (key.startsWith("param.")) {
                String toBeReplaced = configuration.getTuples().getStringProperty(t, key, "");
                // replace default string with the one provided into payload
                if (event.getPayload().getStatementValue(key) != null
                        && !event.getPayload().getStatementValue(key).isEmpty()) {
                    toBeReplaced = event.getPayload().getStatementValue(key);
                }
                // do substitutions
                String resolvedString = sub.replace(toBeReplaced);

                ub.setParameter(key.substring(6), resolvedString);
            }
        }

        // override default message (with variable substitution) if a new one is specified in MessageEvent.text
        if (event.getText() != null & !event.getText().isEmpty()) {
            ub.setParameter(configuration.getTuples().getStringProperty(t, "mapMessageToParam", "message"),
                    sub.replace(event.getText()));
        }

        LOG.info(ub.build().toString());

        HttpClientBuilder hcb = HttpClientBuilder.create();
        HttpClient client = hcb.build();

        // set http method to use
        HttpRequestBase request;
        if (configuration.getTuples().getStringProperty(t, "method", "get").equalsIgnoreCase("POST")) {
            request = new HttpPost(ub.build());
        } else {
            request = new HttpGet(ub.build());
        }

        int responseCode = client.execute(request).getStatusLine().getStatusCode();
        LOG.info("Push request got code: " + responseCode);

    } catch (URISyntaxException | IOException ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
}

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) {//ww w.ja  v  a 2s . c om
    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:ddf.test.itests.catalog.TestSpatial.java

private String getPagingMaxRecordsQuery(int maxRecords) {
    String rawCswQuery = savedCswQueries.get("CswPagingTestLikeQuery");
    StrSubstitutor strSubstitutor = new StrSubstitutor(ImmutableMap.of("maxRecords", "" + maxRecords));

    strSubstitutor.setVariablePrefix(RESOURCE_VARIABLE_DELIMETER);
    strSubstitutor.setVariableSuffix(RESOURCE_VARIABLE_DELIMETER);
    return strSubstitutor.replace(rawCswQuery);
}

From source file:net.firejack.platform.generate.tools.Render.java

public String replace(String value) {
    Map<String, String> map = settings.get();
    StrSubstitutor substitutor = parser.get();
    if (substitutor == null && map != null) {
        substitutor = new StrSubstitutor(map);
        parser.set(substitutor);/*from  w w w. ja  va2 s  .co  m*/
        return substitutor.replace(value);
    } else if (map != null && substitutor != null) {
        return substitutor.replace(value);
    }
    return value;
}