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.eclipse.skalli.services.extension.PropertyMapper.java

/**
 * Converts a string by applying the given <code>template</code>, if it matches
 * the given regular expression. The properties of the entity, if specified, are mapped to
 * placeholders of the form <tt>${propertyName}</tt>.
 * Properties of extensions of the entity, if any, are mapped to placeholders of the form
 * <tt>${extension.propertyName}</tt>.
 * The custom properties, if specified, are mapped to placeholders with their respective keys,
 * e.g. property with key <tt>"prop"</tt> is mapped to the placeholder <tt>${prop}</tt>.
 * The placeholders <tt>${1},${2},...</tt> provide the {@link MatchResult#group(int) groups}
 * of the match result./*from  w w w.  ja  v a 2s. c  o  m*/
 *
 * @param s  the string to check.
 * @param pattern the regular expression to apply.
 * @param template  the template to use for the mapping.
 * @param entity  any (extensible) entity.
 * @param properties  additional properties.
 *
 * @return the mapped string, or <code>null</code>, if the string did not match the
 * given regular expression.
 */
public static String convert(String s, Pattern pattern, String template, EntityBase entity,
        Map<String, Object> properties) {
    if (s == null || pattern == null) {
        return null;
    }
    Matcher matcher = pattern.matcher(s);
    if (!matcher.matches()) {
        return null;
    }
    if (properties == null) {
        properties = new HashMap<String, Object>();
    }
    // put the project ID as property ${0}
    if (entity instanceof Project) {
        properties.put("0", ((Project) entity).getProjectId()); //$NON-NLS-1$
    }
    // put the groups found by the matcher as properties ${1}, ${2}, ...
    for (int i = 1; i <= matcher.groupCount(); i++) {
        properties.put(Integer.toString(i), matcher.group(i));
    }
    StrLookup propertyResolver = new PropertyLookup(entity, properties);
    StrSubstitutor subst = new StrSubstitutor(propertyResolver);
    return subst.replace(template);
}

From source file:org.eclipse.skalli.view.internal.filter.ext.GitGerritFilter.java

@SuppressWarnings("nls")
String getScmLocation(GerritServerConfig gerritConfig, String repository, Project project, User user) {
    Map<String, String> parameters = new HashMap<String, String>();
    String protocol = gerritConfig.getProtocol();
    if (StringUtils.isBlank(protocol)) {
        protocol = "git";
    }//  w  w  w . j  a  v a  2  s.  c  om
    parameters.put("protocol", protocol);
    parameters.put("host", gerritConfig.getHost());
    String port = gerritConfig.getPort();
    if (StringUtils.isBlank(port)) {
        port = Integer.toString(GerritClient.DEFAULT_PORT);
    }
    parameters.put("port", port);
    parameters.put("repository", repository);
    if (StringUtils.isNotBlank(gerritConfig.getParent())) {
        parameters.put("parent", gerritConfig.getParent());
    }
    if (StringUtils.isNotBlank(gerritConfig.getBranch())) {
        parameters.put("branch", gerritConfig.getBranch());
    }
    parameters.put("user", user.getDisplayName());
    parameters.put("userId", user.getUserId());

    String scmTemplate = gerritConfig.getScmTemplate();
    if (StringUtils.isBlank(scmTemplate)) {
        scmTemplate = DEFAULT_SCM_TEMPLATE;
    }

    PropertyLookup propertyLookup = new PropertyLookup(parameters);
    propertyLookup.putAllProperties(project, "");
    propertyLookup.putAllProperties(user, "user");
    StrSubstitutor substitutor = new StrSubstitutor(propertyLookup);
    return substitutor.replace(scmTemplate);
}

From source file:org.eclipse.skalli.view.internal.filter.ext.GitGerritFilter.java

@SuppressWarnings("nls")
String getDescription(String descriptionTemplate, String baseUrl, Project project, User user,
        Map<String, String> properties) {
    Map<String, String> parameters = new HashMap<String, String>();
    parameters.putAll(properties);/*  w w  w  . j  av a2s.c  o  m*/
    parameters.put("user", user.getDisplayName());
    parameters.put("userId", user.getUserId());
    parameters.put("link", baseUrl + Consts.URL_PROJECTS + "/" + project.getProjectId());
    if (StringUtils.isBlank(descriptionTemplate)) {
        descriptionTemplate = DEFAULT_DESCRIPTION;
    }
    PropertyLookup propertyLookup = new PropertyLookup(parameters);
    propertyLookup.putAllProperties(project, "");
    propertyLookup.putAllProperties(user, "user");
    StrSubstitutor substitutor = new StrSubstitutor(propertyLookup);
    return substitutor.replace(descriptionTemplate);
}

