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:org.kuali.rice.kew.util.Utilities.java

/**
 * Performs variable substitution on the specified string, replacing variables specified like ${name}
 * with the value of the corresponding config parameter obtained from the current context Config object.
 * This version of the method also takes an application id to qualify the parameter.
 * @param applicationId the application id to use for qualifying the parameter
 * @param string the string on which to perform variable substitution
 * @return a string with any variables substituted with configuration parameter values
 *//*from w  ww .j  av a2s.  c o  m*/
public static String substituteConfigParameters(String applicationId, String string) {
    StrSubstitutor sub = new StrSubstitutor(new ParameterStrLookup(applicationId));
    return sub.replace(string);
}

From source file:org.mycore.frontend.cli.MCRCommandLineInterface.java

/**
 * Expands variables in a command./*from   www . ja  v  a 2 s .c o m*/
 * Replaces any variables in form ${propertyName} to the value defined by {@link MCRConfiguration#getString(String)}.
 * If the property is not defined not variable replacement takes place.
 * @param command a CLI command that should be expanded
 * @return expanded command
 */
public static String expandCommand(final String command) {
    StrSubstitutor strSubstitutor = new StrSubstitutor(MCRConfiguration.instance().getPropertiesMap());
    String expandedCommand = strSubstitutor.replace(command);
    if (!expandedCommand.equals(command)) {
        LOGGER.info(command + " --> " + expandedCommand);
    }
    return expandedCommand;
}

From source file:org.obiba.mica.core.service.MailService.java

public String getSubject(String subjectFormat, Map<String, String> ctx, String defaultSubject) {
    StrSubstitutor sub = new StrSubstitutor(ctx, "${", "}");

    String temp = Optional.ofNullable(subjectFormat) //
            .filter(s -> !s.isEmpty()) //
            .orElse(defaultSubject);/*from  w  w w .ja  v  a2s . c o m*/

    return sub.replace(temp);
}

From source file:org.pentaho.reporting.platform.plugin.output.PaginationControlWrapper.java

public static void write(final OutputStream stream, final IReportContent content) throws IOException {

    final StringBuilder builder = new StringBuilder();

    synchronized (TEMPLATE_PATH) {
        if (StringUtil.isEmpty(pageableHtml)) {
            pageableHtml = getSolutionDirFileContent(TEMPLATE_PATH);
        }//from  w  ww . ja v  a2  s  .c o m
    }

    final String pages = getPageArray(content, builder);

    final StrSubstitutor substitutor = new StrSubstitutor(Collections.singletonMap("pages", pages));
    final String filledTemplate = substitutor.replace(pageableHtml);

    stream.write(filledTemplate.getBytes());
    stream.flush();

}

From source file:org.signserver.anttasks.PostProcessModulesTask.java

/**
 * Replacer for the postprocess-jar Ant macro.
 * /* w  w w  .j ava 2s .com*/
 * @param replaceincludes Ant list of all files in the jar to replace in
 * @param src Source jar file
 * @param destfile Destination jar file
 * @param properties Properties to replace from
 * @param self The Task (used for logging)
 * @throws IOException in case of error
 */
protected void replaceInJar(String replaceincludes, String src, String destfile, Map properties, Task self)
        throws IOException {
    try {
        self.log("Replace " + replaceincludes + " in " + src + " to " + destfile, Project.MSG_VERBOSE);

        File srcFile = new File(src);
        if (!srcFile.exists()) {
            throw new FileNotFoundException(srcFile.getAbsolutePath());
        }

        // Expand properties of all files in replaceIncludes
        HashSet<String> replaceFiles = new HashSet<String>();
        String[] rfiles = replaceincludes.split(",");
        for (int i = 0; i < rfiles.length; i++) {
            rfiles[i] = rfiles[i].trim();
        }
        replaceFiles.addAll(Arrays.asList(rfiles));
        self.log("Files to replace: " + replaceFiles, Project.MSG_INFO);

        // Open source zip file
        ZipFile zipSrc = new ZipFile(srcFile);
        ZipOutputStream zipDest = new ZipOutputStream(new FileOutputStream(destfile));

        // For each entry in the source file copy them to dest file and postprocess if necessary
        Enumeration<? extends ZipEntry> entries = zipSrc.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            String name = entry.getName();

            if (entry.isDirectory()) {
                // Just put the directory
                zipDest.putNextEntry(entry);
            } else {
                // If we should postprocess the entry
                if (replaceFiles.contains(name)) {
                    name += (" [REPLACE]");
                    self.log(name, Project.MSG_VERBOSE);

                    // Create a new zip entry for the file
                    ZipEntry newEntry = new ZipEntry(entry.getName());
                    newEntry.setComment(entry.getComment());
                    newEntry.setExtra(entry.getExtra());
                    zipDest.putNextEntry(newEntry);

                    // Read the old document
                    StringBuffer oldDocument = stringBufferFromFile(zipSrc.getInputStream(entry));
                    self.log("Before replace ********\n" + oldDocument.toString() + "\n", Project.MSG_DEBUG);

                    // Do properties substitution
                    StrSubstitutor sub = new StrSubstitutor(properties);
                    StringBuffer newerDocument = commentReplacement(oldDocument, properties);
                    String newDocument = sub.replace(newerDocument);
                    self.log("After replace ********\n" + newDocument.toString() + "\n", Project.MSG_DEBUG);

                    // Write the new document
                    byte[] newBytes = newDocument.getBytes("UTF-8");
                    entry.setSize(newBytes.length);
                    copy(new ByteArrayInputStream(newBytes), zipDest);
                } else {
                    // Just copy the entry to dest zip file
                    name += (" []");
                    self.log(name, Project.MSG_VERBOSE);
                    zipDest.putNextEntry(entry);
                    copy(zipSrc.getInputStream(entry), zipDest);
                }
                zipDest.closeEntry();
            }
        }
        zipSrc.close();
        zipDest.close();
    } catch (IOException ex) {
        throw new BuildException(ex);
    }
}

