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: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  w  w.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.
 * /*from w  w  w.  j ava  2s . c  o m*/
 * @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.sventon.util.HTMLCreator.java

/**
 * Creates a string containing the details for a given revision.
 *
 * @param bodyTemplate   Body template string.
 * @param logEntry       log entry revision.
 * @param baseURL        Application base URL.
 * @param repositoryName Repository name.
 * @param response       Response, null if n/a.
 * @param dateFormat     Date formatter instance.
 * @return Result/* w  w  w.  jav a  2 s.  c  o  m*/
 */
public static String createRevisionDetailBody(final String bodyTemplate, final LogEntry logEntry,
        final String baseURL, final RepositoryName repositoryName, final DateFormat dateFormat,
        final HttpServletResponse response) {

    final Map<String, String> valueMap = new HashMap<String, String>();

    int added = 0;
    int modified = 0;
    int replaced = 0;
    int deleted = 0;

    //noinspection unchecked
    final SortedSet<ChangedPath> latestChangedPaths = logEntry.getChangedPaths();

    for (final ChangedPath entryPath : latestChangedPaths) {
        final ChangeType type = entryPath.getType();
        switch (type) {
        case ADDED:
            added++;
            break;
        case MODIFIED:
            modified++;
            break;
        case REPLACED:
            replaced++;
            break;
        case DELETED:
            deleted++;
            break;
        default:
            throw new IllegalArgumentException("Unsupported type: " + type);
        }
    }
    final String logMessage = WebUtils.nl2br(StringEscapeUtils.escapeHtml(logEntry.getMessage())); //TODO: Parse to apply Bugtraq link
    final String author = logEntry.getAuthor();

    valueMap.put(ADDED_COUNT_KEY, Matcher.quoteReplacement(String.valueOf(added)));
    valueMap.put(MODIFIED_COUNT_KEY, Matcher.quoteReplacement(String.valueOf(modified)));
    valueMap.put(REPLACED_COUNT_KEY, Matcher.quoteReplacement(String.valueOf(replaced)));
    valueMap.put(DELETED_COUNT_KEY, Matcher.quoteReplacement(String.valueOf(deleted)));
    valueMap.put(LOG_MESSAGE_KEY, Matcher.quoteReplacement(StringUtils.trimToEmpty(logMessage)));
    valueMap.put(AUTHOR_KEY, Matcher.quoteReplacement(StringUtils.trimToEmpty(author)));
    valueMap.put(DATE_KEY, dateFormat.format(logEntry.getDate()));
    valueMap.put(CHANGED_PATHS_KEY,
            Matcher.quoteReplacement(HTMLCreator.createChangedPathsTable(logEntry.getChangedPaths(),
                    logEntry.getRevision(), null, baseURL, repositoryName, false, false, response)));

    return new StrSubstitutor(valueMap).replace(bodyTemplate);
}

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 w w.  ja v a 2  s .  c o  m*/
    }
    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.cassandra.ManagementServiceImpl.java

private String emailMsg(Map<String, String> values, String propertyName) {
    return new StrSubstitutor(values).replace(properties.getProperty(propertyName));
}

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);
    }//from   ww w  .j  a  va 2s.  co m
}

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 {// www .j  av  a 2 s  .co m
        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);
}

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

public String replace(final String source) {
    StrSubstitutor strSubstitutor = new StrSubstitutor(keylist);
    return strSubstitutor.replace(source);
}