From source file:org.eclipse.skalli.view.internal.servlet.StaticContentServlet.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*from  w w w.  ja  v  a  2 s.co m*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestURI = request.getRequestURI();
    if (requestURI.startsWith("/content/")) {
        String path = request.getPathInfo();
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        InputStream in = getContent(path);
        if (in != null) {
            response.setContentType(getContentType(path));
            try {
                OutputStream out = response.getOutputStream();
                IOUtils.copy(in, out);
            } finally {
                IOUtils.closeQuietly(in);
            }
            return;
        }
    } else if (requestURI.startsWith("/schemas/")) {
        // otherwise check the bundles for a matching schema resource
        URL schema = RestUtils.findSchemaResource(requestURI);
        if (schema != null) {
            response.setContentType(getContentType(requestURI));
            InputStream in = schema.openStream();
            OutputStream out = response.getOutputStream();
            try {
                resolveIncludes(in, out);
            } catch (Exception ex) {
                throw new IOException("Failed to resolve schema resource", ex);
            } finally {
                IOUtils.closeQuietly(in);
            }
            return;
        }
    } else if (requestURI.equals(Consts.URL_SEARCH_PLUGIN)) {
        URL searchPluginXML = getSearchPluginXML();
        if (searchPluginXML != null) {
            response.setContentType("application/opensearchdescription+xml"); //$NON-NLS-1$
            Properties properties = new Properties();
            properties.put(Consts.ATTRIBUTE_SEARCH_PLUGIN_TITLE,
                    request.getAttribute(Consts.ATTRIBUTE_SEARCH_PLUGIN_TITLE));
            properties.put(Consts.ATTRIBUTE_SEARCH_PLUGIN_DESCRIPTION,
                    request.getAttribute(Consts.ATTRIBUTE_SEARCH_PLUGIN_DESCRIPTION));
            properties.put(Consts.ATTRIBUTE_WEBLOCATOR,
                    StringUtils.removeEnd(request.getRequestURL().toString(), requestURI));
            InputStream in = searchPluginXML.openStream();
            try {
                String content = IOUtils.toString(in, "UTF-8"); //$NON-NLS-1$
                StrSubstitutor subst = new StrSubstitutor(properties);
                content = subst.replace(content);
                OutputStream out = response.getOutputStream();
                IOUtils.write(content, out, "UTF-8"); //$NON-NLS-1$
            } finally {
                IOUtils.closeQuietly(in);
            }
            return;
        }
    }
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
}

From source file:org.eurekastreams.server.action.execution.notification.notifier.NotificationMessageBuilderHelper.java

/**
 * Returns a variable-substituted version of the activity's body.
 * //from www  .  ja  v a2 s. c  o  m
 * @param activity
 *            Activity.
 * @param context
 *            Velocity context.
 * @return Activity body text.
 */
public String resolveActivityBody(final ActivityDTO activity, final Context context) {
    StrSubstitutor transform = new StrSubstitutor(new StrLookup() {
        @Override
        public String lookup(final String variableName) {
            if ("ACTORNAME".equals(variableName)) {
                return activity.getActor().getDisplayName();
            } else {
                return null;
            }
        }
    }, VARIABLE_START_MARKER, VARIABLE_END_MARKER, StrSubstitutor.DEFAULT_ESCAPE);
    String result = transform.replace(activity.getBaseObjectProperties().get("content"));
    return result;
}

From source file:org.eurekastreams.server.action.execution.notification.TemplateEmailBuilder.java

/**
 * Builds the email message from the notification and initial properties.
 * /*from ww w .jav a2 s.  c o m*/
 * @param notif
 *            Notification for which to build message.
 * @param invocationProperties
 *            Initial properties to use.
 * @param inMessage
 *            Email message.
 * @throws Exception
 *             On error.
 */
