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:ddf.test.itests.catalog.TestSpatial.java

private String substitutePagingParams(String rawCswRecord, int testNum, String identifier) {
    StrSubstitutor strSubstitutor = new StrSubstitutor(
            ImmutableMap.of("identifier", identifier, "testNum", "" + testNum));

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

From source file:com.ariht.maven.plugins.config.generator.ConfigGeneratorImpl.java

/**
 * Read properties from filter file and substitute template place-holders.
 *
 * Typical output is to .../filter-dir/filter-name-no-extension/template-dir/template.name
 *//*from w  w w.  j av  a  2 s . c  om*/
private void generateConfig(final FileInfo template, final FileInfo filter, final String outputBasePath,
        final StrSubstitutor strSubstitutor, final Map<String, Set<String>> missingPropertiesByFilename,
        final boolean missingPropertyFound) throws IOException, ConfigurationException, MojoFailureException {

    final String outputDirectory = createOutputDirectory(template, filter, outputBasePath);
    final String templateFilename = template.getFile().getName();
    final String outputFilename = FilenameUtils.separatorsToUnix(outputDirectory + templateFilename);

    if (configGeneratorParameters.isLogOutput()) {
        log.info("Creating : " + StringUtils.replace(outputFilename, outputBasePath, ""));
    } else if (log.isDebugEnabled()) {
        log.debug("Creating : " + String.valueOf(outputFilename));
    }
    log.debug("Applying filter : " + filter.toString() + " to template : " + template.toString());

    final String rawTemplate = FileUtils.readFileToString(template.getFile());
    final String processedTemplate = strSubstitutor.replace(rawTemplate);

    // No point in running regex against long strings if properties are all present
    if (missingPropertyFound) {
        checkForMissingProperties(filter.getFile().getAbsolutePath(), processedTemplate,
                missingPropertiesByFilename);
    }

    // Only write out the generated io if there were no errors or errors are specifically ignored
    if (StringUtils.isNotBlank(configGeneratorParameters.getEncoding())) {
        FileUtils.writeStringToFile(new File(outputFilename), processedTemplate,
                configGeneratorParameters.getEncoding());
    } else {
        FileUtils.writeStringToFile(new File(outputFilename), processedTemplate);
    }
}

From source file:com.impetus.ankush2.ganglia.GangliaDeployer.java

public String getConfigurationContent(String host, String confFileName) throws Exception {
    String fileContent = null;//from   ww w  .  jav a  2s  .  c o  m
    Map<String, Object> configValues = getConfigValueMap();

    String udpRecvChannel = "udp_recv_channel {\n port = " + configValues.get("port") + " \n } ";
    // 'udp_recv_channel' value for gmond.conf
    configValues.put("udp_recv_channel", "/*" + udpRecvChannel + "*/");

    if (((String) advanceConf.get(GangliaConstants.ClusterProperties.GMETAD_HOST)).equals(host)) {
        StringBuffer nodeIpPorts = new StringBuffer();
        // Preparing a String of nodeIp:port of gmetad node used in
        // data_source in gmetad.conf.
        nodeIpPorts.append(advanceConf.get(GangliaConstants.ClusterProperties.GMETAD_HOST))
                .append(Symbols.STR_COLON);
        nodeIpPorts.append(advanceConf.get(GangliaConstants.ClusterProperties.GANGLIA_PORT));
        // Putting the nodeIpsPorts string in map
        configValues.put("nodeIpsPorts", nodeIpPorts.toString());
        // On gmond nodes other than Gmetad node commenting
        // udp_recv_channel block
        configValues.put("udp_recv_channel", udpRecvChannel);
    }
    // Reading the content of the template file
    fileContent = FileUtil.readAsString(new File(confFileName));

    // Creating a string substitutor using config values map
    StrSubstitutor sub = new StrSubstitutor(configValues);

    // Replacing the config values key found in the file content with
    // respected values.
    return sub.replace(fileContent);
}

From source file:com.impetus.ankush2.ganglia.GangliaDeployer.java

public String getGmetadConfigurationContent(String host) throws Exception {
    String fileContent = null;/*from   www  .j  av  a 2  s .c o m*/
    String confFileName = (String) advanceConf.get(GangliaConstants.ClusterProperties.SERVER_CONF_FOLDER)
            + GangliaConstants.ConfigurationFiles.GMOND_CONF;

    Map<String, Object> configValues = getConfigValueMap();

    String udpRecvChannel = "udp_recv_channel {\n port = " + configValues.get("port") + " \n } ";
    configValues.put("udp_recv_channel", "/*" + udpRecvChannel + "*/");

    if (((String) advanceConf.get(GangliaConstants.ClusterProperties.GMETAD_HOST)).equals(host)) {
        confFileName = (String) advanceConf.get(GangliaConstants.ClusterProperties.SERVER_CONF_FOLDER)
                + GangliaConstants.ConfigurationFiles.GMETAD_CONF;
        StringBuffer nodeIpPorts = new StringBuffer();
        // Preparing a String of nodeIp:port of gmetad node.
        nodeIpPorts.append(advanceConf.get(GangliaConstants.ClusterProperties.GMETAD_HOST))
                .append(Symbols.STR_COLON);
        nodeIpPorts.append(advanceConf.get(GangliaConstants.ClusterProperties.GANGLIA_PORT));
        // Putting the nodeIpsPorts string in map
        configValues.put("nodeIpsPorts", nodeIpPorts.toString());
        // On gmond nodes other than Gmetad node commenting
        // udp_recv_channel block
        configValues.put("udp_recv_channel", udpRecvChannel);
    }
    // Reading the content of the template file
    fileContent = FileUtil.readAsString(new File(confFileName));

    // Creating a string substitutor using config values map
    StrSubstitutor sub = new StrSubstitutor(configValues);

    // Replacing the config values key found in the file content with
    // respected values.
    return sub.replace(fileContent);
}

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) {//from  ww w  . java2  s. c o 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:ome.services.blitz.repo.ManagedRepositoryI.java

/**
 * Turn the current template into a relative path. Makes use of the data
 * returned by {@link #replacementMap(Ice.Current)}.
 *
 * @param curr/*from w w  w .  j  a  v a2 s .c  o  m*/
 * @return
 */
protected String expandTemplate(final String template, EventContext ec) {

    if (template == null) {
        return ""; // EARLY EXIT.
    }

    final Map<String, String> map = replacementMap(ec);
    final StrSubstitutor strSubstitutor = new StrSubstitutor(new StrLookup() {
        @Override
        public String lookup(final String key) {
            return map.get(key);
        }
    }, "%", "%", '%');
    return strSubstitutor.replace(template);
}

From source file:org.aludratest.impl.log4testing.configuration.ReflectionUtil.java

private static String substituteSystemProperties(String param) {
    final StrLookup systemLookup = StrLookup.systemPropertiesLookup();
    final StrSubstitutor substitutor = new StrSubstitutor(systemLookup);
    return substitutor.replace(param);
}

From source file:org.apache.maven.plugin.cxx.GenerateMojo.java

protected Map<String, String> listResourceFolderContent(String path, Map valuesMap) {
    String location = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
    final File jarFile = new File(location);

    HashMap<String, String> resources = new HashMap<String, String>();
    StrSubstitutor substitutor = new StrSubstitutor(valuesMap);

    path = (StringUtils.isEmpty(path)) ? "" : path + "/";
    getLog().debug("listResourceFolderContent : " + location + ", sublocation : " + path);
    if (jarFile.isFile()) {
        getLog().debug("listResourceFolderContent : jar case");
        try {//from w  ww.j a  va2s  .  com
            final JarFile jar = new JarFile(jarFile);
            final Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                final String name = entries.nextElement().getName();
                if (name.startsWith(path)) {
                    String resourceFile = File.separator + name;
                    if (!(resourceFile.endsWith("/") || resourceFile.endsWith("\\"))) {
                        getLog().debug("resource entry = " + resourceFile);
                        String destFile = substitutor.replace(resourceFile);
                        getLog().debug("become entry = " + destFile);
                        resources.put(resourceFile, destFile);
                    }
                }
            }
            jar.close();
        } catch (IOException ex) {
            getLog().error("unable to list jar content : " + ex);
        }
    } else {
        getLog().debug("listResourceFolderContent : file case");
        //final URL url = Launcher.class.getResource("/" + path);
        final URL url = getClass().getResource("/" + path);
        if (url != null) {
            try {
                final File names = new File(url.toURI());
                Collection<File> entries = FileUtils.listFiles(names, TrueFileFilter.INSTANCE,
                        TrueFileFilter.INSTANCE);
                for (File name : entries) {
                    String resourceFile = name.getPath();
                    if (!(resourceFile.endsWith("/") || resourceFile.endsWith("\\"))) {
                        getLog().debug("resource entry = " + resourceFile);
                        String destFile = substitutor.replace(resourceFile);
                        destFile = destFile.replaceFirst(Pattern.quote(location), "/");
                        getLog().debug("become entry = " + destFile);
                        resources.put(resourceFile, destFile);
                    }
                }
            } catch (URISyntaxException ex) {
                // never happens
            }
        }
    }
    return resources;
}