From source file:org.torproject.metrics.web.TableServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestURI = request.getRequestURI();
    if (requestURI == null || !requestURI.endsWith(".html")) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;/*from  w  ww.java2  s.  c om*/
    }
    String requestedId = requestURI.substring(requestURI.contains("/") ? requestURI.lastIndexOf("/") + 1 : 0,
            requestURI.length() - 5);
    if (!this.idsByType.containsKey("Table") || !this.idsByType.get("Table").contains(requestedId)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    request.setAttribute("id", requestedId);
    request.setAttribute("title", this.titles.get(requestedId));
    request.setAttribute("description", this.descriptions.get(requestedId));
    request.setAttribute("tableheader", this.tableHeaders.get(requestedId));
    request.setAttribute("data", this.data.get(requestedId));
    request.setAttribute("related", this.related.get(requestedId));
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date defaultEndDate = new Date();
    Date defaultStartDate = new Date(defaultEndDate.getTime() - 90L * 24L * 60L * 60L * 1000L);
    if (this.parameters.containsKey(requestedId)) {
        Map<String, String[]> checkedParameters = TableParameterChecker.getInstance()
                .checkParameters(requestedId, request.getParameterMap());
        for (String parameter : this.parameters.get(requestedId)) {
            if (parameter.equals("start") || parameter.equals("end")) {
                String[] requestParameter;
                if (checkedParameters != null && checkedParameters.containsKey(parameter)) {
                    requestParameter = checkedParameters.get(parameter);
                } else {
                    requestParameter = new String[] {
                            dateFormat.format(parameter.equals("start") ? defaultStartDate : defaultEndDate) };
                }
                request.setAttribute(parameter, requestParameter);
            }
        }
    }
    List<Map<String, String>> tableData = rObjectGenerator.generateTable(requestedId, request.getParameterMap(),
            true);
    List<List<String>> formattedTableData = new ArrayList<List<String>>();
    String[] contents = this.tableCellFormats.get(requestedId);
    for (Map<String, String> row : tableData) {
        List<String> formattedRow = new ArrayList<String>();
        StrSubstitutor sub = new StrSubstitutor(row);
        for (String con : contents) {
            formattedRow.add(sub.replace(con));
        }
        formattedTableData.add(formattedRow);
    }
    request.setAttribute("tabledata", formattedTableData);
    request.getRequestDispatcher("WEB-INF/table.jsp").forward(request, response);
}

From source file:org.usergrid.management.EmailFlowTest.java

public void testProperty(String propertyName, boolean containsSubstitution) {

    String propertyValue = properties.getProperty(propertyName);
    assertTrue(propertyName + " was not found", isNotBlank(propertyValue));
    logger.info(propertyName + "=" + propertyValue);

    if (containsSubstitution) {
        Map<String, String> valuesMap = new HashMap<String, String>();
        valuesMap.put("reset_url", "test-url");
        valuesMap.put("organization_name", "test-org");
        valuesMap.put("activation_url", "test-url");
        valuesMap.put("confirmation_url", "test-url");
        valuesMap.put("user_email", "test-email");
        valuesMap.put("pin", "test-pin");
        StrSubstitutor sub = new StrSubstitutor(valuesMap);
        String resolvedString = sub.replace(propertyValue);
        assertNotSame(propertyValue, resolvedString);
    }/* w ww.ja  va 2 s .  com*/
}

From source file:org.wso2.carbon.ui.filters.CSRFProtector.java

private String getInjectingJS(String token) {
    Map<String, Object> valuesMap = new HashMap<>();
    valuesMap.put(CSRFConstants.JSTemplateToken.CSRF_TOKEN_NAME, CSRFConstants.CSRF_TOKEN);
    valuesMap.put(CSRFConstants.JSTemplateToken.CSRF_TOKEN_VALUE, token);

    StrSubstitutor substitutor = new StrSubstitutor(valuesMap);
    return substitutor.replace(jsTemplate.toString());
}

From source file:ro.nextreports.server.web.themes.ThemesManager.java

private void generateStyle(String templateFile, String generatedFilePath) {
    InputStream styleTemplateStream = getClass().getResourceAsStream(templateFile);
    InputStream propertiesStream = getClass().getResourceAsStream(getPropertiesFile(theme));
    try {/* w  ww. j  av  a 2  s  .  com*/
        String styleTemplate = IOUtils.toString(styleTemplateStream);
        StrSubstitutor sub = new StrSubstitutor(createValues(propertiesStream));
        String resolvedString = sub.replace(styleTemplate);
        ServletContext context = NextServerApplication.get().getServletContext();
        String fileName = context.getRealPath(generatedFilePath);
        //         URI outputURI = new URI(("file:///"+ URIUtil.encodePath(fileName)));                      
        //         File styleFile = new File(outputURI);
        File styleFile = new File(fileName);
        FileUtils.writeStringToFile(styleFile, resolvedString);
        LOG.info("Generated style file " + templateFile + " in folder " + styleFile.getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        closeInputStream(styleTemplateStream);
        closeInputStream(propertiesStream);
    }
}

From source file:sos.scheduler.misc.ParameterSubstitutor.java

public String replaceEnvVars(String source) {
    StrSubstitutor strSubstitutor = new StrSubstitutor(System.getenv());
    return strSubstitutor.replace(source);
}