public void build(final NotificationDTO notif, final Map<String, String> invocationProperties,
        final MimeMessage inMessage) throws Exception {
    // -- build properties --

    Map<String, String> properties = new HashMap<String, String>();

    // from system settings
    SystemSettings systemSettings = systemSettingsMapper.execute(null);
    properties.put("settings.sitelabel", systemSettings.getSiteLabel());
    properties.put("settings.support.email", systemSettings.getSupportEmailAddress());
    properties.put("settings.support.phone", systemSettings.getSupportPhoneNumber());
    properties.put("settings.support.name", systemSettings.getSupportStreamGroupDisplayName());
    properties.put("settings.support.uniqueid", systemSettings.getSupportStreamGroupShortName());

    // from upstream builders
    if (invocationProperties != null) {
        properties.putAll(invocationProperties);
    }

    // from system configuration
    if (extraProperties != null) {
        properties.putAll(extraProperties);
    }

    // actor
    if (notif.getActorId() > 0) {
        properties.put("actor.id", Long.toString(notif.getActorId()));
        properties.put("actor.accountid", notif.getActorAccountId());
        properties.put("actor.name", notif.getActorName());
    }

    // activity
    if (notif.getActivityId() > 0) {
        properties.put("activity.id", Long.toString(notif.getActivityId()));
        String type = activityTypeDisplayNameOverrides.get(notif.getActivityType());
        if (type == null) {
            type = notif.getActivityType().name().toLowerCase();
        }
        properties.put("activity.type", type);
    }

    // destination
    if (notif.getDestinationId() > 0) {
        properties.put("dest.id", Long.toString(notif.getDestinationId()));
        properties.put("dest.type", notif.getDestinationType().name());
        properties.put("dest.uniqueid", notif.getDestinationUniqueId());
        properties.put("dest.name", notif.getDestinationName());
        properties.put("dest.page", entityPageNames.get(notif.getDestinationType()));
    }

    // auxiliary
    if (notif.getAuxiliaryType() != null) {
        properties.put("aux.type", notif.getAuxiliaryType().name());
        properties.put("aux.uniqueid", notif.getAuxiliaryUniqueId());
        properties.put("aux.name", notif.getAuxiliaryName());
        properties.put("aux.page", entityPageNames.get(notif.getAuxiliaryType()));
    }

    // -- build email --

    // build and set the email parts
    StrSubstitutor transform = new StrSubstitutor(properties, "$(", ")");
    emailer.setSubject(inMessage, transform.replace(subjectTemplate));
    emailer.setTextBody(inMessage, transform.replace(textBodyTemplate));

    transform.setVariableResolver(new HtmlEncodingLookup(transform.getVariableResolver()));
    emailer.setHtmlBody(inMessage, transform.replace(htmlBodyTemplate));

    // look up recipients and put as email recipients
    List<PersonModelView> recipients = peopleMapper.execute(notif.getRecipientIds());
    if (recipients.size() == 1) {
        emailer.setTo(inMessage, recipients.get(0).getEmail());
    } else {
        emailer.setBcc(inMessage, EmailerFactory.buildEmailList(recipients));
    }
}

From source file:org.jobscheduler.dashboard.installer.db.Databases.java

public String getUrl(String serverName, String port, String databaseName) {
    Map<String, String> valuesMap = new HashMap<String, String>();
    valuesMap.put("serverName", serverName);
    valuesMap.put("port", port);
    valuesMap.put("databaseName", databaseName);
    StrSubstitutor sub = new StrSubstitutor(valuesMap);
    return sub.replace(urlFormat);
}

From source file:org.jobscheduler.dashboard.installer.JDBCManager.java

public void createApplicationPropertiesFile(String installPath, CommandLine cmd) throws IOException {
    Properties valuesMap = new Properties();
    valuesMap.put(SERVER_NAME, cmd.getOptionValue(SERVER_NAME));
    valuesMap.put("url", Databases.valueOf(cmd.getOptionValue(DB).toUpperCase()).getUrl(
            cmd.getOptionValue(SERVER_NAME), cmd.getOptionValue(PORT), cmd.getOptionValue(DATABASE_NAME)));
    valuesMap.put(DB_USER_NAME, cmd.getOptionValue(DB_USER_NAME));
    valuesMap.put(DB_USER_PASSWORD, cmd.getOptionValue(DB_USER_PASSWORD));

    StrSubstitutor sub = new StrSubstitutor(valuesMap);

    String applicationJobSchedulerYaml = IOUtils
            .toString(this.getClass().getResourceAsStream("/application-jobscheduler-template.yml"), "UTF-8");
    String translatedApplicationJobSchedulerYaml = sub.replace(applicationJobSchedulerYaml);
    // Create config directory file
    File configDir = new File(installPath, "config");
    if (!configDir.exists())
        configDir.mkdir();/*  w  w w  . ja  v a 2s. co  m*/
    FileUtils.write(new File(configDir, "application-jobscheduler.yml"), translatedApplicationJobSchedulerYaml);

}

From source file:org.klco.email2html.OutputWriter.java