From source file:org.apache.maven.plugin.cxx.GenerateMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    //Properties systemProperties = session.getSystemProperties();
    //Properties userProperties = session.getUserProperties();
    //Properties properties = session.getExecutionProperties();

    org.apache.maven.artifact.versioning.DefaultArtifactVersion defautCMakeVersion = new org.apache.maven.artifact.versioning.DefaultArtifactVersion(
            "3.0.0");
    org.apache.maven.artifact.versioning.DefaultArtifactVersion askedCMakeVersion = new org.apache.maven.artifact.versioning.DefaultArtifactVersion(
            cmakeMinVersion);//from  w  ww. ja  v  a2 s  . c o m
    boolean bCMake3OrAbove = (askedCMakeVersion.compareTo(defautCMakeVersion) >= 0);

    getLog().debug("CMake 3 or above asked (" + cmakeMinVersion + ") ? " + (bCMake3OrAbove ? "yes" : "no"));

    HashMap<String, String> valuesMap = new HashMap<String, String>();
    valuesMap.put("parentGroupId", parentGroupId);
    valuesMap.put("parentArtifactId", parentArtifactId);
    valuesMap.put("parentVersion", parentVersion);
    valuesMap.put("groupId", groupId);
    valuesMap.put("artifactId", artifactId);
    valuesMap.put("artifactName", artifactName);
    valuesMap.put("version", version);
    valuesMap.put("cmakeMinVersion", cmakeMinVersion);
    valuesMap.put("parentScope", bCMake3OrAbove ? "PARENT_SCOPE" : "");
    valuesMap.put("projectVersion", bCMake3OrAbove ? "VERSION ${TARGET_VERSION}" : "");
    valuesMap.put("scmConnection", "");

    //1/ search for properties
    // -DgroupId=fr.neticoa -DartifactName=QtUtils -DartifactId=qtutils -Dversion=1.0-SNAPSHOT

    if (StringUtils.isEmpty(archetypeArtifactId)) {
        throw new MojoExecutionException("archetypeArtifactId is empty ");
    }

    Map<String, String> resources = listResourceFolderContent(archetypeArtifactId, valuesMap);

    if (null == resources || resources.size() == 0) {
        throw new MojoExecutionException("Unable to find archetype : " + archetypeArtifactId);
    }
    //1.1/ search potential scm location of current dir
    // svn case
    SvnInfo basedirSvnInfo = SvnService.getSvnInfo(basedir, null, basedir.getAbsolutePath(), getLog(), true);
    if (basedirSvnInfo.isValide()) {
        valuesMap.put("scmConnection", "scm:svn:" + basedirSvnInfo.getSvnUrl());
    }
    // todo : handle other scm : git (git remote -v; git log --max-count=1), etc.

    //2/ unpack resource to destdir 
    getLog().info("archetype " + archetypeArtifactId + " has " + resources.entrySet().size() + " item(s)");
    getLog().info("basedir = " + basedir);

    StrSubstitutor substitutor = new StrSubstitutor(valuesMap, "$(", ")");
    String sExecutionDate = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss.SSS").format(new Date());
    for (Map.Entry<String, String> entry : resources.entrySet()) {
        String curRes = entry.getKey();
        String curDest = entry.getValue();
        InputStream resourceStream = null;
        resourceStream = getClass().getResourceAsStream(curRes);
        if (null == resourceStream) {
            try {
                resourceStream = new FileInputStream(new File(curRes));
            } catch (Exception e) {
                // handled later
                resourceStream = null;
            }
        }

        getLog().debug("resource stream to open : " + curRes);
        getLog().debug("destfile pattern : " + curDest);
        if (null != resourceStream) {
            String sRelativePath = curDest.replaceFirst(Pattern.quote(archetypeArtifactId + File.separator),
                    "");
            File newFile = new File(basedir + File.separator + sRelativePath);

            //3/ create empty dir struct; if needed using a descriptor 
            //create all non exists folders
            File newDirs = new File(newFile.getParent());
            if (Files.notExists(Paths.get(newDirs.getPath()))) {
                getLog().info("dirs to generate : " + newDirs.getAbsoluteFile());
                newDirs.mkdirs();
            }

            if (!newFile.getName().equals("empty.dir")) {
                getLog().info("file to generate : " + newFile.getAbsoluteFile());
                try {
                    if (!newFile.createNewFile()) {
                        // duplicate existing file
                        FileInputStream inStream = new FileInputStream(newFile);
                        File backFile = File.createTempFile(newFile.getName() + ".",
                                "." + sExecutionDate + ".back", newFile.getParentFile());
                        FileOutputStream outStream = new FileOutputStream(backFile);

                        IOUtils.copy(inStream, outStream);
                        // manage file times
                        //backFile.setLastModified(newFile.lastModified());
                        BasicFileAttributes attributesFrom = Files.getFileAttributeView(
                                Paths.get(newFile.getPath()), BasicFileAttributeView.class).readAttributes();
                        BasicFileAttributeView attributesToView = Files.getFileAttributeView(
                                Paths.get(backFile.getPath()), BasicFileAttributeView.class);
                        attributesToView.setTimes(attributesFrom.lastModifiedTime(),
                                attributesFrom.lastAccessTime(), attributesFrom.creationTime());

                        inStream.close();
                        outStream.close();
                    }
                    FileOutputStream outStream = new FileOutputStream(newFile);

                    //4/ variable substitution :
                    // change prefix and suffix to '$(' and ')'
                    // see https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/text/StrSubstitutor.html
                    String content = IOUtils.toString(resourceStream, "UTF8");
                    content = substitutor.replace(content);

                    //IOUtils.copy( resourceStream, outStream );
                    IOUtils.write(content, outStream, "UTF8");

                    outStream.close();
                    resourceStream.close();
                } catch (IOException e) {
                    getLog().error("File " + newFile.getAbsoluteFile() + " can't be created : " + e);
                }
            }
        } else {
            getLog().error("Unable to open resource " + curRes);
        }
    }
}