/**
 * Writes the message to a html file. The name of the HTML file is generated
 * from the date of the message./*from w w w  . ja  va  2 s  .  c om*/
 * 
 * @param emailMessage
 *            the message to save to a file
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public void writeHTML(EmailMessage emailMessage) throws IOException {
    log.trace("writeHTML");

    Map<String, Object> params = emailMessage.toMap();
    params.put("attachmentFolder",
            config.getImagesSubDir() + File.separator + FILE_DATE_FORMAT.format(emailMessage.getSentDate()));
    if (config.getHookObj() != null) {
        config.getHookObj().beforeWrite(emailMessage, params);
    }

    File messageFolder = new File(outputDir.getAbsolutePath() + File.separator + config.getMessagesSubDir());
    if (!messageFolder.exists()) {
        log.debug("Creating messages folder");
        messageFolder.mkdirs();
    }

    StrSubstitutor sub = new StrSubstitutor(params);
    String fileContent = sub.replace(template);

    String name = String.format(config.getFileNameFormat(), emailMessage.getSentDate(),
            toPath(emailMessage.getSubject()));
    File messageFile = new File(
            outputDir.getAbsolutePath() + File.separator + config.getMessagesSubDir() + File.separator + name);

    OutputStream os = null;
    try {
        os = new FileOutputStream(messageFile);
        IOUtils.write(fileContent, new FileOutputStream(messageFile));
        log.debug("Writing message to file {}", messageFile.getAbsolutePath());
    } finally {
        IOUtils.closeQuietly(os);
    }
    if (config.getHookObj() != null) {
        config.getHookObj().afterWrite(emailMessage, params, messageFile);
    }
}

From source file:org.kuali.rice.core.impl.config.property.ConfigParserImpl.java

/**
 * Parses a single config location//  w  w  w  .  j a  v  a  2 s  .  co m
 * @param params the current parameter map
 * @param location the location to parse
 * @param subs a StrSubstitutor used to substitute variable tokens
 * @throws IOException
 */
protected void parse(LinkedHashMap<String, Object> params, String location, StrSubstitutor subs, int depth)
        throws IOException {
    InputStream configStream = RiceUtilities.getResourceAsStream(location);
    if (configStream == null) {
        LOG.warn("###############################");
        LOG.warn("#");
        LOG.warn("# Configuration file '" + location + "' not found!");
        LOG.warn("#");
        LOG.warn("###############################");
        return;
    }

    final String prefix = StringUtils.repeat(INDENT, depth);
    LOG.info(prefix + "+ Parsing config: " + location);

    Document doc;
    try {
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(configStream);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Contents of config " + location + ": \n" + XmlJotter.jotNode(doc, true));
        }
    } catch (SAXException se) {
        IOException ioe = new IOException("Error parsing config resource: " + location);
        ioe.initCause(se);
        throw ioe;
    } catch (ParserConfigurationException pce) {
        IOException ioe = new IOException("Unable to obtain document builder");
        ioe.initCause(pce);
        throw ioe;
    } finally {
        configStream.close();
    }

    Element root = doc.getDocumentElement();
    // ignore the actual type of the document element for now
    // so that plugin descriptors can be parsed
    NodeList list = root.getChildNodes();
    StringBuilder content = new StringBuilder();
    for (int i = 0; i < list.getLength(); i++) {
        Node node = list.item(i);
        if (node.getNodeType() != Node.ELEMENT_NODE)
            continue;
        if (!PARAM_NAME.equals(node.getNodeName())) {
            LOG.warn("Encountered non-param config node: " + node.getNodeName());
            continue;
        }
        Element param = (Element) node;
        String name = param.getAttribute(NAME_ATTR);
        if (name == null) {
            LOG.error("Unnamed parameter in config resource '" + location + "': " + XmlJotter.jotNode(param));
            continue;
        }
        Boolean override = Boolean.TRUE;
        String overrideVal = param.getAttribute(OVERRIDE_ATTR);
        if (!StringUtils.isEmpty(overrideVal)) {
            override = Boolean.valueOf(overrideVal);
        }

        content.setLength(0);
        // accumulate all content (preserving any XML content)
        getNodeValue(name, location, param, content);
        String value = subs.replace(content);
        if (LOG.isDebugEnabled()) {
            LOG.debug(
                    prefix + INDENT + "* " + name + "=[" + ConfigLogger.getDisplaySafeValue(name, value) + "]");
        }

        if (IMPORT_NAME.equals(name)) {
            // what is this...we don't follow a string with this substring in it? i.e. if the value does not
            // resolve then don't try to follow it (it won't find it anyway; this is the case for any path
            // with unresolved params...)?
            if (!value.contains(ALTERNATE_BUILD_LOCATION_KEY)) {
                parse(params, value, subs, depth + 1);
            }
        } else {
            if (Boolean.valueOf(param.getAttribute(RANDOM_ATTR))) {
                // this is a special type of property whose value is a randomly generated number in the range specified
                value = String.valueOf(generateRandomInteger(value));
            }
            setParam(params, override, name, value, prefix + INDENT);
        }
    }
    LOG.info(prefix + "- Parsed config: " + location);
}