From source file:org.apache.maven.surefire.its.fixture.MavenLauncher.java

public OutputValidator executeCurrentGoals() {

    String userLocalRepo = System.getProperty("user.localRepository");
    String testBuildDirectory = System.getProperty("testBuildDirectory");
    boolean useInterpolatedSettings = Boolean.getBoolean("useInterpolatedSettings");

    try {/*from   w w  w.j a  v  a  2s  . c o m*/
        if (useInterpolatedSettings) {
            File interpolatedSettings = new File(testBuildDirectory, "interpolated-settings");

            if (!interpolatedSettings.exists()) {
                // hack "a la" invoker plugin to download dependencies from local repo
                // and not download from central

                Map<String, String> values = new HashMap<String, String>(1);
                values.put("localRepositoryUrl", toUrl(userLocalRepo));
                StrSubstitutor strSubstitutor = new StrSubstitutor(values);

                String fileContent = FileUtils.fileRead(new File(testBuildDirectory, "settings.xml"));

                String filtered = strSubstitutor.replace(fileContent);

                FileUtils.fileWrite(interpolatedSettings.getAbsolutePath(), filtered);

            }

            addCliOption("-s " + interpolatedSettings.getCanonicalPath());
        }
        getVerifier().setCliOptions(cliOptions);

        getVerifier().executeGoals(goals, envvars);
        return getValidator();
    } catch (IOException e) {
        throw new SurefireVerifierException(e.getMessage(), e);
    } catch (VerificationException e) {
        throw new SurefireVerifierException(e.getMessage(), e);
    } finally {
        getVerifier().resetStreams();
    }
}